hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
cbbf71f481103279183d9f713a9ec90c1d136e25
280
cc
C++
CSE-1305/class-practice/exception-handling/setTerminate.cc
imrande/university-courses
e10af95d1e6bfc2f0a0e467e732f9b39bf8d99c1
[ "MIT" ]
null
null
null
CSE-1305/class-practice/exception-handling/setTerminate.cc
imrande/university-courses
e10af95d1e6bfc2f0a0e467e732f9b39bf8d99c1
[ "MIT" ]
null
null
null
CSE-1305/class-practice/exception-handling/setTerminate.cc
imrande/university-courses
e10af95d1e6bfc2f0a0e467e732f9b39bf8d99c1
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void my_terminateFunction(){ cout << "Uncaught error handle" <<endl; } int main(){ is_terminate(my_terminateFunction); try { throw 5; } catch(char x){ cout << "Testing Purpose" <<endl; } return 0; }
15.555556
42
0.607143
imrande
cbc0c05ba53e0d28b2d17504ee3360b3a1f1e423
1,455
cpp
C++
trees/priority_queue.cpp
triffon/sdp-2015-16
bb15cea4b4cad7791d82f55d106c3975b287af4e
[ "MIT" ]
3
2015-10-12T14:02:43.000Z
2021-06-22T13:02:48.000Z
trees/priority_queue.cpp
triffon/sdp-2015-16
bb15cea4b4cad7791d82f55d106c3975b287af4e
[ "MIT" ]
null
null
null
trees/priority_queue.cpp
triffon/sdp-2015-16
bb15cea4b4cad7791d82f55d106c3975b287af4e
[ "MIT" ]
null
null
null
/* * priority_queue.cpp * * Created on: 4.12.2015 г. * Author: trifon */ #include "bintree.cpp" template <typename T> class PriorityQueue : BinaryTree<T> { private: using P = BinaryTreePosition<T>; void insertAndSiftUp(P pos, T const& x) { if (pos) { P newpos = (x % 2) ? -pos : +pos; insertAndSiftUp(newpos, x); // sift up if (*newpos > *pos) swap(*newpos, *pos); } else { // insert BinaryTree<T>::assignFrom(pos, BinaryTree<T>(x)); } } P findLeaf(P pos) const { if (!pos || (!-pos && !+pos)) return pos; if (!-pos) return findLeaf(+pos); if (!+pos) return findLeaf(-pos); return findLeaf((*pos % 2) ? -pos : +pos); } P maxChild(P pos) { if (!-pos) return +pos; if (!+pos) return -pos; return *-pos > *+pos ? -pos : +pos; } void siftDown(P pos) { if (pos) { P maxcpos = maxChild(pos); if (maxcpos && *pos < *maxcpos) swap(*maxcpos, *pos); siftDown(maxcpos); } } public: bool empty() const { return BinaryTree<T>::empty(); } T head() { return *BinaryTree<T>::root(); } void enqueue_prioritized(T const& x) { insertAndSiftUp(BinaryTree<T>::root(), x); } T dequeue_highest() { P rpos = BinaryTree<T>::root(); T result = head(); P pos = findLeaf(rpos); swap(*pos,*rpos); BinaryTree<T>::deleteAt(pos); siftDown(rpos); return result; } void printDOT(char const* filename) { ::printDOT((BinaryTree<T>&)(*this), filename); } };
17.962963
54
0.58488
triffon
cbc111cee1890731f510c5be40358b4a87132982
5,155
cc
C++
src/developer/memory/monitor/tests/metrics_unittest.cc
winksaville/Fuchsia
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
[ "BSD-3-Clause" ]
3
2020-08-02T04:46:18.000Z
2020-08-07T10:10:53.000Z
src/developer/memory/monitor/tests/metrics_unittest.cc
winksaville/Fuchsia
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
[ "BSD-3-Clause" ]
null
null
null
src/developer/memory/monitor/tests/metrics_unittest.cc
winksaville/Fuchsia
a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f
[ "BSD-3-Clause" ]
1
2020-08-07T10:11:49.000Z
2020-08-07T10:11:49.000Z
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/developer/memory/monitor/metrics.h" #include <lib/gtest/real_loop_fixture.h> #include <gtest/gtest.h> #include <src/cobalt/bin/testing/fake_logger.h> #include "src/developer/memory/metrics/capture.h" #include "src/developer/memory/metrics/tests/test_utils.h" using namespace memory; using cobalt_registry::MemoryMetricDimensionBucket; using fuchsia::cobalt::EventPayload; namespace monitor { namespace { class MetricsUnitTest : public gtest::RealLoopFixture {}; TEST_F(MetricsUnitTest, All) { CaptureSupplier cs({{ .vmos = { {.koid = 1, .name = "", .committed_bytes = 1}, {.koid = 2, .name = "magma_create_buffer", .committed_bytes = 2}, {.koid = 3, .name = "Sysmem:buf", .committed_bytes = 3}, {.koid = 4, .name = "test", .committed_bytes = 4}, {.koid = 5, .name = "test", .committed_bytes = 5}, {.koid = 6, .name = "test", .committed_bytes = 6}, {.koid = 7, .name = "test", .committed_bytes = 7}, {.koid = 8, .name = "test", .committed_bytes = 8}, {.koid = 9, .name = "test", .committed_bytes = 9}, {.koid = 10, .name = "test", .committed_bytes = 10}, {.koid = 11, .name = "test", .committed_bytes = 11}, {.koid = 12, .name = "test", .committed_bytes = 12}, {.koid = 13, .name = "test", .committed_bytes = 13}, {.koid = 14, .name = "test", .committed_bytes = 14}, {.koid = 15, .name = "test", .committed_bytes = 15}, {.koid = 16, .name = "test", .committed_bytes = 16}, }, .processes = { {.koid = 1, .name = "bin/bootsvc", .vmos = {1}}, {.koid = 2, .name = "test", .vmos = {2}}, {.koid = 3, .name = "devhost:sys", .vmos = {3}}, {.koid = 4, .name = "/boot/bin/minfs", .vmos = {4}}, {.koid = 5, .name = "/boot/bin/blobfs", .vmos = {5}}, {.koid = 6, .name = "io.flutter.product_runner.aot", .vmos = {6}}, {.koid = 7, .name = "/pkg/web_engine_exe", .vmos = {7}}, {.koid = 8, .name = "kronk.cmx", .vmos = {8}}, {.koid = 9, .name = "scenic.cmx", .vmos = {9}}, {.koid = 10, .name = "devhost:pdev:05:00:f", .vmos = {10}}, {.koid = 11, .name = "netstack.cmx", .vmos = {11}}, {.koid = 12, .name = "amber.cmx", .vmos = {12}}, {.koid = 13, .name = "pkgfs", .vmos = {13}}, {.koid = 14, .name = "cast_agent.cmx", .vmos = {14}}, {.koid = 15, .name = "chromium.cmx", .vmos = {15}}, {.koid = 16, .name = "fshost", .vmos = {16}}, }, }}); cobalt::FakeLogger_Sync logger; Metrics m(zx::msec(10), dispatcher(), &logger, [&cs](Capture* c, CaptureLevel l) { return cs.GetCapture(c, l); }); RunLoopUntil([&cs] { return cs.empty(); }); EXPECT_EQ(16U, logger.logged_events().size()); for (const auto& cobalt_event : logger.logged_events()) { EXPECT_EQ(1u, cobalt_event.metric_id); ASSERT_EQ(1u, cobalt_event.event_codes.size()); EXPECT_EQ(EventPayload::Tag::kMemoryBytesUsed, cobalt_event.payload.Which()); switch (cobalt_event.event_codes[0]) { case MemoryMetricDimensionBucket::Fshost: EXPECT_EQ(16u, cobalt_event.payload.memory_bytes_used()); break; case MemoryMetricDimensionBucket::Web: EXPECT_EQ(15u, cobalt_event.payload.memory_bytes_used()); break; case MemoryMetricDimensionBucket::Cast: EXPECT_EQ(14u, cobalt_event.payload.memory_bytes_used()); break; default: EXPECT_TRUE(cobalt_event.payload.memory_bytes_used() < 14); break; } } } TEST_F(MetricsUnitTest, One) { CaptureSupplier cs({{ .vmos = { {.koid = 1, .name = "", .committed_bytes = 1}, }, .processes = { {.koid = 1, .name = "bin/bootsvc", .vmos = {1}}, }, }}); cobalt::FakeLogger_Sync logger; Metrics m(zx::msec(10), dispatcher(), &logger, [&cs](Capture* c, CaptureLevel l) { return cs.GetCapture(c, l); }); RunLoopUntil([&cs] { return cs.empty(); }); EXPECT_EQ(1U, logger.event_count()); } TEST_F(MetricsUnitTest, Undigested) { CaptureSupplier cs({{ .vmos = { {.koid = 1, .name = "", .committed_bytes = 1}, {.koid = 2, .name = "test", .committed_bytes = 2}, }, .processes = { {.koid = 1, .name = "bin/bootsvc", .vmos = {1}}, {.koid = 2, .name = "test", .vmos = {2}}, }, }}); cobalt::FakeLogger_Sync logger; Metrics m(zx::msec(10), dispatcher(), &logger, [&cs](Capture* c, CaptureLevel l) { return cs.GetCapture(c, l); }); RunLoopUntil([&cs] { return cs.empty(); }); EXPECT_EQ(2U, logger.event_count()); } } // namespace } // namespace monitor
38.185185
81
0.537342
winksaville
cbc52e1b7326324fe9d676e4322614e29ea60d75
1,128
cpp
C++
leetcode_solutions/others/leetcode_492.cpp
EatAllBugs/leetcode_cpp
3f5c58b32f0c3b115a706dd172c3fb72e4cc67ba
[ "MIT" ]
4
2021-12-07T19:39:03.000Z
2021-12-23T09:15:08.000Z
leetcode_solutions/others/leetcode_492.cpp
EatAllBugs/leetcode_cpp
3f5c58b32f0c3b115a706dd172c3fb72e4cc67ba
[ "MIT" ]
null
null
null
leetcode_solutions/others/leetcode_492.cpp
EatAllBugs/leetcode_cpp
3f5c58b32f0c3b115a706dd172c3fb72e4cc67ba
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<limits.h> #include<algorithm> #include<numeric> #include<unordered_set> #include<cmath> using namespace std; /* 作为一位web开发者, 懂得怎样去规划一个页面的尺寸是很重要的。 现给定一个具体的矩形页面面积,你的任务是设计一个长度为 L 和宽度为 W 且满足以下要求的矩形的页面。要求: 1. 你设计的矩形页面必须等于给定的目标面积。 2. 宽度 W 不应大于长度 L,换言之,要求 L >= W 。 3. 长度 L 和宽度 W 之间的差距应当尽可能小。 你需要按顺序输出你设计的页面的长度 L 和宽度 W。 示例: 输入: 4 输出: [2, 2] 解释: 目标面积是 4, 所有可能的构造方案有 [1,4], [2,2], [4,1]。 但是根据要求2,[1,4] 不符合要求; 根据要求3,[2,2] 比 [4,1] 更能符合要求. 所以输出长度 L 为 2, 宽度 W 为 2。 说明: 给定的面积不大于 10,000,000 且为正整数。 你设计的页面的长度和宽度必须都是正整数。 */ class Solution { public: vector<int> constructRectangle(int area) { int mid = sqrt(area); int w = mid, l = mid; vector<int> ans; while (w > 0 && l < area && w <= l) { if (area % w == 0 && l * w == area) { vector<int> ans = {l, w}; return ans; } else if (l * w < area) { l++; } else if (l * w > area) { w--; } } return ans; } }; int main() { int g = 10000000; Solution app; vector<int> ans = app.constructRectangle(g); cout << ans[0] << endl; cout << ans[1] << endl; return 0; }
20.888889
87
0.590426
EatAllBugs
cbc810cfeb0de84d45088c9b9ecb861e9f28e79d
586
cpp
C++
zoe/src/zoe/display/Game/Sprite.cpp
NudelErde/zoe
456e38bba86058f006a7c0fd5168af5039714c6c
[ "MIT" ]
7
2019-12-16T20:23:39.000Z
2020-10-26T08:46:12.000Z
zoe/src/zoe/display/Game/Sprite.cpp
NudelErde/zoe
456e38bba86058f006a7c0fd5168af5039714c6c
[ "MIT" ]
13
2020-01-13T20:19:06.000Z
2021-09-10T21:23:52.000Z
zoe/src/zoe/display/Game/Sprite.cpp
NudelErde/zoe
456e38bba86058f006a7c0fd5168af5039714c6c
[ "MIT" ]
7
2019-12-29T22:46:23.000Z
2020-07-15T19:56:32.000Z
// // Created by Florian on 10.07.2020. // #include "Sprite.h" namespace Zoe{ void Sprite::onDraw(const Camera& camera) {} void Sprite::onUpdate(double time) {} void Sprite::onInputEvent(Event &event) {} void Sprite::fill(const XMLNode &node) { if(node.attributes.count("x")>0){ position.x = std::stof(node.attributes.at("x")); } if(node.attributes.count("y")>0){ position.y = std::stof(node.attributes.at("y")); } if(node.attributes.count("z")>0){ position.z = std::stof(node.attributes.at("z")); } } void Sprite::postFill() { } }
20.206897
56
0.616041
NudelErde
cbcdd815e81296e1dfc4d91a622d85790312973c
1,545
cxx
C++
svc_kube_vision_opencvplus/dependencies/cmake-3.4.1/Source/cmCPackPropertiesGenerator.cxx
lucmichalski/kube-vproxy
c7cc0edbcbcd07a48f0fc48b9457eae693b76688
[ "Apache-2.0" ]
3
2018-06-22T07:55:51.000Z
2021-06-21T19:18:16.000Z
svc_kube_vision_opencvplus/dependencies/cmake-3.4.1/Source/cmCPackPropertiesGenerator.cxx
lucmichalski/kube-vproxy
c7cc0edbcbcd07a48f0fc48b9457eae693b76688
[ "Apache-2.0" ]
null
null
null
svc_kube_vision_opencvplus/dependencies/cmake-3.4.1/Source/cmCPackPropertiesGenerator.cxx
lucmichalski/kube-vproxy
c7cc0edbcbcd07a48f0fc48b9457eae693b76688
[ "Apache-2.0" ]
1
2020-11-04T04:56:50.000Z
2020-11-04T04:56:50.000Z
#include "cmCPackPropertiesGenerator.h" #include "cmOutputConverter.h" #include "cmLocalGenerator.h" cmCPackPropertiesGenerator::cmCPackPropertiesGenerator( cmLocalGenerator* lg, cmInstalledFile const& installedFile, std::vector<std::string> const& configurations): cmScriptGenerator("CPACK_BUILD_CONFIG", configurations), LG(lg), InstalledFile(installedFile) { this->ActionsPerConfig = true; } void cmCPackPropertiesGenerator::GenerateScriptForConfig(std::ostream& os, const std::string& config, Indent const& indent) { std::string const& expandedFileName = this->InstalledFile.GetNameExpression().Evaluate(this->LG->GetMakefile(), config); cmInstalledFile::PropertyMapType const& properties = this->InstalledFile.GetProperties(); for(cmInstalledFile::PropertyMapType::const_iterator i = properties.begin(); i != properties.end(); ++i) { std::string const& name = i->first; cmInstalledFile::Property const& property = i->second; os << indent << "set_property(INSTALL " << cmOutputConverter::EscapeForCMake(expandedFileName) << " PROPERTY " << cmOutputConverter::EscapeForCMake(name); for(cmInstalledFile::ExpressionVectorType::const_iterator j = property.ValueExpressions.begin(); j != property.ValueExpressions.end(); ++j) { std::string value = (*j)->Evaluate(LG->GetMakefile(), config); os << " " << cmOutputConverter::EscapeForCMake(value); } os << ")\n"; } }
32.1875
79
0.682201
lucmichalski
cbce4032e94199fa3e8d2c448f4278774f45f7fa
2,692
cpp
C++
sources/http/response.cpp
deguangchow/NetFlex
8fbdee6601dcbaa5be12e467bee82f1f648cd63b
[ "MIT" ]
null
null
null
sources/http/response.cpp
deguangchow/NetFlex
8fbdee6601dcbaa5be12e467bee82f1f648cd63b
[ "MIT" ]
null
null
null
sources/http/response.cpp
deguangchow/NetFlex
8fbdee6601dcbaa5be12e467bee82f1f648cd63b
[ "MIT" ]
null
null
null
// The MIT License (MIT) // // Copyright (c) 2015-2017 Simon Ninon <simon.ninon@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation 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 <netflex/http/response.hpp> #include <netflex/misc/output.hpp> namespace netflex { namespace http { //! //! ctor & dtor //! response::response(void) : m_sHttpVersion("HTTP/1.1") , m_uStatusCode(200) , m_sReason("OK") {} //! //! convert response to http packet //! std::string response::to_http_packet(void) const { return misc::status_line_to_http_packet(m_sHttpVersion, m_uStatusCode, m_sReason) + misc::header_list_to_http_packet(m_mapHeaders) + m_sBody; } //! //! status line //! const std::string& response::get_http_version(void) const { return m_sHttpVersion; } unsigned int response::get_status_code(void) const { return m_uStatusCode; } const std::string& response::get_reason_phase(void) const { return m_sReason; } void response::set_http_version(const std::string& version) { m_sHttpVersion = version; } void response::set_status_code(unsigned int code) { m_uStatusCode = code; } void response::set_reason_phrase(const std::string& reason) { m_sReason = reason; } //! //! headers //! const header_list_t& response::get_headers(void) const { return m_mapHeaders; } void response::add_header(const header& header) { m_mapHeaders[header.field_name] = header.field_value; } void response::set_headers(const header_list_t& headers) { m_mapHeaders = headers; } //! //! body //! const std::string& response::get_body(void) const { return m_sBody; } void response::set_body(const std::string& body) { m_sBody = body; } } // namespace http } // namespace netflex
22.813559
85
0.737741
deguangchow
cbcedc2d6774b39d58401968d95377fe3e199385
2,039
cpp
C++
components/common/tests/streams/wxf_writer.cpp
untgames/funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
7
2016-03-30T17:00:39.000Z
2017-03-27T16:04:04.000Z
components/common/tests/streams/wxf_writer.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2017-11-21T11:25:49.000Z
2018-09-20T17:59:27.000Z
components/common/tests/streams/wxf_writer.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2016-11-29T15:18:40.000Z
2017-03-27T16:04:08.000Z
#include "shared.h" using namespace math; typedef stl::set<stl::string> MySet; int main () { printf ("Results of wxf_writer_test:\n"); try { int array [] = {1,2,3,4,5,6,7,8,9,10}; MySet set; set.insert ("world"); set.insert ("sunny"); set.insert ("hello"); WxfWriter writer (&dump, 2, 8); writer.WriteComment ("This file is auto generated\nDo not modify it by hand"); writer.BeginFrame ("test1"); writer.WriteComment ("Scalar types serialization"); writer.BeginFrame ("scalar"); writer.Write ("int", -1); writer.Write ("size_t", (unsigned int)-1); writer.Write ("float", math::constf::pi); writer.Write ("double", math::constd::pi); writer.Write ("long_double", math::constants<long double>::pi); writer.Write ("string", "Hello world"); writer.Write ("char", 'x'); writer.EndFrame (); writer.WriteComment ("Mathlib types serialization"); writer.BeginFrame ("mathlib"); writer.Write ("vec3f", vec3f (1.1f, 2.2f, 3.3f)); writer.Write ("mat4f", mat4f (1.0f)); writer.Write ("quatd", quatd (math::constd::pi)); writer.EndFrame (); writer.WriteComment ("Intervals serialization"); writer.BeginFrame ("intervals"); writer.Write ("int_array", xtl::make_iterator_range (sizeof (array)/sizeof (*array), array)); writer.Write ("stl_set", xtl::make_iterator_range (set)); writer.EndFrame (); writer.EndFrame (); writer.BeginFrame ("test2", vec4f (1.0f)); writer.WriteComment ("This frame need to test block-comments in subframes\nDon't worry about it:)"); writer.Write ("bool_flag"); // writer.EndFrame (); //н⮠ᤥ« ­® бЇҐжЁ «м­®! writer.Flush (); writer.Write ("wrong tag"); } catch (std::exception& exception) { printf ("exception: %s\n", exception.what ()); } return 0; }
32.887097
105
0.567435
untgames
cbd03db1164e9615f0994bd2b3d87714d016b12c
4,313
cc
C++
remove-invalid-parentheses.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
remove-invalid-parentheses.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
remove-invalid-parentheses.cc
ArCan314/leetcode
8e22790dc2f34f5cf2892741ff4e5d492bb6d0dd
[ "MIT" ]
null
null
null
#include <string> #include <bitset> #include <vector> #include <cctype> #include <unordered_set> #include <deque> #include <iostream> class Solution { public: bool check(const std::string &s, const std::bitset<25> &valid) const { int stack_count = 0; for (int i = 0; i < s.size(); i++) { if (valid[i]) { if (s[i] == '(') stack_count++; else if (stack_count && s[i] == ')') stack_count--; else if (std::isalpha(s[i])) continue; else return false; } } return stack_count == 0; } std::string decode(const std::string &s, const std::bitset<25> &valid) const { std::string res; for (int i = 0; i < s.size(); i++) { if (valid[i]) res.push_back(s[i]); } return res; } char diff(const std::string &s, const std::bitset<25> &valid) const { int lp = 0, rp = 0; for (int i = 0; i < s.size(); i++) { lp += (valid[i] && s[i] == '('); rp += (valid[i] && s[i] == ')'); } return lp - rp; } std::vector<std::string> removeInvalidParentheses(std::string s) { // std::unordered_set<std::bitset<25>> has; // { // int pos = 0; // for (int i = 0; i < s.size(); i++) // if (!std::isalpha(s[i])) // s[pos++] = s[i]; // while (s.size() != pos) // s.pop_back(); // } std::unordered_set<std::string> str_has; std::vector<std::pair<char, std::bitset<25>>> expand, rooling; std::vector<char> diff_res, diff_rooling; std::vector<std::bitset<25>> res_store; expand.emplace_back(0, -1); diff_res.push_back(diff(s, -1)); str_has.insert(s); // std::cout << diff_res[0] << std::endl; // has.insert(expand.back().second); // for (int i = s.size(); i < 25; i++) // expand.back().set(i, false); while (expand.size()) { rooling.clear(); diff_rooling.clear(); // for (int i = 0; i < 10 && i < expand.size(); i++) // std::cout << "[\"" << decode(s, expand[i].second) << "\", " << diff_res[i] << "], "; // std::cout << std::endl; for (int i = 0; i < expand.size(); i++) { if (!diff_res[i] && check(s, expand[i].second)) { res_store.emplace_back(expand[i].second); } else { if (res_store.size()) continue; for (int j = diff_res[i] ? expand[i].first : 0; j < s.size(); j++) { if (std::isalpha(s[j]) || (diff_res[i] > 0 && s[j] != '(') || (diff_res[i] < 0 && s[j] != ')')) continue; // std::cout << decode(s, expand[i].second) << "\t\t" << diff_res[i] << std::endl; expand[i].second.flip(j); std::string temp = decode(s, expand[i].second); if (!str_has.count(temp)) { str_has.insert(std::move(temp)); rooling.emplace_back(j + 1, expand[i].second); diff_rooling.push_back(diff_res[i] - (s[j] == '(' ? 1 : -1)); } expand[i].second.flip(j); } } } if (res_store.size()) break; expand.swap(rooling); diff_res.swap(diff_rooling); } std::unordered_set<std::string> res; for (int i = 0; i < res_store.size(); i++) { std::string temp; for (int j = 0; j < s.size(); j++) if (res_store[i][j]) temp.push_back(s[j]); res.insert(std::move(temp)); } return {res.begin(), res.end()}; } };
31.253623
106
0.392534
ArCan314
cbd0590bc3e83d3833293f7f960910798fa68b3c
768
cpp
C++
src/PhaserNativeEvent.cpp
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
null
null
null
src/PhaserNativeEvent.cpp
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
null
null
null
src/PhaserNativeEvent.cpp
mchiasson/PhaserNative
f867454602c395484bf730a7c43b9c586c102ac2
[ "MIT" ]
1
2019-01-25T13:55:25.000Z
2019-01-25T13:55:25.000Z
#include "PhaserNativeEvent.h" std::vector<SDL_Event*> PhaserNativeEvent::Timers; uint32_t PhaserNativeEvent::Timeout = 0; uint32_t PhaserNativeEvent::ImageDecoded = 0; uint32_t PhaserNativeEvent::RequestAnimationFrame = 0; uint32_t PhaserNativeEvent::XHR = 0; std::vector<JSC::Object> PhaserNativeEvent::keyDownListeners; std::vector<JSC::Object> PhaserNativeEvent::keyUpListeners; std::vector<JSC::Object> PhaserNativeEvent::mouseMoveListeners; std::vector<JSC::Object> PhaserNativeEvent::mouseDownListeners; std::vector<JSC::Object> PhaserNativeEvent::mouseUpListeners; std::vector<JSC::Object> PhaserNativeEvent::touchStartListeners; std::vector<JSC::Object> PhaserNativeEvent::touchMoveListeners; std::vector<JSC::Object> PhaserNativeEvent::touchEndListeners;
42.666667
64
0.81901
mchiasson
cbd0cecbc1a854b0bac056d1739c3577662fc95e
1,155
cpp
C++
C++/problem0594.cpp
1050669722/LeetCode-Answers
c8f4d1ccaac09cda63b60d75144335347b06dc81
[ "MIT" ]
null
null
null
C++/problem0594.cpp
1050669722/LeetCode-Answers
c8f4d1ccaac09cda63b60d75144335347b06dc81
[ "MIT" ]
null
null
null
C++/problem0594.cpp
1050669722/LeetCode-Answers
c8f4d1ccaac09cda63b60d75144335347b06dc81
[ "MIT" ]
null
null
null
#include <iostream> #include <iomanip> #include <vector> #include <map> #include <set> #include <algorithm> #include <cmath> #include <ctime> #include <cstdlib> #include <windows.h> #include <string> #include <numeric> using namespace std; class Solution { public: int findLHS(vector<int>& nums) { map<int, int> d; vector<int>::iterator it; for (it = nums.begin(); it < nums.end(); ++it) { // if (d.count(*it)) // { // d[*it]++; // } // else // { // d[*it] = 1; // } d[*it]++; } map<int, int>::iterator iter; int ans = 0; for (iter = d.begin(); iter != d.end(); ++iter) { cout << iter->first << ' ' << iter->second << endl; if (d.count(iter->first-1)) { ans = max(ans, iter->second+d[iter->first-1]); } } return ans; } }; int main() { vector<int> nums {1,3,2,2,5,2,3,7}; Solution solu; int ans = solu.findLHS(nums); cout << ans << endl; return 0; }
21
63
0.442424
1050669722
cbd41b49a3e4434c897b2a025ec33f574c3b1996
1,782
cpp
C++
src/map.cpp
johnpeterflynn/visual-orb-slam
443427895ab513b78d164ff31da1a55efd1cc289
[ "BSD-3-Clause" ]
3
2020-11-18T09:15:22.000Z
2021-12-30T19:40:09.000Z
src/map.cpp
ParikaGoel/orb-slam
6eb93da00ef3e29ca7c4addd92941ccf95746b48
[ "BSD-3-Clause" ]
null
null
null
src/map.cpp
ParikaGoel/orb-slam
6eb93da00ef3e29ca7c4addd92941ccf95746b48
[ "BSD-3-Clause" ]
null
null
null
#include "map.h" Map::Map() {} std::vector<Landmark*> Map::getAllLandmarks() { std::unique_lock<std::mutex>(mutexMap); return std::vector<Landmark*>(mLandmarks.begin(), mLandmarks.end()); } void Map::addLandmark(Landmark* lm) { std::unique_lock<std::mutex>(mutexMap); mLandmarks.push_back(lm); } void Map::addLandmarks(std::vector<Landmark*> landmarks) { std::unique_lock<std::mutex>(mutexMap); for (auto& lm : landmarks) { mLandmarks.push_back(lm); } } void Map::eraseLandmark(Landmark* lm) { std::unique_lock<std::mutex>(mutexMap); oldLandmarks.push_back(lm); std::vector<Landmark*>::iterator index = std::find(mLandmarks.begin(), mLandmarks.end(), lm); if (index != mLandmarks.end()) { mLandmarks.erase(index); } } void Map::eraseAllLandmarks() { std::unique_lock<std::mutex>(mutexMap); mLandmarks.clear(); } size_t Map::noOfLandmarks() { std::unique_lock<std::mutex>(mutexMap); return mLandmarks.size(); } std::vector<Keyframe*> Map::getAllKeyframes() { std::unique_lock<std::mutex>(mutexMap); return std::vector<Keyframe*>(mKeyframes.begin(), mKeyframes.end()); } void Map::addKeyframe(Keyframe* kf) { std::unique_lock<std::mutex>(mutexMap); mKeyframes.push_back(kf); } void Map::eraseKeyframe(Keyframe* kf) { std::unique_lock<std::mutex>(mutexMap); oldKeyframes.push_back(kf); std::vector<Keyframe*>::iterator index = std::find(mKeyframes.begin(), mKeyframes.end(), kf); if (index != mKeyframes.end()) { mKeyframes.erase(index); } } size_t Map::noOfKeyframes() { std::unique_lock<std::mutex>(mutexMap); return mKeyframes.size(); } // Assumption: The first keyframe is never culled. Keyframe* Map::getFirstKeyframe() { std::unique_lock<std::mutex>(mutexMap); return mKeyframes[0]; }
24.75
70
0.688552
johnpeterflynn
cbd7b33cdc290bfc98be048f396e031fd1ca7586
1,472
hpp
C++
include/Jam/Instance.hpp
DrJonki/Kajak-Games-Finlandia-Jam
7c5e44c11ec5a3edbbf4ae006fab4fd5921141e7
[ "MIT" ]
null
null
null
include/Jam/Instance.hpp
DrJonki/Kajak-Games-Finlandia-Jam
7c5e44c11ec5a3edbbf4ae006fab4fd5921141e7
[ "MIT" ]
null
null
null
include/Jam/Instance.hpp
DrJonki/Kajak-Games-Finlandia-Jam
7c5e44c11ec5a3edbbf4ae006fab4fd5921141e7
[ "MIT" ]
null
null
null
#pragma once #include <SFML/Graphics/RenderWindow.hpp> #include <SFML/Graphics/RenderTexture.hpp> #include <SFML/System/Clock.hpp> #include <SFML/Graphics/RectangleShape.hpp> #include <SFML/Network/TcpSocket.hpp> #include <SFML/Network/UdpSocket.hpp> #include <rapidjson/document.h> #include <memory> #include <Jam/ResourceManager.hpp> #include <Jam/ConfigManager.hpp> #include <Jam/PostProcessor.hpp> #include <set> namespace sf { class TcpSocket; class UdpSocket; class Socket; } namespace jam { class Scene; class Instance final { Instance(const Instance&) = delete; void operator =(const Instance&) = delete; public: Instance(); ~Instance(); void operator ()(); bool sendMessage(const char* message, const bool tcp); bool sendMessage(const char* message, rapidjson::Value& data, const bool tcp); sf::Time getLastPingTime() const; private: sf::TcpSocket& tcpSocket(); sf::UdpSocket& udpSocket(); void connectTcp(); public: // Globals ConfigManager config; sf::RenderWindow window; sf::RenderTexture framebuffer[2]; std::unique_ptr<Scene> currentScene; ResourceManager resourceManager; PostProcessor postProcessor; public: sf::Clock m_clock; private: std::pair<sf::TcpSocket, sf::UdpSocket> m_sockets; sf::RectangleShape m_quad; sf::Clock m_pingTimer; sf::Clock m_pingClock; sf::Time m_lastPingTime; std::string m_udpId; }; }
19.116883
82
0.696332
DrJonki
cbdbda7941c47992cd7ca837bfd8134df0947c23
3,439
cpp
C++
secure_tunneling/source/IotSecureTunnelingClient.cpp
gregbreen/aws-iot-device-sdk-cpp-v2
57ded0046d1cda3b35fbe9298eed308392961435
[ "Apache-2.0" ]
88
2019-11-29T19:30:29.000Z
2022-03-28T02:29:51.000Z
secure_tunneling/source/IotSecureTunnelingClient.cpp
gregbreen/aws-iot-device-sdk-cpp-v2
57ded0046d1cda3b35fbe9298eed308392961435
[ "Apache-2.0" ]
194
2019-12-01T15:54:42.000Z
2022-03-31T22:06:11.000Z
secure_tunneling/source/IotSecureTunnelingClient.cpp
gregbreen/aws-iot-device-sdk-cpp-v2
57ded0046d1cda3b35fbe9298eed308392961435
[ "Apache-2.0" ]
64
2019-12-17T14:13:40.000Z
2022-03-12T07:43:13.000Z
/* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. * This file is generated */ #include <aws/iotsecuretunneling/IotSecureTunnelingClient.h> #include <aws/iotsecuretunneling/SecureTunnelingNotifyResponse.h> #include <aws/iotsecuretunneling/SubscribeToTunnelsNotifyRequest.h> namespace Aws { namespace Iotsecuretunneling { IotSecureTunnelingClient::IotSecureTunnelingClient( const std::shared_ptr<Aws::Crt::Mqtt::MqttConnection> &connection) : m_connection(connection) { } IotSecureTunnelingClient::operator bool() const noexcept { return *m_connection; } int IotSecureTunnelingClient::GetLastError() const noexcept { return aws_last_error(); } bool IotSecureTunnelingClient::SubscribeToTunnelsNotify( const Aws::Iotsecuretunneling::SubscribeToTunnelsNotifyRequest &request, Aws::Crt::Mqtt::QOS qos, const OnSubscribeToTunnelsNotifyResponse &handler, const OnSubscribeComplete &onSubAck) { (void)request; auto onSubscribeComplete = [handler, onSubAck]( Aws::Crt::Mqtt::MqttConnection &, uint16_t, const Aws::Crt::String &topic, Aws::Crt::Mqtt::QOS, int errorCode) { (void)topic; if (errorCode) { handler(nullptr, errorCode); } if (onSubAck) { onSubAck(errorCode); } }; auto onSubscribePublish = [handler]( Aws::Crt::Mqtt::MqttConnection &, const Aws::Crt::String &, const Aws::Crt::ByteBuf &payload) { Aws::Crt::String objectStr(reinterpret_cast<char *>(payload.buffer), payload.len); Aws::Crt::JsonObject jsonObject(objectStr); Aws::Iotsecuretunneling::SecureTunnelingNotifyResponse response(jsonObject); handler(&response, AWS_ERROR_SUCCESS); }; Aws::Crt::StringStream subscribeTopicSStr; subscribeTopicSStr << "$aws" << "/" << "things" << "/" << *request.ThingName << "/" << "tunnels" << "/" << "notify"; return m_connection->Subscribe( subscribeTopicSStr.str().c_str(), qos, std::move(onSubscribePublish), std::move(onSubscribeComplete)) != 0; } } // namespace Iotsecuretunneling } // namespace Aws
38.640449
115
0.540855
gregbreen
cbdc28c1ebf146761dfe69734807d0defed1e9a7
1,549
cpp
C++
src/hotrod/api/RemoteCacheManager.cpp
tristantarrant/cpp-client
11f5f0919978d21284ecba6d015ca88c41134dbb
[ "Apache-2.0" ]
null
null
null
src/hotrod/api/RemoteCacheManager.cpp
tristantarrant/cpp-client
11f5f0919978d21284ecba6d015ca88c41134dbb
[ "Apache-2.0" ]
null
null
null
src/hotrod/api/RemoteCacheManager.cpp
tristantarrant/cpp-client
11f5f0919978d21284ecba6d015ca88c41134dbb
[ "Apache-2.0" ]
null
null
null
#include "infinispan/hotrod/RemoteCacheManager.h" #include "infinispan/hotrod/ConfigurationBuilder.h" #include "hotrod/impl/RemoteCacheManagerImpl.h" #include "hotrod/impl/protocol/CodecFactory.h" #include "hotrod/impl/operations/OperationsFactory.h" namespace infinispan { namespace hotrod { using namespace protocol; using namespace transport; using namespace operations; RemoteCacheManager::RemoteCacheManager(bool start_) : Handle<RemoteCacheManagerImpl>(new RemoteCacheManagerImpl(start_)) { } RemoteCacheManager::RemoteCacheManager(const std::map<std::string,std::string>& properties, bool start_) : Handle<RemoteCacheManagerImpl>(new RemoteCacheManagerImpl(properties, start_)) { } // Deprecated RemoteCacheManager::RemoteCacheManager(const Configuration& configuration, bool start_) : Handle<RemoteCacheManagerImpl>(new RemoteCacheManagerImpl(configuration, start_)) { } void RemoteCacheManager::initCache( RemoteCacheBase& cache, bool forceReturnValue) { cache.impl = impl->createRemoteCache(forceReturnValue); } void RemoteCacheManager::initCache( RemoteCacheBase& cache, const std::string& name, bool forceReturnValue) { cache.impl = impl->createRemoteCache(name, forceReturnValue); } void RemoteCacheManager::start() { impl->start(); } void RemoteCacheManager::stop() { impl->stop(); } bool RemoteCacheManager::isStarted() { return impl->isStarted(); } const Configuration& RemoteCacheManager::getConfiguration() { return impl->getConfiguration(); } }} // namespace infinispan::hotrod
28.685185
104
0.780504
tristantarrant
cbdc8a04e9c4399ac7090b2fd640bc26f3caa9dd
60,743
cxx
C++
inetsrv/iis/setup/osrc/webcomp.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/iis/setup/osrc/webcomp.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/iis/setup/osrc/webcomp.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 2001 Microsoft Corporation Module Name : webcomp.cxx Abstract: Class used to install the World Wide Web component Author: Christopher Achille (cachille) Project: Internet Services Setup Revision History: April 2002: Created --*/ #include "stdafx.h" #include "webcomp.hxx" #include "acl.hxx" #include "iadm.h" #include "iiscnfgp.h" #include "mdkey.h" #include "mdentry.h" #include "restrlst.hxx" #include "svc.h" #include "reg.hxx" #include "ACShim.h" #include "Setuser.h" #include "lockdown.hxx" #include "helper.h" #include "Wtsapi32.h" // TS settings #include "Mprapi.h" // RAS/VPN Settings #include "lockdown.hxx" #include <secconlib.h> #include <shlwapi.h> #include "inetinfo.h" #include "resource.h" // Undef this becase of collision with TSTR::PathAppend #ifdef PathAppend #undef PathAppend #endif // Local const definitions // LPCWSTR IIS_WPG_GROUPNAME = L"IIS_WPG"; LPCWSTR OLD_WAM_GROUPNAME = L"Web Applications"; const LPTSTR MofCompFiles[] = { { _T("asp.mof") }, { _T("w3core.mof") }, { _T("w3isapi.mof") }, { NULL } }; sOurDefaultExtensions CWebServiceInstallComponent::m_aExternalExt[ CWebServiceInstallComponent::EXTENSIONS_EXTERNAL ] = { { _T("idq.dll"), _T("IndexingService"), IDS_PRODUCT_INDEXSERVICE, NULL, // No component name - we don't install this FALSE, // UI deletable FALSE, // Disabled { _T(".idq"), _T(".ida"), NULL } }, { _T("webhits.dll"), _T("IndexingService"), IDS_PRODUCT_INDEXSERVICE, NULL, // No component name - we don't install this FALSE, // UI deletable FALSE, // Disabled { _T(".htw"), NULL } }, { _T("msw3prt.dll"), _T("W3PRT"), IDS_PRODUCT_INETPRINT, NULL, // No component name - we don't install this FALSE, // UI deletable FALSE, // Disabled { _T(".printer"), NULL } } }; // Constructor // CWebServiceInstallComponent::CWebServiceInstallComponent() { m_bMofCompRun = FALSE; m_bWebDavIsDisabled = FALSE; } // GetName // // Return the name for the Web Service Component // LPTSTR CWebServiceInstallComponent::GetName() { return _T("iis_www"); } // GetFriendlyName // // Get the Friendly name for the UI // BOOL CWebServiceInstallComponent::GetFriendlyName( TSTR *pstrFriendlyName ) { return pstrFriendlyName->LoadString( IDS_DTC_WORLDWIDEWEB ); } // SetWWWRootAclonDir // // Set the WWW Root Acl that we need. This will be used for WWWRoot // and the customer error pages root // // The acl is the following: // Upgrades - Add IIS_WPG:R // Fresh Install - <Deny> IUSR_MACHINENAME:Write+Delete // <Allow> Users:Read+Execute // <Allow> IIS_WPG:Read+Execute // <Allow> Administrators:Full // <Allow> LocalSystem:Full // // Parameters: // szPhysicalPath - The Physical Path to add the ACL // bAddIusrDeny - Should we add the IUSR_ deny acl? // // Return: // TRUE - Success // FALSE - Failure BOOL CWebServiceInstallComponent::SetWWWRootAclonDir(LPTSTR szPhysicalPath, BOOL bAddIusrDeny) { CSecurityDescriptor PathSD; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling SetWWWRootAclonDir\n"))); if ( IsUpgrade() ) { // Upgrade if ( !PathSD.GetSecurityInfoOnFile( szPhysicalPath ) ) { // Failed to retrieve old SD return FALSE; } } else { // Fresh Install if ( !PathSD.AddAccessAcebyWellKnownID( CSecurityDescriptor::GROUP_USERS, CSecurityDescriptor::ACCESS_READ_EXECUTE, TRUE, TRUE ) || !PathSD.AddAccessAcebyWellKnownID( CSecurityDescriptor::GROUP_ADMINISTRATORS, CSecurityDescriptor::ACCESS_FULL, TRUE, TRUE ) || !PathSD.AddAccessAcebyWellKnownID( CSecurityDescriptor::USER_LOCALSYSTEM, CSecurityDescriptor::ACCESS_FULL, TRUE, TRUE ) ) { // Failed ot create SD return FALSE; } if ( bAddIusrDeny && !PathSD.AddAccessAcebyName( g_pTheApp->m_csGuestName.GetBuffer(0), CSecurityDescriptor::ACCESS_WRITEONLY | CSecurityDescriptor::ACCESS_DIR_DELETE, FALSE, TRUE ) ) { // Failed to add IUSR_ return FALSE; } } if ( !PathSD.AddAccessAcebyName( _T("IIS_WPG"), CSecurityDescriptor::ACCESS_READ_EXECUTE, TRUE, TRUE ) ) { // Failed to add IIS_WPG return FALSE; } if ( !CreateDirectoryWithSA( szPhysicalPath, PathSD, FALSE ) ) { // Failed to set ACL on file/dir return FALSE; } return TRUE; } // SetPassportAcls // // Set the appropriate Passport Acl's // // Parameters // bAdd - TRUE == Add Acl // FALSE == Remove Acl // BOOL CWebServiceInstallComponent::SetPassportAcls( BOOL bAdd ) { BOOL bIsAclable; TSTR_PATH strPassportDir; CSecurityDescriptor sdPassport; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling SetPassportAcls\n"))); if ( !strPassportDir.RetrieveSystemDir() || !strPassportDir.PathAppend( PATH_PASSPORT ) ) { // Could not create CustomError Path return FALSE; } if ( !CSecurityDescriptor::DoesFileSystemSupportACLs( strPassportDir.QueryStr(), &bIsAclable ) ) { return FALSE; } if ( !bIsAclable ) { // Passport dir is not aclable, so lets exit return TRUE; } // If directory does not exist, then create it if ( !IsFileExist( strPassportDir.QueryStr() ) ) { if ( !bAdd ) { // Nothing to remove ACl From return TRUE; } if ( !CreateDirectory( strPassportDir.QueryStr(), NULL ) ) { // Failed to create passport dir return FALSE; } } if ( !sdPassport.GetSecurityInfoOnFile( strPassportDir.QueryStr() ) ) { return FALSE; } if ( bAdd ) { if ( !sdPassport.AddAccessAcebyName( _T("IIS_WPG"), CSecurityDescriptor::ACCESS_READ_EXECUTE | CSecurityDescriptor::ACCESS_WRITEONLY | CSecurityDescriptor::ACCESS_DIR_DELETE, TRUE, TRUE ) ) { return FALSE; } } else { if ( !sdPassport.RemoveAccessAcebyName( _T("IIS_WPG") ) ) { return FALSE; } } if ( !sdPassport.SetSecurityInfoOnFile( strPassportDir.QueryStr(), FALSE ) ) { // Failed to set ACL return FALSE; } return TRUE; } // SetAdminScriptsAcl // // Set the ACL on the AdminScripts Directory // BOOL CWebServiceInstallComponent::SetAdminScriptsAcl() { TSTR_PATH strAdminScripts; CSecurityDescriptor AdminSD; BOOL bDriveIsAclable; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling SetAdminScriptsAcl\n"))); if ( !strAdminScripts.Copy( g_pTheApp->m_csPathInetpub.GetBuffer(0) ) || !strAdminScripts.PathAppend( _T("AdminScripts") ) ) { // Failed to construct Path return FALSE; } if ( !CSecurityDescriptor::DoesFileSystemSupportACLs( strAdminScripts.QueryStr(), &bDriveIsAclable ) ) { // Failed to check if ACL is valid for this filesystem return FALSE; } if ( !bDriveIsAclable ) { // This drive is not aclable, so skip it return TRUE; } if ( !AdminSD.AddAccessAcebyWellKnownID( CSecurityDescriptor::GROUP_ADMINISTRATORS, CSecurityDescriptor::ACCESS_FULL, TRUE, TRUE ) || !AdminSD.AddAccessAcebyWellKnownID( CSecurityDescriptor::USER_LOCALSYSTEM, CSecurityDescriptor::ACCESS_FULL, TRUE, TRUE ) ) { // Failed to create Admin SD return FALSE; } if ( !AdminSD.SetSecurityInfoOnFiles( strAdminScripts.QueryStr(), FALSE ) ) { // Failed to set ACL on this resource return FALSE; } return TRUE; } // SetAppropriateFileAcls // // To tighten security, set some ACL's in strategic places // where we install files. // // We set the following ACL's on the web root, and // custom error root // IUSR_MACHINE: Deny Write and Delete // IIS_WPG: Allow Read // Administrators: Allow Full // Local System: Allow Full // Users: Allow Read // BOOL CWebServiceInstallComponent::SetAppropriateFileAcls() { iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling SetAppropriateFileAcls\n"))); return SetAppropriateFileAclsforDrive( _T('*') ); } // SetAppropriateFileAclsforDrive // // Set the appropriate File Acl's, but only for the drive // specified // // Parameters: // cDriveLetter - The drive letter to be acl'd, send in '*' // for all drives // BOOL CWebServiceInstallComponent::SetAppropriateFileAclsforDrive( WCHAR cDriveLetter) { BOOL bWWWRootIsAclable; BOOL bCustomErrorsAreAclable; TSTR_PATH strCustomErrorPath; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling SetAppropriateFileAclsforDrive\n"))); if ( !strCustomErrorPath.RetrieveWindowsDir() || !strCustomErrorPath.PathAppend( PATH_WWW_CUSTOMERRORS ) ) { // Could not create CustomError Path return FALSE; } if ( !CSecurityDescriptor::DoesFileSystemSupportACLs( g_pTheApp->m_csPathWWWRoot.GetBuffer(0), &bWWWRootIsAclable ) || !CSecurityDescriptor::DoesFileSystemSupportACLs( strCustomErrorPath.QueryStr(), &bCustomErrorsAreAclable ) ) { // Could not check FS if they were aclable return FALSE; } // Acl everything needed for systemdrive if ( ( cDriveLetter == _T('*') ) || ( tolower( cDriveLetter ) == tolower( *( strCustomErrorPath.QueryStr() ) ) ) ) { if ( bCustomErrorsAreAclable && !SetWWWRootAclonDir( strCustomErrorPath.QueryStr(), FALSE ) ) { // Failed to set ACL return FALSE; } if ( !SetPassportAcls( TRUE ) ) { // Failed to set ACL return FALSE; } if ( !SetIISTemporaryDirAcls( TRUE ) ) { // Failed to set Acl on IIS Temporary Dirs return FALSE; } if ( !SetAdminScriptsAcl() ) { // Failed to set ACL for AdminScripts directory return FALSE; } } // Acl everything in inetpub if ( ( cDriveLetter == _T('*') ) || ( tolower( cDriveLetter ) == tolower( *( g_pTheApp->m_csPathWWWRoot.GetBuffer(0) ) ) ) ) { if ( bWWWRootIsAclable && !SetWWWRootAclonDir( g_pTheApp->m_csPathWWWRoot.GetBuffer(0), TRUE ) ) { // Failed to set ACL return FALSE; } } return TRUE; } // SetIISTemporaryDirAcls // // Set the ACL's on the IIS Temporary dirs // BOOL CWebServiceInstallComponent::SetIISTemporaryDirAcls( BOOL bAdd ) { BOOL bIsAclable; TSTR_PATH strCompressionDir; CSecurityDescriptor sdCompression; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling SetIISTemporaryDirAcls\n"))); if ( !strCompressionDir.RetrieveWindowsDir() || !strCompressionDir.PathAppend( PATH_TEMPORARY_COMPRESSION_FILES ) ) { // Could not create CustomError Path return FALSE; } if ( !CSecurityDescriptor::DoesFileSystemSupportACLs( strCompressionDir.QueryStr(), &bIsAclable ) ) { return FALSE; } if ( !bIsAclable ) { // Passport dir is not aclable, so lets exit return TRUE; } // If directory does not exist, then create it if ( !IsFileExist( strCompressionDir.QueryStr() ) ) { if ( !bAdd ) { // Nothing to remove ACl From return TRUE; } if ( !CreateDirectory( strCompressionDir.QueryStr(), NULL ) ) { // Failed to create passport dir return FALSE; } } if ( !sdCompression.GetSecurityInfoOnFile( strCompressionDir.QueryStr() ) ) { return FALSE; } if ( bAdd ) { if ( !sdCompression.AddAccessAcebyName( _T("IIS_WPG"), CSecurityDescriptor::ACCESS_FULL, TRUE, TRUE ) ) { return FALSE; } } else { if ( !sdCompression.RemoveAccessAcebyName( _T("IIS_WPG") ) ) { return FALSE; } } if ( !sdCompression.SetSecurityInfoOnFile( strCompressionDir.QueryStr(), FALSE ) ) { // Failed to set ACL return FALSE; } return TRUE; } // SetAspTemporaryDirAcl // // Set the ACL's on the ASP Temporary dirs // BOOL CWebServiceInstallComponent::SetAspTemporaryDirAcl( BOOL bAdd ) { BOOL bIsAclable; TSTR_PATH strASPDir; CSecurityDescriptor sdASP; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling SetAspTemporaryDirAcl\n"))); if ( !strASPDir.RetrieveSystemDir() || !strASPDir.PathAppend( PATH_TEMPORARY_ASP_FILES ) ) { // Could not create CustomError Path return FALSE; } if ( !CSecurityDescriptor::DoesFileSystemSupportACLs( strASPDir.QueryStr(), &bIsAclable ) ) { return FALSE; } if ( !bIsAclable ) { // Passport dir is not aclable, so lets exit return TRUE; } // If directory does not exist, then create it if ( !IsFileExist( strASPDir.QueryStr() ) ) { if ( !bAdd ) { // Nothing to remove ACL From return TRUE; } if ( !CreateDirectory( strASPDir.QueryStr(), NULL ) ) { // Failed to create ASP Temporary Dir return FALSE; } } if ( bAdd ) { if ( !sdASP.AddAccessAcebyName( _T("IIS_WPG"), CSecurityDescriptor::ACCESS_FULL, TRUE, TRUE ) || !sdASP.AddAccessAcebyWellKnownID( CSecurityDescriptor::GROUP_ADMINISTRATORS, CSecurityDescriptor::ACCESS_FULL, TRUE, TRUE ) || !sdASP.AddAccessAcebyWellKnownID( CSecurityDescriptor::USER_LOCALSYSTEM, CSecurityDescriptor::ACCESS_FULL, TRUE, TRUE ) ) { // Could not create appropriate ACL return FALSE; } } else { if ( !sdASP.GetSecurityInfoOnFile( strASPDir.QueryStr() ) || !sdASP.RemoveAccessAcebyName( _T("IIS_WPG") ) ) { return FALSE; } } if ( !sdASP.SetSecurityInfoOnFile( strASPDir.QueryStr(), FALSE ) ) { // Failed to set ACL return FALSE; } return TRUE; } // RemoveOurAcls // // Remove IIS's Acls from a resource. This is so that when // we delete the accounts, the bad sid's are not left around // BOOL CWebServiceInstallComponent::RemoveOurAcls( LPTSTR szPhysicalPath) { BOOL bIsAclable; CSecurityDescriptor sd; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling RemoveOurAcls\n"))); if ( !CSecurityDescriptor::DoesFileSystemSupportACLs( szPhysicalPath, &bIsAclable ) ) { // Failed to check if it was aclable return FALSE; } if ( !bIsAclable ) { // No acling was needed return TRUE; } if ( !sd.GetSecurityInfoOnFile( szPhysicalPath ) || !sd.RemoveAccessAcebyName( g_pTheApp->m_csGuestName.GetBuffer(0), TRUE ) || !sd.RemoveAccessAcebyName( _T("IIS_WPG"), TRUE ) || !sd.SetSecurityInfoOnFile( szPhysicalPath, FALSE ) ) { // Failed to remove our acl's return FALSE; } return TRUE; } // RemoveAppropriateFileAcls // // During install, we explicity set the ACLs for a couple of locations, // including the \inetpub\wwwroot and the custom errors pages. For uninstall // we will not remove all the ACL's, since someone might still have // valuable information in those directories. What we will do, is we will // remove the ACL's that will not mean anything after we are uninstalled. Like // the IUSR_ and IIS_WPG since. Since those users are being removed later in setup, // we must delete the ACL's now. // BOOL CWebServiceInstallComponent::RemoveAppropriateFileAcls() { TSTR strCustomErrorPath; BOOL bRet = TRUE; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling RemoveAppropriateFileAcls\n"))); if ( !strCustomErrorPath.Copy( g_pTheApp->m_csWinDir ) || !strCustomErrorPath.Append( PATH_WWW_CUSTOMERRORS ) ) { // Could not create CustomError Path return FALSE; } if ( !RemoveOurAcls( g_pTheApp->m_csPathWWWRoot.GetBuffer(0) ) ) { bRet = FALSE; } if ( !RemoveOurAcls( strCustomErrorPath.QueryStr() ) ) { bRet = FALSE; } if ( !SetPassportAcls( FALSE ) ) { // Failed to set ACL bRet = FALSE; } if ( !SetIISTemporaryDirAcls( FALSE ) ) { // Failed to set Acl on IIS Temporary Dirs bRet = FALSE; } if ( !SetAspTemporaryDirAcl( FALSE ) ) { // Failed to remove acl for ASP Temp Dir bRet = FALSE; } return bRet; } // SetApplicationDependencies // // Set the Application Dependencies as they are defined in the // unattend file. We take the dependencies from the inf, and // put them in the metabase // BOOL CWebServiceInstallComponent::SetApplicationDependencies() { CApplicationDependencies AppDep; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling SetApplicationDependencies\n"))); // Load current settings if ( !AppDep.InitMetabase() || !AppDep.LoadCurrentSettings() ) { return FALSE; } // Load Unattend Values if ( AppDep.DoUnattendSettingsExist() ) { if ( !AppDep.AddUnattendSettings() ) { // Failed to add unattend settings return FALSE; } } if ( !AppDep.AddDefaults() ) { // Failed to add defaults return FALSE; } return AppDep.SaveSettings(); } // SetRestrictionList // // Set the restriction list for the extensions and CGIs. // // This will: // - Load current RestrictionList // - Incorporate old values (IsapiRestrictionList and CgiRestrictionList) // - Load unattend values // - Add defaults // - Save them to metabase // // Return Values: // TRUE - Successfully loaded and written // FALSE - Failure // BOOL CWebServiceInstallComponent::SetRestrictionList() { CRestrictionList RestList; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling SetRestrictionList\n"))); // Load current Value if ( !RestList.InitMetabase() || !RestList.LoadCurrentSettings() ) { // Failed to load current value return FALSE; } if ( RestList.IsEmpty() && IsUpgrade() && ( GetUpgradeVersion() == 6 ) ) { // This is an IIS6 upgrade, so lets try to load the old format // Isapi and Cgi Restriction Lists if ( !RestList.ImportOldLists( m_mstrOldCgiRestList, m_mstrOldIsapiRestList ) ) { return FALSE; } } // Now lets load values in unattend, if they exist if ( !RestList.AddUnattendSettings() ) { return FALSE; } // Last, lets put in the default values if they are not already // present if ( !RestList.AddDefaults( IsUpgrade() ? TRUE : FALSE ) ) { return FALSE; } // Everything is done, so lets save our new values return RestList.SaveSettings(); } // LogWarningonFAT // // On Fat systems, just log a warning saying that we are installing on FAT, // and that is not secure // BOOL CWebServiceInstallComponent::LogWarningonFAT() { BOOL bSystemPreservesAcls; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling LogWarningonFAT\n"))); if ( !DoesTheInstallDrivePreserveAcls( &bSystemPreservesAcls ) ) { return FALSE; } if ( !bSystemPreservesAcls ) { iisDebugOut((LOG_TYPE_WARN, _T("IIS is being installed on a fat volume. This will disable IIS security features. Please consider converting the partition from FAT to NTFS.\n") ) ); } return TRUE; } // DisableW3SVCOnUpgrade // // Disable W3SVC on Upgrades // This is determined by checking the registry entry that is set by // the compatability wizard that runs on the Win2k side of the // upgrade, and also affected by the unattend setting // // Return Values: // TRUE - Success // FALSE - Failure // BOOL CWebServiceInstallComponent::DisableW3SVCOnUpgrade() { BOOL bDisable = TRUE; BOOL bRet = TRUE; CRegValue Value; CRegistry Registry; TSTR strUnattendValue( MAX_PATH ); iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling DisableW3SVCOnUpgrade\n"))); if ( !Registry.OpenRegistry( HKEY_LOCAL_MACHINE, REG_INETSTP, KEY_READ | KEY_WRITE ) ) { // Failed to open our node in registry return FALSE; } // Check registry entry if ( Registry.ReadValue( REGISTR_IISSETUP_DISABLEW3SVC, Value ) ) { if ( Value.m_dwType == REG_DWORD ) { // Set Disable to on or off bDisable = *( (LPDWORD) Value.m_buffData.QueryPtr() ) != 0; } // Delete the value, since it is no longer needed Registry.DeleteValue( REGISTR_IISSETUP_DISABLEW3SVC ); } if ( ( g_pTheApp->m_hUnattendFile != NULL ) && ( g_pTheApp->m_hUnattendFile != INVALID_HANDLE_VALUE) && SetupGetLineText( NULL, g_pTheApp->m_hUnattendFile, UNATTEND_FILE_SECTION, UNATTEND_INETSERVER_DISABLEW3SVC, strUnattendValue.QueryStr(), strUnattendValue.QuerySize(), NULL ) ) { // Retrieved line from unattend, so lets compare if ( strUnattendValue.IsEqual( _T("true"), FALSE ) ) { bDisable = TRUE; } else if ( strUnattendValue.IsEqual( _T("false"), FALSE ) ) { bDisable = FALSE; } else { iisDebugOut((LOG_TYPE_ERROR, _T("Unattend setting incorrect '%s=%s'\n"), UNATTEND_INETSERVER_DISABLEW3SVC, strUnattendValue.QueryStr() ) ); } } if ( bDisable ) { // Disable the W3SVC Service if ( InetDisableService( _T("W3SVC") ) != 0 ) { iisDebugOut((LOG_TYPE_ERROR, _T("Failed to disable W3SVC\n") ) ); bRet = FALSE; } g_pTheApp->dwUnattendConfig |= USER_SPECIFIED_INFO_MANUAL_START_WWW; } return bRet; } // DisableIUSRandIWAMLogons // // Disable Terminal Server Logons and RAS VPN Logons // for both IUSR and IWAM accounts // // Return // TRUE - Successfully changed // FALSE - Not successfully changed // BOOL CWebServiceInstallComponent::DisableIUSRandIWAMLogons() { DWORD dwAllowTSLogin = FALSE; RAS_USER_1 RasInfo; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling DisableIUSRandIWAMLogons\n"))); RasInfo.bfPrivilege = RASPRIV_NoCallback | RASPRIV_CallbackType; // No callback RasInfo.bfPrivilege = 0; // Do not allow dialin _tcscpy( RasInfo.wszPhoneNumber, _T("") ); // Disable RAS/VPN access for our users if ( MprAdminUserSetInfo( NULL, // Server g_pTheApp->m_csWWWAnonyName.GetBuffer(0), 1, // RAS_USER_0 (LPBYTE) &RasInfo ) != NO_ERROR ) { return FALSE; } if ( MprAdminUserSetInfo( NULL, // Server g_pTheApp->m_csWAMAccountName.GetBuffer(0), 1, // RAS_USER_0 (LPBYTE) &RasInfo ) != NO_ERROR ) { return FALSE; } // Disable TS access for our users // IUSR_ account if ( !WTSSetUserConfig( WTS_CURRENT_SERVER_NAME, g_pTheApp->m_csWWWAnonyName.GetBuffer(0), WTSUserConfigfAllowLogonTerminalServer, (LPTSTR) &dwAllowTSLogin, sizeof(DWORD) ) ) { return FALSE; } // IWAM_ account if ( !WTSSetUserConfig( WTS_CURRENT_SERVER_NAME, g_pTheApp->m_csWAMAccountName.GetBuffer(0), WTSUserConfigfAllowLogonTerminalServer, (LPTSTR) &dwAllowTSLogin, sizeof(DWORD) ) ) { return FALSE; } return TRUE; } // RunMofCompOnIISFiles // // Run MofComp on the IIS mofcomp files // BOOL CWebServiceInstallComponent::RunMofCompOnIISFiles() { HRESULT hRes; TSTR_PATH strMofPath; DWORD dwCurrent; BOOL bRet = TRUE; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling RunMofCompOnIISFiles\n"))); if ( m_bMofCompRun ) { // We have already done this return TRUE; } for ( dwCurrent = 0; MofCompFiles[ dwCurrent ] != NULL; dwCurrent++ ) { if ( !strMofPath.Copy( g_pTheApp->m_csPathInetsrv.GetBuffer(0) ) || !strMofPath.PathAppend( MofCompFiles[ dwCurrent ] ) ) { // Fatal Error iisDebugOut((LOG_TYPE_ERROR, _T("RunMofCompOnIISFiles: Failed to construct path for '%s'\n"), MofCompFiles[ dwCurrent ] ) ); return FALSE; } hRes = MofCompile( strMofPath.QueryStr() ); if ( FAILED( hRes ) ) { iisDebugOut((LOG_TYPE_ERROR, _T("RunMofCompOnIISFiles: Failed to mofcomp on file '%s', hRes=0x%8x\n"), strMofPath.QueryStr(), hRes ) ); bRet = FALSE; } } if ( bRet ) { m_bMofCompRun = TRUE; } return bRet; } // CheckIfWebDavIsDisabled // // Check if WebDav is disabled via the IIS Lockdown tool for // IIS 4, 5, and 5.1 // BOOL CWebServiceInstallComponent::CheckIfWebDavIsDisabled() { BOOL bIsAclDisabled; BOOL bIsRegistryDisabled = FALSE; CRegValue Value; CRegistry Registry; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling CheckIfWebDavIsDisabled\n"))); if ( !IsUpgrade() || ( GetUpgradeVersion() <= 3 ) || ( GetUpgradeVersion() >= 6 ) ) { // Since we either not upgrading, or the version is not between // 4 and 5.1, lets not do the test return TRUE; } if ( !IsWebDavDisabled( &bIsAclDisabled ) || !IsWebDavDisabledViaRegistry( &bIsRegistryDisabled ) ) { // Failed during check return FALSE; } m_bWebDavIsDisabled = bIsAclDisabled || bIsRegistryDisabled; return TRUE; } // DisabledWebDavOnUpgrade // // If Web DAV was disabled before the upgrade via acl's, then lets // put that in the restriction list now // BOOL CWebServiceInstallComponent::DisabledWebDavOnUpgrade() { iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling DisabledWebDavOnUpgrade\n"))); if ( !m_bWebDavIsDisabled ) { // Nothing needed to be done return TRUE; } return DisableWebDavInRestrictionList(); } // SetServiceToManualIfNeeded // // Set the service to manual if specified in unattend file // BOOL CWebServiceInstallComponent::SetServiceToManualIfNeeded() { iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling SetServiceToManualIfNeeded\n"))); if ( g_pTheApp->dwUnattendConfig & USER_SPECIFIED_INFO_MANUAL_START_WWW ) { SetServiceStart( _T("W3SVC"), SERVICE_DEMAND_START ); } return TRUE; } // PreInstall // // Do all of the work that needs to be done before we do // all the heavy install work // BOOL CWebServiceInstallComponent::PreInstall() { BOOL bRet = TRUE; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling PreInstall\n"))); // Rename the "Web Applications" group to IIS_WPG. This group is created by IIS Lockdown tool if ( bRet && IsUpgrade() && ( GetUpgradeVersion() >= 4 ) ) { if ( LocalGroupExists( OLD_WAM_GROUPNAME ) ) { if ( !LocalGroupExists( IIS_WPG_GROUPNAME ) ) { LOCALGROUP_INFO_0 Info = { const_cast<LPWSTR>( IIS_WPG_GROUPNAME ) }; if ( ::NetLocalGroupSetInfo( NULL, OLD_WAM_GROUPNAME, 0, (BYTE*)&Info, NULL ) != NERR_Success ) { iisDebugOut((LOG_TYPE_ERROR, _T("Failed to rename '%s' group to '%s'!\n"), OLD_WAM_GROUPNAME, IIS_WPG_GROUPNAME )); bRet = FALSE; } } else { // IIS_WPG NT group should not exist at this point. If it does - move the code that creates it // later or do no create it if the 'Web Applications' group exist _ASSERT( false ); iisDebugOut((LOG_TYPE_ERROR, _T("IIS_WPG group exists. Cannot rename 'Web Applications'!\n"), OLD_WAM_GROUPNAME, IIS_WPG_GROUPNAME )); } } } bRet = bRet && CheckIfWebDavIsDisabled(); if ( bRet && IsUpgrade() ) { if ( GetUpgradeVersion() == 6 ) { // If it is an IIS6 upgrade, then we should load the old Cgi and Isapi Restriction // Lists, because the metabase no longer know anything about them bRet = bRet && CRestrictionList::LoadOldFormatSettings( &m_mstrOldCgiRestList, &m_mstrOldIsapiRestList ); } } return bRet; } // Install // // Do all of the main work need for install // BOOL CWebServiceInstallComponent::Install() { BOOL bRet = TRUE; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Executing Install of WWW Component...\n"))); bRet = bRet && SetVersionInMetabase(); bRet = bRet && SetAppropriateFileAcls(); /*bRet = bRet &&*/ DisableIUSRandIWAMLogons(); // Load the Restriction List and Application Dependencies bRet = bRet && DisabledWebDavOnUpgrade(); bRet = bRet && SetRestrictionList(); bRet = bRet && SetApplicationDependencies(); bRet = bRet && SetServiceToManualIfNeeded(); bRet = bRet && AddInheritFlagToSSLUseDSMap(); bRet = bRet && SetRegEntries( TRUE ); bRet = bRet && UpdateSiteFiltersAcl(); // Set /w3svc/X/filters acl if ( IsUpgrade() ) { //Do work for upgrades bRet = bRet && ProcessIISShims(); // Import IIS Shims from the AppCompat sys DB bRet = bRet && UpgradeRestrictedExtensions(); // Upgrade restricted ( 404.dall mapped ) extension to WebSvcExtRestrictionList if ( ( GetUpgradeVersion() >= 4 ) && ( GetUpgradeVersion() < 6 ) ) { bRet = bRet && UpgradeWAMUsers(); } if ( GetUpgradeVersion() == 5 ) { // Do work for Win2k Upgrades bRet = bRet && DisableW3SVCOnUpgrade(); } if ( ( GetUpgradeVersion() >= 4 ) && ( GetUpgradeVersion() <= 5 ) ) { // Remove IIS Help Vdir bRet = bRet && RemoveHelpVdironUpgrade(); } } if ( !g_pTheApp->m_fNTGuiMode ) { // Do non GUI stuff bRet = bRet && RunMofCompOnIISFiles(); // If in GUI, must do at OC_CLEANUP } bRet = bRet && LogWarningonFAT(); return bRet; } // Post install // BOOL CWebServiceInstallComponent::PostInstall() { BOOL bRet = TRUE; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Executing PostInstall for the WWW component...\n"))); // Run MofComp if not already run bRet = bRet && RunMofCompOnIISFiles(); bRet = bRet && InitialMetabaseBackUp( TRUE ); // Backup Metabase // Start the service if ( !g_pTheApp->m_fNTGuiMode && ( g_pTheApp->dwUnattendConfig & USER_SPECIFIED_INFO_MANUAL_START_WWW ) == 0 ) { // If it is not GUI mode, then we will try an start the service. // It's not fatal if we fail to start the service, but return result anyway INT nRes = InetStartService( _T("W3SVC") ); bRet = ( (nRes == ERROR_SUCCESS) || (nRes == ERROR_SERVICE_ALREADY_RUNNING) ); } return bRet; } // Uninstall // // Do all the main work to uninstall the component // BOOL CWebServiceInstallComponent::UnInstall() { BOOL bRet = TRUE; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Executing UnInstall of WWW Component...\n"))); bRet = SetRegEntries( FALSE ) && bRet; bRet = InitialMetabaseBackUp( FALSE ) && bRet; return bRet; } // PreUninstall // // Do everything that needs to be done before uninstall // BOOL CWebServiceInstallComponent::PreUnInstall() { BOOL bRet = TRUE; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Executing PreUnInstall of WWW Component...\n"))); bRet = bRet && RemoveAppropriateFileAcls(); return bRet; } /* Locates all MD_WAM_USER_NAME values in the metabse and inserts each value ( the value is NT username ) in the IIS_WPG NT Group */ BOOL CWebServiceInstallComponent::UpgradeWAMUsers() { iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Upgrading WAM users...\n"))); // We support only UNICODE now. This functions is designed for UNICODE only! #if !( defined(UNICODE) || defined(_UNICODE) ) #error UNICODE build required #endif // Find all nodes that have MD_WAM_USER_NAME explicitly set CMDKey MBKey; CStringList listPaths; if ( FAILED( MBKey.OpenNode( METABASEPATH_WWW_ROOT ) ) ) { iisDebugOut((LOG_TYPE_ERROR, _T("Failed open LM/W3SVC node\n") )); return FALSE; } if ( FAILED( MBKey.GetDataPaths( MD_WAM_USER_NAME, STRING_METADATA, /*r*/listPaths ) ) ) { iisDebugOut((LOG_TYPE_ERROR, _T("Failed to get data paths from LM/W3SVC node\n") )); return FALSE; } // Get each value POSITION pos = listPaths.GetHeadPosition(); BOOL bRet = TRUE; while( pos != NULL ) { CString strPath = listPaths.GetNext( pos ); CMDValue UserName; BOOL bResult = MBKey.GetData( /*r*/UserName, MD_WAM_USER_NAME, strPath.GetBuffer( 0 ) ); if ( bResult ) { NET_API_STATUS nRes = RegisterAccountToLocalGroup( reinterpret_cast<LPCWSTR>( UserName.GetData() ), IIS_WPG_GROUPNAME, TRUE ); bResult = ( ( nRes == NERR_Success ) || ( nRes == ERROR_MEMBER_IN_ALIAS ) ); } if ( !bResult ) { // Log error but try to import the other usernames iisDebugOut((LOG_TYPE_ERROR, _T("Failed to transfer a WAM user from MB to IIS_WPG. Will try with next one...\n") )); bRet = FALSE; } }; return bRet; } /* Get all script maps ( on each level bellow LM/W3SVC ) For each script mapping - if there is a disabled extension - restore the mapping to the original one and create a disabled entry for this extension in the WebSvcExtRestrictionList */ BOOL CWebServiceInstallComponent::UpgradeRestrictedExtensions() { typedef std::map<std::wstring, DWORD> TExtMap; typedef std::list<std::pair<std::wstring, std::wstring> > TStrStrList; // This shows whether a particular ext group ( an elem of TExtToCheck ) should be upgraded enum GroupState { esUnknown, // Don't know if the element should be upgraded, so it woun't be esUpgrade, // Upgrade it ( move it to WebSvcExtRestrictionList esDontUpgrade // No thanks }; // This is the array that flags which extensions should be moved to WebSvcExtRe... GroupState anUpgradeExt[ TExtToCheck::ARRAY_SIZE ]; // Create a map for the file extension that we need to check // The map is Extension->ExtnesionIndex // Where Extension is the filename extension ( ".asp" ) // And ExtensionIndex is the array index in TExtToCheck and abUpgradeExt TExtMap mapExt; // This list holds a pair of strings. The first one is the full MB key where a script map is located // The second script is extension name ( ".asp" ) // At one point of time we will change the mapping of this extension to be the default filename TStrStrList listKeysToUpdate; // Create the map with the extensions // By default no extensions will be upgraded ( which means - added as disabled in WebSvcExtRestrictionList ) for ( DWORD iExtInfo = 0; iExtInfo < TExtToCheck::ARRAY_SIZE; ++iExtInfo ) { anUpgradeExt[ iExtInfo ] = esUnknown; // Enter the extensions in the map for ( DWORD iExt = 0; iExt < sOurDefaultExtensions::MaxFileExtCount; ++iExt ) { if ( TExtToCheck::Element( iExtInfo ).szExtensions[ iExt ] != NULL ) { // Put this extension in the map TExtMap::value_type New( std::wstring( TExtToCheck::Element( iExtInfo ).szExtensions[ iExt ] ), iExtInfo ); mapExt.insert( New ); } } } // Get all paths at which the script mappings are set CStringList listPaths; CMDKey mdKey; if ( FAILED( mdKey.OpenNode( METABASEPATH_WWW_ROOT ) ) ) return FALSE; if ( FAILED( mdKey.GetDataPaths( MD_SCRIPT_MAPS, MULTISZ_METADATA, /*r*/listPaths ) ) ) return FALSE; POSITION pos = listPaths.GetHeadPosition(); // For each script map - check if every mapping in the map is mapped to 404.dll // and if so - whether this is an IIS extension while( pos != NULL ) { const CString strSubPath = listPaths.GetNext( /*r*/pos ); DWORD dwType = 0; DWORD dwAttribs = 0; LPCWSTR wszSubKey = strSubPath; CStringList listMappings; // If we fail - exit. No need to continue with other paths because we // need to be sure that no mapping exist to anything different then 404.dll if ( FAILED( mdKey.GetMultiSzAsStringList( MD_SCRIPT_MAPS, &dwType, &dwAttribs, /*r*/listMappings, wszSubKey ) ) ) { iisDebugOut((LOG_TYPE_ERROR, _T("Failed to get and parse ScriptMap value\n") )); return FALSE; } // For each mapping in the script map - get what ext is mapped to what filename // If it is one of our extensions ( the ones in the map ) - check the filename // If the filename is not 404.dll - this extension will not be modified POSITION posMapping = listMappings.GetHeadPosition(); while( posMapping != NULL ) { WCHAR wszFilename[ MAX_PATH ]; CString strMapping = listMappings.GetNext( /*r*/posMapping ); LPCWSTR wszMapping = strMapping; LPCWSTR wszFirstComma = ::wcschr( wszMapping, L',' ) + 1; // Will point at the first symb after the comma if ( NULL == wszFirstComma ) { iisDebugOut((LOG_TYPE_ERROR, _T("Invalid mapping: %s\n"),wszMapping )); return FALSE; } LPCWSTR wszSecondComma = ::wcschr( wszFirstComma, L',' ); // Will point at the second comma if ( NULL == wszSecondComma ) { // Set to point at the end of the string wszSecondComma = wszMapping + ::wcslen( wszMapping ); } // Get the extension and the filename ::wcsncpy( wszFilename, wszFirstComma, min( wszSecondComma - wszFirstComma, MAX_PATH ) ); wszFilename[ min( wszSecondComma - wszFirstComma, MAX_PATH ) ] = L'\0'; std::wstring strExt( wszMapping, wszFirstComma - wszMapping - 1 ); // -1 to remove the comma as well TExtMap::iterator it = mapExt.find( strExt ); // If this is not an IIS extension - skip it if ( mapExt.end() == it ) continue; // Strip the path to be the filename only ::PathStripPath( wszFilename ); if ( ::_wcsicmp( wszFilename, L"404.dll" ) != 0 ) { // If this is not an 404.dll filename - this extension will not be upgraded anUpgradeExt[ it->second ] = esDontUpgrade; } else { // This is an IIS ext mapped to 404.dll. // If this group upgrade flag is not esDontUpgrade - then we will upgrade the group if ( anUpgradeExt[ it->second ] != esDontUpgrade ) { anUpgradeExt[ it->second ] = esUpgrade; // We may need to upgrade this entry, so store it std::wstring strKeyName( L"LM/W3SVC/" ); strKeyName += ( L'/' == wszSubKey[ 0 ] ) ? wszSubKey + 1 : wszSubKey; listKeysToUpdate.push_back( TStrStrList::value_type( strKeyName, strExt ) ); } } }; }; // Close the MB key. It is important to close it here because we will write to LM/W3SVC node // so we should not have open handles mdKey.Close(); // Right here, in anUpgradeExt we have esUpgrade values for all WebSvcExtensions we need to upgrade // In listKeysToUpdate we have all the keys that contains script maps that contain // mappings that MAY need to be modified. So perform the upgrade now // Modify the script mappings for file extensions that will be upgraded for ( TStrStrList::iterator itMapping = listKeysToUpdate.begin(); itMapping != listKeysToUpdate.end(); ++itMapping ) { // Find which element in TExtToCheck array represents this extension TExtMap::iterator itInfo = mapExt.find( itMapping->second.c_str() ); // For an extension to be in listKeysToUpdate, it should've existed in mapExt. // So we will always find it _ASSERT( itInfo != mapExt.end() ); // If we will upgrade this extension info - then we need to modify this value if ( esUpgrade == anUpgradeExt[ itInfo->second ] ) { // Don't fail on error - try to update as many mappings as possible if ( !UpdateScriptMapping( itMapping->first.c_str(), itMapping->second.c_str(), itInfo->second ) ) { iisDebugOut(( LOG_TYPE_ERROR, _T("Failed to update script mapping. Ext='%s' at '%s'\n"), itMapping->second.c_str(), itMapping->first.c_str() )); } } } CSecConLib Helper; TSTR_PATH strFullPath( MAX_PATH ); BOOL bRet = TRUE; // Now we need to put an entry in WebSvcExtRestrictionList for all disabled ISAPI dlls // The ones we need to process are the ones on abUpgradeExt for which the element is TRUE for ( DWORD iExtInfo = 0; iExtInfo < TExtToCheck::ARRAY_SIZE; ++iExtInfo ) { if ( esUpgrade == anUpgradeExt[ iExtInfo ] ) { TSTR strDesc; // Extensions from the first array go to InetSrv dir // Extensions from the second array - System32 LPCWSTR wszDir = TExtToCheck::IsIndexInFirst( iExtInfo ) ? g_pTheApp->m_csPathInetsrv.GetBuffer(0) : g_pTheApp->m_csSysDir.GetBuffer(0); if ( !strFullPath.Copy( wszDir ) || !strFullPath.PathAppend( TExtToCheck::Element( iExtInfo ).szFileName ) || !strDesc.LoadString( TExtToCheck::Element( iExtInfo ).dwProductName ) ) { // Failed to create full path, so skip to next one bRet = FALSE; iisDebugOut((LOG_TYPE_ERROR, _T("Unable to build full path for WebSvc extension. Possible OutOfMem\n") )); continue; } // Delete the extension first ( the SeccLib will fail to add an extension if it's alreafy there ) HRESULT hrDel = Helper.DeleteExtensionFileRecord( strFullPath.QueryStr(), METABASEPATH_WWW_ROOT ); if ( FAILED( hrDel ) && ( hrDel != MD_ERROR_DATA_NOT_FOUND ) ) { iisDebugOut(( LOG_TYPE_WARN, _T("Failed to delete extension file '%s' in order to change it's settings\n"), strFullPath.QueryStr() ) ); bRet = FALSE; continue; } if ( FAILED( Helper.AddExtensionFile( strFullPath.QueryStr(), // Path false, // Image should be disabled TExtToCheck::Element( iExtInfo ).szNotLocalizedGroupName, // GroupID TExtToCheck::Element( iExtInfo ).bUIDeletable != FALSE, // UI deletable strDesc.QueryStr(), // Group description METABASEPATH_WWW_ROOT ) ) ) // MB location { iisDebugOut(( LOG_TYPE_WARN, _T("Failed to add extension '%s' to group '%s'\n"), strFullPath.QueryStr(), TExtToCheck::Element( iExtInfo ).szNotLocalizedGroupName )); bRet = FALSE; continue; } } } return bRet; } /* This function updates the script mapping value ( MD_SCRIPT_MAP ) under the metabase key wszMBKey. The file extension wszExt will be associated with the filename specified in TExtToCheck[ iExtInfo ] */ BOOL CWebServiceInstallComponent::UpdateScriptMapping( LPCWSTR wszMBKey, LPCWSTR wszExt, DWORD iExtInfo ) { _ASSERT( wszMBKey != NULL ); _ASSERT( ::wcsstr( wszMBKey, L"LM/W3SVC" ) != NULL ); _ASSERT( wszExt != NULL ); _ASSERT( iExtInfo < TExtToCheck::ARRAY_SIZE ); CMDKey Key; CStringList listMappings; DWORD dwType = 0; DWORD dwAttribs = 0; if ( FAILED( Key.OpenNode( wszMBKey ) ) ) return FALSE; if ( FAILED( Key.GetMultiSzAsStringList( MD_SCRIPT_MAPS, &dwType, &dwAttribs, /*r*/listMappings ) ) ) return FALSE; // Find the string that is the extension we are looking for POSITION pos = listMappings.GetHeadPosition(); while( pos != NULL ) { CString strMapping = listMappings.GetAt( pos ); // The mapping must be large enough to consist of our ext, +2 symbols for the first and second commas // and +1 for at least one symbol for filename if ( static_cast<size_t>( strMapping.GetLength() ) <= ( ::wcslen( wszExt ) + 2 + 1 ) ) { continue; } // Check if this is the exteniosn we are looking for if ( ::_wcsnicmp( wszExt, strMapping, ::wcslen( wszExt ) ) == 0 ) { // Create the full path to the ISAPI that this ext should be mapped to TSTR_PATH strFullPath( MAX_PATH ); // There is a little trick here - extensions from the first array go to InetSrv dir // Extensions from the second array - System32 LPCWSTR wszDir = TExtToCheck::IsIndexInFirst( iExtInfo ) ? g_pTheApp->m_csPathInetsrv.GetBuffer(0) : g_pTheApp->m_csSysDir.GetBuffer(0); if ( !strFullPath.Copy( wszDir ) || !strFullPath.PathAppend( TExtToCheck::Element( iExtInfo ).szFileName ) ) { iisDebugOut((LOG_TYPE_ERROR, _T("Unable to build full path for WebSvc extension. Possible OutOfMem\n") )); return FALSE; } LPCWSTR wszMapping = strMapping; LPCWSTR wszTheRest = ::wcschr( wszMapping + wcslen( wszExt ) + 1, L',' ); _ASSERT( wszTheRest != NULL ); // Our buffer will be the ext size, +1 comma, +Path, + the rest of it +1 for the '\0' std::auto_ptr<WCHAR> spMapping( new WCHAR[ ::wcslen( wszExt ) + 1 + strFullPath.QueryLen() + ::wcslen( wszTheRest ) + 1 ] ); if ( NULL == spMapping.get() ) return FALSE; ::wcscpy( spMapping.get(), wszExt ); ::wcscat( spMapping.get(), L"," ); ::wcscat( spMapping.get(), strFullPath.QueryStr() ); ::wcscat( spMapping.get(), wszTheRest ); listMappings.SetAt( pos, CString( spMapping.get() ) ); if ( FAILED( Key.SetMultiSzAsStringList( MD_SCRIPT_MAPS, dwType, dwAttribs, listMappings ) ) ) { iisDebugOut(( LOG_TYPE_ERROR, _T("Failed to modify extension mapping ( ISAPI dll name ) for ext '%s' in '%s'\n"), wszExt, wszMBKey )); } // Thats it break; } listMappings.GetNext( /*r*/pos ); } return TRUE; } // SetVersionInMetabase // // Set the version information in the metabase // // Return Values // TRUE - Successfully Set // FALSE - Failed to Set // BOOL CWebServiceInstallComponent::SetVersionInMetabase() { CMDValue MajorVersion; CMDValue MinorVersion; CMDKey Metabase; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling SetVersionInMetabase\n"))); if ( !MajorVersion.SetValue( MD_SERVER_VERSION_MAJOR, 0, DWORD_METADATA, IIS_SERVER_VERSION_MAJOR ) || !MinorVersion.SetValue( MD_SERVER_VERSION_MINOR, 0, DWORD_METADATA, IIS_SERVER_VERSION_MINOR ) ) { // Could not create properties return FALSE; } if ( FAILED( Metabase.OpenNode( METABASEPATH_WWW_INFO ) ) || !Metabase.SetData( MajorVersion, MD_SERVER_VERSION_MAJOR ) || !Metabase.SetData( MinorVersion, MD_SERVER_VERSION_MINOR ) ) { // Failed to set return FALSE; } return TRUE; } // RemoveIISHelpVdir // // Remove an IISHelp Vdir, if it exists // // Parameters // szMetabasePath - Metabase path of website // szPhysicalPath1 - One of the physical path's it could point to, to be considered valid // szPhysicalPath1 - The second possible physical path it could point to, to be considered valid // BOOL CWebServiceInstallComponent::RemoveIISHelpVdir( LPCTSTR szMetabasePath, LPCTSTR szPhysicalPath1, LPCTSTR szPhysicalPath2 ) { CMDKey cmdKey; CMDValue cmdValue; TSTR strFullPath; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling RemoveIISHelpVdir\n"))); if ( !strFullPath.Copy( szMetabasePath ) || !strFullPath.Append( _T("/") ) || !strFullPath.Append( METABASEPATH_UPG_IISHELP_NAME ) ) { // Failed to construct Full Path return FALSE; } if ( SUCCEEDED( cmdKey.OpenNode( strFullPath.QueryStr() ) ) && cmdKey.GetData( cmdValue, MD_VR_PATH ) && ( cmdValue.GetDataType() == STRING_METADATA ) && ( ( _tcsicmp( (LPTSTR) cmdValue.GetData(), szPhysicalPath1 ) == 0 ) || ( _tcsicmp( (LPTSTR) cmdValue.GetData(), szPhysicalPath2 ) == 0 ) ) ) { cmdKey.Close(); // This is the correct vdir, so lets delete it if ( FAILED( cmdKey.OpenNode( szMetabasePath ) ) ) { // Failed to open node return FALSE; } if ( FAILED( cmdKey.DeleteNode( METABASEPATH_UPG_IISHELP_NAME ) ) ) { // Failed to remove vdir return FALSE; } } return TRUE; } // RemoveHelpVdironUpgrade // // Remove the IIS Help vdir on upgrades // BOOL CWebServiceInstallComponent::RemoveHelpVdironUpgrade() { TSTR_PATH strHelpLoc1; TSTR_PATH strHelpLoc2; TSTR_PATH strHelpDeleteLoc; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling RemoveHelpVdironUpgrade\n"))); if ( !strHelpLoc1.RetrieveWindowsDir() || !strHelpLoc1.PathAppend( PATH_UPG_IISHELP_1 ) || !strHelpLoc2.RetrieveWindowsDir() || !strHelpLoc2.PathAppend( PATH_UPG_IISHELP_2 ) || !strHelpDeleteLoc.RetrieveWindowsDir() || !strHelpDeleteLoc.PathAppend( PATH_IISHELP_DEL ) ) { // Failed to create Path return FALSE; } if ( !RemoveIISHelpVdir( METABASEPATH_UPG_IISHELP_WEB1_ROOT, strHelpLoc1.QueryStr(), strHelpLoc2.QueryStr() ) || !RemoveIISHelpVdir( METABASEPATH_UPG_IISHELP_WEB2_ROOT, strHelpLoc1.QueryStr(), strHelpLoc2.QueryStr() ) ) { // Failed to remove VDir return FALSE; } // Now delete directory RecRemoveDir( strHelpDeleteLoc.QueryStr(), TRUE ); return TRUE; } // CreateInitialMetabaseBackUp // // Create an initial backup of the metabase at the end of // the W3SVC Instalation // // Parameters: // bAdd - TRUE == Add, // FALSE == remove // BOOL CWebServiceInstallComponent::InitialMetabaseBackUp( BOOL bAdd ) { TSTR strBackupName; if ( !strBackupName.LoadString( IDS_INITIAL_METABASE_BK_NAME ) ) { // Failed to get metabase name return FALSE; } if ( bAdd ) { return CMDKey::Backup( strBackupName.QueryStr(), // Backup Name 1, // Version # MD_BACKUP_OVERWRITE | MD_BACKUP_SAVE_FIRST | MD_BACKUP_FORCE_BACKUP ); // Overwrite if one already exists } return CMDKey::DeleteBackup( strBackupName.QueryStr(), 1 ); } // CWebServiceInstallComponent:: // // If during upgrade, this metabase setting is set, add the inherit flag to it // The reason for this was because it was not set in Win2k days, and now // we need it set // BOOL CWebServiceInstallComponent::AddInheritFlagToSSLUseDSMap() { CMDKey cmdKey; CMDValue cmdValue; if ( FAILED( cmdKey.OpenNode( METABASEPATH_WWW_ROOT ) ) ) { // Failed to open metabase return FALSE; } if ( cmdKey.GetData( cmdValue, MD_SSL_USE_DS_MAPPER ) && ( cmdValue.GetDataType() == DWORD_METADATA ) ) { // If this value is present, then set with inheritance cmdValue.SetAttributes( METADATA_INHERIT ); if ( !cmdKey.SetData( cmdValue, MD_SSL_USE_DS_MAPPER ) ) { return FALSE; } } return TRUE; } // SetRegEntries // // Set the appropriate registry entries // // Parameters: // bAdd - [in] TRUE == Add; FALSE == Remove // BOOL CWebServiceInstallComponent::SetRegEntries( BOOL bAdd ) { CRegistry Registry; if ( !Registry.OpenRegistry( HKEY_LOCAL_MACHINE, REG_HTTPSYS_PARAM, KEY_WRITE ) ) { // Failed to open registry Key return FALSE; } if ( bAdd ) { CRegValue Value; if ( !Value.SetDword( 1 ) || !Registry.SetValue( REG_HTTPSYS_DISABLESERVERHEADER, Value ) ) { // Failed to set return FALSE; } } else { Registry.DeleteValue( REG_HTTPSYS_DISABLESERVERHEADER ); } return TRUE; } // function: UpdateSiteFiltersAcl // // Update all the SiteFilter's Acl's with the new ACL // // Return Value: // TRUE - Success change // FALSE - Failure changing BOOL CWebServiceInstallComponent::UpdateSiteFiltersAcl() { CMDKey cmdKey; CMDValue cmdValue; CMDValue cmdIISFiltersValue; WCHAR szSubNode[METADATA_MAX_NAME_LEN]; TSTR strFilterKey; DWORD i = 0; iisDebugOut((LOG_TYPE_PROGRAM_FLOW, _T("Calling UpdateSiteFiltersAcl\n"))); if ( !RetrieveFiltersAcl( &cmdValue ) ) { // There is no acl to set, so lets exit return TRUE; } if ( FAILED( cmdKey.OpenNode( METABASEPATH_WWW_ROOT ) ) || !cmdIISFiltersValue.SetValue( MD_KEY_TYPE, // ID 0, // Attributes IIS_MD_UT_SERVER, // UserType STRING_METADATA, // DataType ( _tcslen( KEYTYPE_FILTERS ) + 1 ) * sizeof(TCHAR), KEYTYPE_FILTERS ) ) // Value { // Failed to open filters node return FALSE; } while ( cmdKey.EnumKeys( szSubNode, i++ ) ) { if ( !IsNumber( szSubNode ) ) { // Since it is not a number, it is not a website, so lets skip continue; } if ( !strFilterKey.Copy( szSubNode ) || !strFilterKey.Append( METABASEPATH_FILTER_PATH ) ) { return FALSE; } // Add the filters node if not already there cmdKey.AddNode( strFilterKey.QueryStr() ); if ( !cmdKey.SetData( cmdIISFiltersValue, MD_KEY_TYPE, strFilterKey.QueryStr() ) || !cmdKey.SetData( cmdValue, MD_ADMIN_ACL, strFilterKey.QueryStr() ) ) { // Failed to set ACL return FALSE; } } return TRUE; } // function: RetrieveFiltersAcl // // Retrieve the Filters ACL to use // BOOL CWebServiceInstallComponent::RetrieveFiltersAcl(CMDValue *pcmdValue) { CMDKey cmdKey; if ( FAILED( cmdKey.OpenNode( METABASEPATH_FILTER_GLOBAL_ROOT ) ) ) { // Failed to open filters node return FALSE; } // Don't inherit acl, but do retrieve if it should be inheritted pcmdValue->SetAttributes( METADATA_ISINHERITED ); if ( !cmdKey.GetData( *pcmdValue, MD_ADMIN_ACL ) ) { // Failed to retrieve value return FALSE; } return TRUE; } // function: IsNumber // // Determine if the string is a number // BOOL CWebServiceInstallComponent::IsNumber( LPWSTR szString ) { while ( *szString ) { if ( ( *szString < '0' ) || ( *szString > '9' ) ) { return FALSE; } szString++; } return TRUE; }
29.77598
173
0.571424
npocmaka
cbe6f9ef05ae9b282678961e29744424f091b87b
10,888
cc
C++
sdk/lib/syslog/cpp/logging_unittest.cc
dahlia-os/fuchsia-pine64-pinephone
57aace6f0b0bd75306426c98ab9eb3ff4524a61d
[ "BSD-3-Clause" ]
14
2020-10-25T05:48:36.000Z
2021-09-20T02:46:20.000Z
sdk/lib/syslog/cpp/logging_unittest.cc
JokeZhang/fuchsia
d6e9dea8dca7a1c8fa89d03e131367e284b30d23
[ "BSD-3-Clause" ]
1
2022-01-14T23:38:40.000Z
2022-01-14T23:38:40.000Z
sdk/lib/syslog/cpp/logging_unittest.cc
JokeZhang/fuchsia
d6e9dea8dca7a1c8fa89d03e131367e284b30d23
[ "BSD-3-Clause" ]
4
2020-12-28T17:04:45.000Z
2022-03-12T03:20:44.000Z
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <lib/syslog/cpp/log_settings.h> #include <lib/syslog/cpp/logging_backend.h> #include <lib/syslog/cpp/macros.h> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "src/lib/files/file.h" #include "src/lib/files/scoped_temp_dir.h" #ifdef __Fuchsia__ #include <lib/syslog/global.h> #include <lib/syslog/logger.h> #include <lib/syslog/wire_format.h> #include <lib/zx/socket.h> #endif namespace syslog { namespace { class LoggingFixture : public ::testing::Test { public: LoggingFixture() : old_severity_(GetMinLogLevel()), old_stderr_(dup(STDERR_FILENO)) {} ~LoggingFixture() { SetLogSettings({.min_log_level = old_severity_}); #ifdef __Fuchsia__ // Go back to using STDERR. fx_logger_t* logger = fx_log_get_logger(); fx_logger_activate_fallback(logger, -1); #else dup2(old_stderr_, STDERR_FILENO); #endif } private: LogSeverity old_severity_; int old_stderr_; }; using LoggingFixtureDeathTest = LoggingFixture; TEST_F(LoggingFixture, Log) { LogSettings new_settings; EXPECT_EQ(LOG_INFO, new_settings.min_log_level); files::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.NewTempFile(&new_settings.log_file)); SetLogSettings(new_settings); int error_line = __LINE__ + 1; FX_LOGS(ERROR) << "something at error"; int info_line = __LINE__ + 1; FX_LOGS(INFO) << "and some other at info level"; std::string log; ASSERT_TRUE(files::ReadFileToString(new_settings.log_file, &log)); #ifdef __Fuchsia__ EXPECT_THAT(log, testing::HasSubstr("ERROR: [sdk/lib/syslog/cpp/logging_unittest.cc(" + std::to_string(error_line) + ")] something at error")); EXPECT_THAT(log, testing::HasSubstr("INFO: [logging_unittest.cc(" + std::to_string(info_line) + ")] and some other at info level")); #else EXPECT_THAT(log, testing::HasSubstr("[ERROR:sdk/lib/syslog/cpp/logging_unittest.cc(" + std::to_string(error_line) + ")] something at error")); EXPECT_THAT(log, testing::HasSubstr("[INFO:logging_unittest.cc(" + std::to_string(info_line) + ")] and some other at info level")); #endif } TEST_F(LoggingFixture, LogFirstN) { constexpr int kLimit = 5; constexpr int kCycles = 20; constexpr const char* kLogMessage = "Hello"; static_assert(kCycles > kLimit); LogSettings new_settings; EXPECT_EQ(LOG_INFO, new_settings.min_log_level); files::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.NewTempFile(&new_settings.log_file)); SetLogSettings(new_settings); for (int i = 0; i < kCycles; ++i) { FX_LOGS_FIRST_N(ERROR, kLimit) << kLogMessage; } std::string log; ASSERT_TRUE(files::ReadFileToString(new_settings.log_file, &log)); int count = 0; size_t pos = 0; while ((pos = log.find(kLogMessage, pos)) != std::string::npos) { ++count; ++pos; } EXPECT_EQ(kLimit, count); } TEST_F(LoggingFixture, LogT) { LogSettings new_settings; EXPECT_EQ(LOG_INFO, new_settings.min_log_level); files::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.NewTempFile(&new_settings.log_file)); SetLogSettings(new_settings); int error_line = __LINE__ + 1; FX_LOGST(ERROR, "first") << "something at error"; int info_line = __LINE__ + 1; FX_LOGST(INFO, "second") << "and some other at info level"; std::string log; ASSERT_TRUE(files::ReadFileToString(new_settings.log_file, &log)); #ifdef __Fuchsia__ EXPECT_THAT(log, testing::HasSubstr("first] ERROR: [sdk/lib/syslog/cpp/logging_unittest.cc(" + std::to_string(error_line) + ")] something at error")); EXPECT_THAT(log, testing::HasSubstr("second] INFO: [logging_unittest.cc(" + std::to_string(info_line) + ")] and some other at info level")); #else EXPECT_THAT(log, testing::HasSubstr("[first] [ERROR:sdk/lib/syslog/cpp/logging_unittest.cc(" + std::to_string(error_line) + ")] something at error")); EXPECT_THAT(log, testing::HasSubstr("[second] [INFO:logging_unittest.cc(" + std::to_string(info_line) + ")] and some other at info level")); #endif } TEST_F(LoggingFixture, VLogT) { LogSettings new_settings; new_settings.min_log_level = (LOG_INFO - 2); // verbosity = 2 files::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.NewTempFile(&new_settings.log_file)); SetLogSettings(new_settings, {}); int line = __LINE__ + 1; FX_VLOGST(1, "first") << "First message"; FX_VLOGST(2, "second") << "ABCD"; FX_VLOGST(3, "third") << "EFGH"; std::string log; ASSERT_TRUE(files::ReadFileToString(new_settings.log_file, &log)); EXPECT_THAT(log, testing::HasSubstr("[first] VLOG(1): [logging_unittest.cc(" + std::to_string(line) + ")] First message")); EXPECT_THAT(log, testing::HasSubstr("second")); EXPECT_THAT(log, testing::HasSubstr("ABCD")); EXPECT_THAT(log, testing::Not(testing::HasSubstr("third"))); EXPECT_THAT(log, testing::Not(testing::HasSubstr("EFGH"))); } TEST_F(LoggingFixture, VlogVerbosity) { LogSettings new_settings; EXPECT_EQ(LOG_INFO, new_settings.min_log_level); EXPECT_EQ(0, GetVlogVerbosity()); new_settings.min_log_level = LOG_INFO - 1; SetLogSettings(new_settings); EXPECT_EQ(1, GetVlogVerbosity()); new_settings.min_log_level = LOG_INFO - 15; SetLogSettings(new_settings); EXPECT_EQ(15, GetVlogVerbosity()); new_settings.min_log_level = LOG_DEBUG; SetLogSettings(new_settings); EXPECT_EQ(0, GetVlogVerbosity()); } TEST_F(LoggingFixture, DVLogNoMinLevel) { LogSettings new_settings; EXPECT_EQ(LOG_INFO, new_settings.min_log_level); files::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.NewTempFile(&new_settings.log_file)); SetLogSettings(new_settings); FX_DVLOGS(1) << "hello"; std::string log; ASSERT_TRUE(files::ReadFileToString(new_settings.log_file, &log)); EXPECT_EQ(log, ""); } TEST_F(LoggingFixture, DVLogWithMinLevel) { LogSettings new_settings; EXPECT_EQ(LOG_INFO, new_settings.min_log_level); new_settings.min_log_level = (LOG_INFO - 1); files::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.NewTempFile(&new_settings.log_file)); SetLogSettings(new_settings); FX_DVLOGS(1) << "hello"; std::string log; ASSERT_TRUE(files::ReadFileToString(new_settings.log_file, &log)); #if defined(NDEBUG) EXPECT_EQ(log, ""); #else EXPECT_THAT(log, testing::HasSubstr("hello")); #endif } TEST_F(LoggingFixtureDeathTest, CheckFailed) { ASSERT_DEATH(FX_CHECK(false), ""); } #if defined(__Fuchsia__) TEST_F(LoggingFixture, Plog) { LogSettings new_settings; EXPECT_EQ(LOG_INFO, new_settings.min_log_level); files::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.NewTempFile(&new_settings.log_file)); SetLogSettings(new_settings); FX_PLOGS(ERROR, ZX_OK) << "should be ok"; FX_PLOGS(ERROR, ZX_ERR_ACCESS_DENIED) << "got access denied"; std::string log; ASSERT_TRUE(files::ReadFileToString(new_settings.log_file, &log)); EXPECT_THAT(log, testing::HasSubstr("should be ok: 0 (ZX_OK)")); EXPECT_THAT(log, testing::HasSubstr("got access denied: -30 (ZX_ERR_ACCESS_DENIED)")); } TEST_F(LoggingFixture, PlogT) { LogSettings new_settings; EXPECT_EQ(LOG_INFO, new_settings.min_log_level); files::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.NewTempFile(&new_settings.log_file)); SetLogSettings(new_settings); int line1 = __LINE__ + 1; FX_PLOGST(ERROR, "abcd", ZX_OK) << "should be ok"; int line2 = __LINE__ + 1; FX_PLOGST(ERROR, "qwerty", ZX_ERR_ACCESS_DENIED) << "got access denied"; std::string log; ASSERT_TRUE(files::ReadFileToString(new_settings.log_file, &log)); EXPECT_THAT(log, testing::HasSubstr("abcd] ERROR: [sdk/lib/syslog/cpp/logging_unittest.cc(" + std::to_string(line1) + ")] should be ok: 0 (ZX_OK)")); EXPECT_THAT(log, testing::HasSubstr("qwerty] ERROR: [sdk/lib/syslog/cpp/logging_unittest.cc(" + std::to_string(line2) + ")] got access denied: -30 (ZX_ERR_ACCESS_DENIED)")); } #endif // defined(__Fuchsia__) TEST_F(LoggingFixture, SLog) { LogSettings new_settings; EXPECT_EQ(LOG_INFO, new_settings.min_log_level); files::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.NewTempFile(&new_settings.log_file)); SetLogSettings(new_settings); int line1 = __LINE__ + 1; FX_SLOG(ERROR)("tag", "String log"); int line2 = __LINE__ + 1; FX_SLOG(ERROR)("tag", 42); int line3 = __LINE__ + 1; FX_SLOG(ERROR)("tag", {42, "string"}); int line4 = __LINE__ + 1; FX_SLOG(ERROR)("tag", {"first"_k = 42, "second"_k = "string"}); int line5 = __LINE__ + 1; FX_SLOG(ERROR)("String log"); std::string log; ASSERT_TRUE(files::ReadFileToString(new_settings.log_file, &log)); EXPECT_THAT(log, testing::HasSubstr("tag] ERROR: [sdk/lib/syslog/cpp/logging_unittest.cc(" + std::to_string(line1) + ")] String log")); EXPECT_THAT(log, testing::HasSubstr("tag] ERROR: [sdk/lib/syslog/cpp/logging_unittest.cc(" + std::to_string(line2) + ")] 42")); EXPECT_THAT(log, testing::HasSubstr("tag] ERROR: [sdk/lib/syslog/cpp/logging_unittest.cc(" + std::to_string(line3) + ")] [42, \"string\"]")); EXPECT_THAT(log, testing::HasSubstr("tag] ERROR: [sdk/lib/syslog/cpp/logging_unittest.cc(" + std::to_string(line4) + ")] {\"first\": 42, \"second\": \"string\"}")); EXPECT_THAT(log, testing::HasSubstr("String log] ERROR: [sdk/lib/syslog/cpp/logging_unittest.cc(" + std::to_string(line5) + ")]")); } TEST_F(LoggingFixture, BackendDirect) { LogSettings new_settings; EXPECT_EQ(LOG_INFO, new_settings.min_log_level); files::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.NewTempFile(&new_settings.log_file)); SetLogSettings(new_settings); syslog_backend::WriteLog(syslog::LOG_ERROR, "foo.cc", 42, "fake tag", "condition", "Log message"); syslog_backend::WriteLogValue(syslog::LOG_ERROR, "foo.cc", 42, "fake tag", "condition", {"foo"_k = 42}); std::string log; ASSERT_TRUE(files::ReadFileToString(new_settings.log_file, &log)); EXPECT_THAT(log, testing::HasSubstr("ERROR: [foo.cc(42)] Check failed: condition. Log message\n")); EXPECT_THAT(log, testing::HasSubstr("ERROR: [foo.cc(42)] Check failed: condition. {\"foo\": 42}\n")); } } // namespace } // namespace syslog
33.195122
100
0.673035
dahlia-os
cbe87e0656a63e5395e46851df7dd8290e5e7831
368
cpp
C++
src/Render/ShaderImporter/ShaderImporterRegister_FillMode.cpp
Ubpa/DustEngine
4fc32d4011ce21ab5ab2a8149e398d9baa3cbdc0
[ "MIT" ]
9
2020-08-03T02:11:07.000Z
2020-09-29T09:12:45.000Z
src/Render/ShaderImporter/ShaderImporterRegister_FillMode.cpp
Ubpa/DustEngine
4fc32d4011ce21ab5ab2a8149e398d9baa3cbdc0
[ "MIT" ]
null
null
null
src/Render/ShaderImporter/ShaderImporterRegister_FillMode.cpp
Ubpa/DustEngine
4fc32d4011ce21ab5ab2a8149e398d9baa3cbdc0
[ "MIT" ]
1
2020-08-10T03:34:52.000Z
2020-08-10T03:34:52.000Z
#include "ShaderImporterRegisterImpl.h" #include <Utopia/Render/RenderState.h> using namespace Ubpa::Utopia; using namespace Ubpa::UDRefl; void Ubpa::Utopia::details::ShaderImporterRegister_FillMode() { UDRefl::Mngr.RegisterType<FillMode>(); UDRefl::Mngr.SimpleAddField<FillMode::WIREFRAME>("WIREFRAME"); UDRefl::Mngr.SimpleAddField<FillMode::SOLID>("SOLID"); }
28.307692
63
0.779891
Ubpa
cbeb6fc37640ac96d23eb339c45b0d391d9554d1
926
hpp
C++
sdk/boost_1_30_0/boost/preprocessor/comparison.hpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
10
2021-05-04T06:40:27.000Z
2022-01-20T20:24:28.000Z
sdk/boost_1_30_0/boost/preprocessor/comparison.hpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
null
null
null
sdk/boost_1_30_0/boost/preprocessor/comparison.hpp
acidicMercury8/xray-1.0
65e85c0e31e82d612c793d980dc4b73fa186c76c
[ "Linux-OpenIB" ]
2
2020-05-17T10:01:14.000Z
2020-09-11T20:17:27.000Z
# /* Copyright (C) 2001 # * Housemarque Oy # * http://www.housemarque.com # * # * Permission to copy, use, modify, sell and distribute this software is # * granted provided this copyright notice appears in all copies. This # * software is provided "as is" without express or implied warranty, and # * with no claim as to its suitability for any purpose. # */ # # /* Revised by Paul Mensonides (2002) */ # # /* See http://www.boost.org for most recent version. */ # # ifndef BOOST_PREPROCESSOR_COMPARISON_HPP # define BOOST_PREPROCESSOR_COMPARISON_HPP # # include <boost/preprocessor/comparison/equal.hpp> # include <boost/preprocessor/comparison/greater.hpp> # include <boost/preprocessor/comparison/greater_equal.hpp> # include <boost/preprocessor/comparison/less.hpp> # include <boost/preprocessor/comparison/less_equal.hpp> # include <boost/preprocessor/comparison/not_equal.hpp> # # endif
35.615385
75
0.730022
acidicMercury8
cbf49c5a24e61e4f2b4d97be0848f6efdc9ebb5b
4,236
hpp
C++
Manipulation.hpp
theoden8/rubikscube
94ffd4a99f03729b28db41f1b05cbb208b4eceba
[ "MIT" ]
1
2021-03-22T22:14:49.000Z
2021-03-22T22:14:49.000Z
Manipulation.hpp
theoden8/rubikscube
94ffd4a99f03729b28db41f1b05cbb208b4eceba
[ "MIT" ]
null
null
null
Manipulation.hpp
theoden8/rubikscube
94ffd4a99f03729b28db41f1b05cbb208b4eceba
[ "MIT" ]
null
null
null
#pragma once #include <cmath> #ifndef M_PI #define M_PI 3.141592653589793238462643383279502884L #endif #include <vector> #include <queue> #include <Logger.hpp> #include <Debug.hpp> #include <Face.hpp> struct Manipulation { const Face face; const Rotation rot; float progress = 0.; /* inline Manipulation() */ /* {} */ inline Manipulation(Face f, Rotation r, float progress=0.): face(f), rot(r), progress(progress) {} static Manipulation make_random() { return Manipulation(get_random_face(), get_random_rotation()); } inline bool is_complete() const { /* Logger::Info("progress: %.4f, %.4f\n", progress, std::abs(1.-progress)); */ return std::abs(progress - 1.0) < 1e-5; } inline bool is_close() const { return std::abs(progress - 1.0) < 1e-2; } inline decltype(auto) inverse() const { return Manipulation( face, rot == Rotation::CLOCKWISE ? Rotation::COUNTERCLOCKWISE : Rotation::CLOCKWISE, 1. - progress ); } }; class ManipulationPerformer { std::vector<Manipulation> timeline; std::queue<Manipulation> performQueue; int currentIndex = -1; float speed = 1.; double previous_time = 0.; template <typename RubiksCubeT> void rotate_face(RubiksCubeT &rb, const Manipulation &m, float deg) { static constexpr glm::vec3 axis_z(0, 0, 1), axis_y(0, 1, 0), axis_x(1, 0, 0); glm::vec3 axis; float sign = 0.; const Face &f = m.face; const Rotation &r = m.rot; if((f == Face::Z_FRONT && r == Rotation::CLOCKWISE) || (f == Face::Z_BACK && r == Rotation::COUNTERCLOCKWISE)) { axis = axis_z; sign = 1.; } else if((f == Face::Z_BACK && r == Rotation::CLOCKWISE) || (f == Face::Z_FRONT && r == Rotation::COUNTERCLOCKWISE)) { axis = axis_z; sign = -1.; } else if((f == Face::Y_FRONT && r == Rotation::CLOCKWISE) || (f == Face::Y_BACK && r == Rotation::COUNTERCLOCKWISE)) { axis = axis_y; sign = 1.; } else if((f == Face::Y_BACK && r == Rotation::CLOCKWISE) || (f == Face::Y_FRONT && r == Rotation::COUNTERCLOCKWISE)) { axis = axis_y; sign = -1.; } else if((f == Face::X_FRONT && r == Rotation::CLOCKWISE) || (f == Face::X_BACK && r == Rotation::COUNTERCLOCKWISE)) { axis = axis_x; sign = 1.; } else if((f == Face::X_BACK && r == Rotation::CLOCKWISE) || (f == Face::X_FRONT && r == Rotation::COUNTERCLOCKWISE)) { axis = axis_x; sign = -1.; } rb.select_face(f, [&](Facing &f, const Face &face) mutable -> void { f.getCubeTransform().Rotate(axis, sign * deg); }); } public: ManipulationPerformer() {} template <typename RubiksCubeT> void rotate_face(RubiksCubeT &rb, Manipulation &m) { if(m.is_complete())return; double current_time_step = fmax(glfwGetTime() - previous_time, .5); float deg = std::sin((0.5 + m.progress * .5) * M_PI) * 90. * .03 * current_time_step * speed * std::sqrt(performQueue.size()); #if !defined(_POSIX_VERSION) deg *= 10; #endif if((m.progress + deg / 90. > 1.) || m.is_close()) { deg = (1. - m.progress) * 90.; } rotate_face(rb, m, deg); m.progress = (m.progress * 90. + deg) / 90.; previous_time = glfwGetTime(); } void set_new(Manipulation m) { ++currentIndex; if(currentIndex == timeline.size()) { timeline.push_back(m); performQueue.push(m); } else { while(currentIndex < timeline.size()) { performQueue.push(timeline.back().inverse()); performQueue.pop(); } timeline.push_back(m); performQueue.push(m); } } void take_back() { if(currentIndex == -1)return; Manipulation m = timeline[currentIndex--].inverse(); m.progress = 0.; performQueue.push(m); } int count() const { return currentIndex + 1; } template <typename RubiksCubeT> void perform_step(RubiksCubeT &rb) { if(performQueue.empty())return; while(performQueue.front().is_complete()) { rb.update_face_types(performQueue.front()); performQueue.pop(); if(performQueue.empty())return; } rotate_face(rb, performQueue.front()); } };
24.485549
130
0.595373
theoden8
cbf69c5dd1c88758b676cdbdba78f8059d3ae2df
13,160
hpp
C++
src/util/lp/square_dense_submatrix.hpp
greatmazinger/z3
52e9ddcb64e1d1dc94f280801995f4b30c8fe58b
[ "MIT" ]
18
2018-05-25T03:16:11.000Z
2022-01-25T01:41:20.000Z
src/util/lp/square_dense_submatrix.hpp
greatmazinger/z3
52e9ddcb64e1d1dc94f280801995f4b30c8fe58b
[ "MIT" ]
null
null
null
src/util/lp/square_dense_submatrix.hpp
greatmazinger/z3
52e9ddcb64e1d1dc94f280801995f4b30c8fe58b
[ "MIT" ]
9
2019-11-12T05:42:08.000Z
2022-02-18T01:09:53.000Z
/*++ Copyright (c) 2017 Microsoft Corporation Module Name: <name> Abstract: <abstract> Author: Lev Nachmanson (levnach) Revision History: --*/ #include "util/vector.h" #include "util/lp/square_dense_submatrix.h" namespace lp { template <typename T, typename X> square_dense_submatrix<T, X>::square_dense_submatrix (sparse_matrix<T, X> *parent_matrix, unsigned index_start) : m_index_start(index_start), m_dim(parent_matrix->dimension() - index_start), m_v(m_dim * m_dim), m_parent(parent_matrix), m_row_permutation(m_parent->dimension()), m_column_permutation(m_parent->dimension()) { int row_offset = - static_cast<int>(m_index_start); for (unsigned i = index_start; i < parent_matrix->dimension(); i++) { unsigned row = parent_matrix->adjust_row(i); for (auto & iv : parent_matrix->get_row_values(row)) { unsigned j = parent_matrix->adjust_column_inverse(iv.m_index); SASSERT(j>= m_index_start); m_v[row_offset + j] = iv.m_value; } row_offset += m_dim; } } template <typename T, typename X> void square_dense_submatrix<T, X>::init(sparse_matrix<T, X> *parent_matrix, unsigned index_start) { m_index_start = index_start; m_dim = parent_matrix->dimension() - index_start; m_v.resize(m_dim * m_dim); m_parent = parent_matrix; m_column_permutation.init(m_parent->dimension()); for (unsigned i = index_start; i < parent_matrix->dimension(); i++) { unsigned row = parent_matrix->adjust_row(i); for (auto & iv : parent_matrix->get_row_values(row)) { unsigned j = parent_matrix->adjust_column_inverse(iv.m_index); (*this)[i][j] = iv.m_value; } } } template <typename T, typename X> int square_dense_submatrix<T, X>::find_pivot_column_in_row(unsigned i) const { int j = -1; T max = zero_of_type<T>(); SASSERT(i >= m_index_start); unsigned row_start = (i - m_index_start) * m_dim; for (unsigned k = i; k < m_parent->dimension(); k++) { unsigned col = adjust_column(k); // this is where the column is in the row unsigned offs = row_start + col - m_index_start; T t = abs(m_v[offs]); if (t > max) { j = k; max = t; } } return j; } template <typename T, typename X> void square_dense_submatrix<T, X>::pivot(unsigned i, lp_settings & settings) { divide_row_by_pivot(i); for (unsigned k = i + 1; k < m_parent->dimension(); k++) pivot_row_to_row(i, k, settings); } template <typename T, typename X> void square_dense_submatrix<T, X>::pivot_row_to_row(unsigned i, unsigned row, lp_settings & settings) { SASSERT(i < row); unsigned pj = adjust_column(i); // the pivot column unsigned pjd = pj - m_index_start; unsigned pivot_row_offset = (i-m_index_start)*m_dim; T pivot = m_v[pivot_row_offset + pjd]; unsigned row_offset= (row-m_index_start)*m_dim; T m = m_v[row_offset + pjd]; SASSERT(!is_zero(pivot)); m_v[row_offset + pjd] = -m * pivot; // creating L matrix for (unsigned j = m_index_start; j < m_parent->dimension(); j++) { if (j == pj) { pivot_row_offset++; row_offset++; continue; } auto t = m_v[row_offset] - m_v[pivot_row_offset] * m; if (settings.abs_val_is_smaller_than_drop_tolerance(t)) { m_v[row_offset] = zero_of_type<T>(); } else { m_v[row_offset] = t; } row_offset++; pivot_row_offset++; // at the same time we pivot the L too } } template <typename T, typename X> void square_dense_submatrix<T, X>::divide_row_by_pivot(unsigned i) { unsigned pj = adjust_column(i); // the pivot column unsigned irow_offset = (i - m_index_start) * m_dim; T pivot = m_v[irow_offset + pj - m_index_start]; SASSERT(!is_zero(pivot)); for (unsigned k = m_index_start; k < m_parent->dimension(); k++) { if (k == pj){ m_v[irow_offset++] = one_of_type<T>() / pivot; // creating the L matrix diagonal continue; } m_v[irow_offset++] /= pivot; } } template <typename T, typename X> void square_dense_submatrix<T, X>::update_parent_matrix(lp_settings & settings) { for (unsigned i = m_index_start; i < m_parent->dimension(); i++) update_existing_or_delete_in_parent_matrix_for_row(i, settings); push_new_elements_to_parent_matrix(settings); for (unsigned i = m_index_start; i < m_parent->dimension(); i++) m_parent->set_max_in_row(m_parent->adjust_row(i)); } template <typename T, typename X> void square_dense_submatrix<T, X>::update_existing_or_delete_in_parent_matrix_for_row(unsigned i, lp_settings & settings) { bool diag_updated = false; unsigned ai = m_parent->adjust_row(i); auto & row_vals = m_parent->get_row_values(ai); for (unsigned k = 0; k < row_vals.size(); k++) { auto & iv = row_vals[k]; unsigned j = m_parent->adjust_column_inverse(iv.m_index); if (j < i) { m_parent->remove_element(row_vals, iv); k--; } else if (i == j) { m_parent->m_columns[iv.m_index].m_values[iv.m_other].set_value(iv.m_value = one_of_type<T>()); diag_updated = true; } else { // j > i T & v = (*this)[i][j]; if (settings.abs_val_is_smaller_than_drop_tolerance(v)) { m_parent->remove_element(row_vals, iv); k--; } else { m_parent->m_columns[iv.m_index].m_values[iv.m_other].set_value(iv.m_value = v); v = zero_of_type<T>(); // only new elements are left above the diagonal } } } if (!diag_updated) { unsigned aj = m_parent->adjust_column(i); m_parent->add_new_element(ai, aj, one_of_type<T>()); } } template <typename T, typename X> void square_dense_submatrix<T, X>::push_new_elements_to_parent_matrix(lp_settings & settings) { for (unsigned i = m_index_start; i < m_parent->dimension() - 1; i++) { unsigned ai = m_parent->adjust_row(i); for (unsigned j = i + 1; j < m_parent->dimension(); j++) { T & v = (*this)[i][j]; if (!settings.abs_val_is_smaller_than_drop_tolerance(v)) { unsigned aj = m_parent->adjust_column(j); m_parent->add_new_element(ai, aj, v); } v = zero_of_type<T>(); // leave only L elements now } } } template <typename T, typename X> template <typename L> L square_dense_submatrix<T, X>::row_by_vector_product(unsigned i, const vector<L> & v) { SASSERT(i >= m_index_start); unsigned row_in_subm = i - m_index_start; unsigned row_offset = row_in_subm * m_dim; L r = zero_of_type<L>(); for (unsigned j = 0; j < m_dim; j++) r += m_v[row_offset + j] * v[adjust_column_inverse(m_index_start + j)]; return r; } template <typename T, typename X> template <typename L> L square_dense_submatrix<T, X>::column_by_vector_product(unsigned j, const vector<L> & v) { SASSERT(j >= m_index_start); unsigned offset = j - m_index_start; L r = zero_of_type<L>(); for (unsigned i = 0; i < m_dim; i++, offset += m_dim) r += m_v[offset] * v[adjust_row_inverse(m_index_start + i)]; return r; } template <typename T, typename X> template <typename L> L square_dense_submatrix<T, X>::row_by_indexed_vector_product(unsigned i, const indexed_vector<L> & v) { SASSERT(i >= m_index_start); unsigned row_in_subm = i - m_index_start; unsigned row_offset = row_in_subm * m_dim; L r = zero_of_type<L>(); for (unsigned j = 0; j < m_dim; j++) r += m_v[row_offset + j] * v[adjust_column_inverse(m_index_start + j)]; return r; } template <typename T, typename X> template <typename L> void square_dense_submatrix<T, X>::apply_from_left_local(indexed_vector<L> & w, lp_settings & settings) { #ifdef Z3DEBUG // dense_matrix<T, X> deb(*this); // vector<L> deb_w(w.m_data.size()); // for (unsigned i = 0; i < w.m_data.size(); i++) // deb_w[i] = w[i]; // deb.apply_from_left(deb_w); #endif // use indexed vector here #ifndef DO_NOT_USE_INDEX vector<L> t(m_parent->dimension(), zero_of_type<L>()); for (auto k : w.m_index) { unsigned j = adjust_column(k); // k-th element will contribute only to column j if (j < m_index_start || j >= this->m_index_start + this->m_dim) { // it is a unit matrix outside t[adjust_row_inverse(j)] = w[k]; } else { const L & v = w[k]; for (unsigned i = 0; i < m_dim; i++) { unsigned row = adjust_row_inverse(m_index_start + i); unsigned offs = i * m_dim + j - m_index_start; t[row] += m_v[offs] * v; } } } w.m_index.clear(); for (unsigned i = 0; i < m_parent->dimension(); i++) { const L & v = t[i]; if (!settings.abs_val_is_smaller_than_drop_tolerance(v)){ w.m_index.push_back(i); w.m_data[i] = v; } else { w.m_data[i] = zero_of_type<L>(); } } #else vector<L> t(m_parent->dimension()); for (unsigned i = 0; i < m_index_start; i++) { t[adjust_row_inverse(i)] = w[adjust_column_inverse(i)]; } for (unsigned i = m_index_start; i < m_parent->dimension(); i++){ t[adjust_row_inverse(i)] = row_by_indexed_vector_product(i, w); } for (unsigned i = 0; i < m_parent->dimension(); i++) { w.set_value(t[i], i); } for (unsigned i = 0; i < m_parent->dimension(); i++) { const L & v = t[i]; if (!is_zero(v)) w.m_index.push_back(i); w.m_data[i] = v; } #endif #ifdef Z3DEBUG // cout << "w final" << endl; // print_vector(w.m_data); // SASSERT(vectors_are_equal<T>(deb_w, w.m_data)); // SASSERT(w.is_OK()); #endif } template <typename T, typename X> template <typename L> void square_dense_submatrix<T, X>::apply_from_left_to_vector(vector<L> & w) { // lp_settings & settings) { // dense_matrix<T, L> deb(*this); // vector<L> deb_w(w); // deb.apply_from_left_to_X(deb_w, settings); // // cout << "deb" << endl; // // print_matrix(deb); // // cout << "w" << endl; // // print_vector(w.m_data); // // cout << "deb_w" << endl; // // print_vector(deb_w); vector<L> t(m_parent->dimension()); for (unsigned i = 0; i < m_index_start; i++) { t[adjust_row_inverse(i)] = w[adjust_column_inverse(i)]; } for (unsigned i = m_index_start; i < m_parent->dimension(); i++){ t[adjust_row_inverse(i)] = row_by_vector_product(i, w); } for (unsigned i = 0; i < m_parent->dimension(); i++) { w[i] = t[i]; } #ifdef Z3DEBUG // cout << "w final" << endl; // print_vector(w.m_data); // SASSERT(vectors_are_equal<L>(deb_w, w)); #endif } template <typename T, typename X> bool square_dense_submatrix<T, X>::is_L_matrix() const { #ifdef Z3DEBUG SASSERT(m_row_permutation.is_identity()); for (unsigned i = 0; i < m_parent->dimension(); i++) { if (i < m_index_start) { SASSERT(m_column_permutation[i] == i); continue; } unsigned row_offs = (i-m_index_start)*m_dim; for (unsigned k = 0; k < m_dim; k++) { unsigned j = m_index_start + k; unsigned jex = adjust_column_inverse(j); if (jex > i) { SASSERT(is_zero(m_v[row_offs + k])); } else if (jex == i) { SASSERT(!is_zero(m_v[row_offs + k])); } } } #endif return true; } template <typename T, typename X> void square_dense_submatrix<T, X>::apply_from_right(vector<T> & w) { #ifdef Z3DEBUG // dense_matrix<T, X> deb(*this); // vector<T> deb_w(w); // deb.apply_from_right(deb_w); #endif vector<T> t(w.size()); for (unsigned j = 0; j < m_index_start; j++) { t[adjust_column_inverse(j)] = w[adjust_row_inverse(j)]; } unsigned end = m_index_start + m_dim; for (unsigned j = end; j < m_parent->dimension(); j++) { t[adjust_column_inverse(j)] = w[adjust_row_inverse(j)]; } for (unsigned j = m_index_start; j < end; j++) { t[adjust_column_inverse(j)] = column_by_vector_product(j, w); } w = t; #ifdef Z3DEBUG // SASSERT(vector_are_equal<T>(deb_w, w)); #endif } #ifdef Z3DEBUG template <typename T, typename X> T square_dense_submatrix<T, X>::get_elem (unsigned i, unsigned j) const { i = adjust_row(i); j = adjust_column(j); if (i < m_index_start || j < m_index_start) return i == j? one_of_type<T>() : zero_of_type<T>(); unsigned offs = (i - m_index_start)* m_dim + j - m_index_start; return m_v[offs]; } #endif template <typename T, typename X> void square_dense_submatrix<T, X>::conjugate_by_permutation(permutation_matrix<T, X> & q) { m_row_permutation.multiply_by_permutation_from_left(q); m_column_permutation.multiply_by_reverse_from_right(q); } }
35.663957
160
0.607979
greatmazinger
cbf72f21062fb5d21cb485db47a0c04898cd36de
7,545
cpp
C++
src/liblvr2/io/BoctreeIO.cpp
uos/lvr
9bb03a30441b027c39db967318877e03725112d5
[ "BSD-3-Clause" ]
38
2019-06-19T15:10:35.000Z
2022-02-16T03:08:24.000Z
src/liblvr2/io/BoctreeIO.cpp
uos/lvr
9bb03a30441b027c39db967318877e03725112d5
[ "BSD-3-Clause" ]
9
2019-06-19T16:19:51.000Z
2021-09-17T08:31:25.000Z
src/liblvr2/io/BoctreeIO.cpp
uos/lvr
9bb03a30441b027c39db967318877e03725112d5
[ "BSD-3-Clause" ]
13
2019-04-16T11:50:32.000Z
2020-11-26T07:47:44.000Z
/** * Copyright (c) 2018, University Osnabrück * 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 University Osnabrück 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 University Osnabrück 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. */ /** * BoctreeIO.cpp * * @date 23.08.2012 * @author Thomas Wiemann */ #include <stdio.h> #include "lvr2/io/BoctreeIO.hpp" #include "lvr2/io/Timestamp.hpp" #include <slam6d/Boctree.h> namespace lvr2 { BoctreeIO::BoctreeIO() { } BoctreeIO::~BoctreeIO() { } ModelPtr BoctreeIO::read(string directory ) { int numScans = 0; int firstScan = -1; int lastScan = -1; // First, look for .oct files boost::filesystem::directory_iterator lastFile; for(boost::filesystem::directory_iterator it(directory); it != lastFile; it++ ) { boost::filesystem::path p = it->path(); if(string(p.extension().string().c_str()) == ".oct") { // Check for naming convention "scanxxx.3d" int num = 0; if(sscanf(p.filename().string().c_str(), "scan%3d", &num)) { numScans++; if(firstScan == -1) firstScan = num; if(lastScan == -1) lastScan = num; if(num > lastScan) lastScan = num; if(num < firstScan) firstScan = num; } } } list<Point> allPoints; if(numScans) { for(int i = 0; i < numScans; i++) { char scanfile[128]; sprintf(scanfile, "%sscan%03d.oct", directory.c_str(), firstScan + i); cout << timestamp << "Reading " << scanfile << endl; Matrix4<Vec> tf; vector<Point> points; BOctTree<float>::deserialize(scanfile, points); // Try to get transformation from .frames file boost::filesystem::path frame_path( boost::filesystem::path(directory) / boost::filesystem::path( "scan" + to_string( firstScan + i, 3 ) + ".frames" ) ); string frameFileName = "/" + frame_path.relative_path().string(); ifstream frame_in(frameFileName.c_str()); if(!frame_in.good()) { // Try to parse .pose file boost::filesystem::path pose_path( boost::filesystem::path(directory) / boost::filesystem::path( "scan" + to_string( firstScan + i, 3 ) + ".pose" ) ); string poseFileName = "/" + pose_path.relative_path().string(); ifstream pose_in(poseFileName.c_str()); if(pose_in.good()) { float euler[6]; for(int i = 0; i < 6; i++) pose_in >> euler[i]; Vec position(euler[0], euler[1], euler[2]); Vec angle(euler[3], euler[4], euler[5]); tf = Matrix4<Vec>(position, angle); } else { cout << timestamp << "UOS Reader: Warning: No position information found." << endl; tf = Matrix4<Vec>(); } } else { // Use transformation from .frame files tf = parseFrameFile(frame_in); } // Ugly hack to transform scan data for(int j = 0; j < points.size(); j++) { Vec v(points[j].x, points[j].y, points[j].z); v = tf * v; if(v.length() < 10000) { points[j].x = v[0]; points[j].y = v[1]; points[j].z = v[2]; allPoints.push_back(points[j]); } } } } cout << timestamp << "Read " << allPoints.size() << " points." << endl; ModelPtr model( new Model ); if(allPoints.size()) { floatArr points(new float[3 * allPoints.size()]); ucharArr colors(new unsigned char[3 * allPoints.size()]); floatArr intensities( new float[allPoints.size()]); int i = 0; bool found_color = false; float min_r = 1e10; float max_r = -1e10; for(list<Point>::iterator it = allPoints.begin(); it != allPoints.end(); it++) { Point p = *it; points[3 * i ] = p.x; points[3 * i + 1] = p.y; points[3 * i + 2] = p.z; colors[3 * i ] = p.rgb[0]; colors[3 * i + 1] = p.rgb[1]; colors[3 * i + 2] = p.rgb[2]; if(p.rgb[0] != 255 && p.rgb[1] != 255 && p.rgb[2] != 255) { found_color = true; } intensities[i] = p.reflectance; if(intensities[i] < min_r) min_r = intensities[i]; if(intensities[i] > max_r) max_r = intensities[i]; //cout << p.reflectance << " " << p.amplitude << " " << p.deviation << endl; i++; } // // Map reflectances to 0..255 // float r_diff = max_r - min_r; // if(r_diff > 0) // { // size_t np = allPoints.size(); // float b_size = r_diff / 255.0; // for(int a = 0; a < np; a++) // { // float value = intensities[a]; // value -= min_r; // value /= b_size; // //cout << value << endl; // intensities[a] = value; // } // } model->m_pointCloud = PointBufferPtr( new PointBuffer ); model->m_pointCloud->setPointArray(points, allPoints.size()); model->m_pointCloud->setColorArray(colors, allPoints.size()); model->m_pointCloud->addFloatChannel(intensities, "intensities", allPoints.size(), 1); } return model; } void BoctreeIO::save( string filename ) { } Matrix4<Vec> BoctreeIO::parseFrameFile(ifstream& frameFile) { float m[16], color; while(frameFile.good()) { for(int i = 0; i < 16; i++ && frameFile.good()) frameFile >> m[i]; frameFile >> color; } return Matrix4<Vec>(m); } } /* namespace lvr2 */
31.701681
103
0.533333
uos
cbf736ce4a477ce6fe1054fb591394ad3b9fcdf8
2,115
hpp
C++
src/misc/containers.hpp
kmaninis/COB_public
e4cb02a4c6e9ffa85951bec36846581dc98e68de
[ "BSD-2-Clause-FreeBSD" ]
205
2016-08-10T04:13:40.000Z
2022-01-28T08:57:37.000Z
src/misc/containers.hpp
kmaninis/COB_public
e4cb02a4c6e9ffa85951bec36846581dc98e68de
[ "BSD-2-Clause-FreeBSD" ]
19
2016-09-19T13:05:59.000Z
2021-05-13T12:39:33.000Z
src/misc/containers.hpp
kmaninis/COB_public
e4cb02a4c6e9ffa85951bec36846581dc98e68de
[ "BSD-2-Clause-FreeBSD" ]
70
2016-08-03T03:36:53.000Z
2022-02-03T20:44:43.000Z
// ------------------------------------------------------------------------ // Copyright (C) // ETH Zurich - Switzerland // // Kevis-Kokitsi Maninis <kmaninis@vision.ee.ethz.ch> // Jordi Pont-Tuset <jponttuset@vision.ee.ethz.ch> // July 2016 // ------------------------------------------------------------------------ // This file is part of the COB package presented in: // K.K. Maninis, J. Pont-Tuset, P. Arbelaez and L. Van Gool // Convolutional Oriented Boundaries // European Conference on Computer Vision (ECCV), 2016 // Please consider citing the paper if you use this code. // ------------------------------------------------------------------------ #ifndef CONTAINERS_HPP #define CONTAINERS_HPP #include <vector> #include <list> #include <set> #include <map> typedef uint32_t label_type; typedef std::set<label_type> set_type; typedef std::map<double,std::list<set_type> > map_type; struct merging_sequence { std::vector<label_type> parent_labels; std::vector<std::list<label_type> > children_labels; std::vector<double> start_ths; std::size_t n_max_children; std::size_t n_leaves; std::size_t n_regs; void print() const { for(std::size_t ii=0; ii<parent_labels.size(); ++ii) { for(label_type id: children_labels[ii]) printf("%d\t",id); printf("-->\t%d\n", parent_labels[ii]); } } }; struct cont_elem { cont_elem(size_t new_x, size_t new_y) : x(new_x), y(new_y) { } size_t x; size_t y; }; struct contour_container: public std::map<std::pair<label_type,label_type>, std::list<cont_elem> > { contour_container(): std::map<std::pair<label_type,label_type>, std::list<cont_elem> >() { } void print() const { for(auto elem:(*this)) { printf("[%d,%d] - ", elem.first.first, elem.first.second); for(const cont_elem& cont: elem.second) printf("(%d,%d), ",cont.x,cont.y); printf("\n"); } } }; #endif
26.111111
98
0.533333
kmaninis
cbfbb58db9322b4e56c3c01538754afe49203555
14,499
cpp
C++
src/CDocScriptAmendments.cpp
QtWorks/CDoc
64b806a39b24bedd8aede6a7134326c248c0c614
[ "MIT" ]
1
2019-04-24T02:14:34.000Z
2019-04-24T02:14:34.000Z
src/CDocScriptAmendments.cpp
QtWorks/CDoc
64b806a39b24bedd8aede6a7134326c248c0c614
[ "MIT" ]
null
null
null
src/CDocScriptAmendments.cpp
QtWorks/CDoc
64b806a39b24bedd8aede6a7134326c248c0c614
[ "MIT" ]
null
null
null
#include "CDocI.h" /*----------------------------------------------------------------*/ #define DUMMY_AMENDMENT 0 #define AMENDMENT_ISSUED 1 #define AMENDMENT_ADDED 2 struct CDAmendmentData { int type; char *issue; char *amend; char *detail; char *author; char *date; char *approve; char *agree; char *text; }; struct CDAmendment { CDAmendmentData data; CDAmendment() { data.type = DUMMY_AMENDMENT; data.issue = NULL; data.amend = NULL; data.detail = NULL; data.author = NULL; data.date = NULL; data.approve = NULL; data.agree = NULL; data.text = NULL; } ~CDAmendment() { delete [] data.issue ; delete [] data.amend ; delete [] data.detail ; delete [] data.author ; delete [] data.date ; delete [] data.approve; delete [] data.agree ; delete [] data.text ; } }; /*----------------------------------------------------------------*/ typedef std::vector<CDAmendment *> CDAmendmentList; static CDAmendmentList amendment_list; static CDScriptTempFile *amendments_temp_file = NULL; /*----------------------------------------------------------------*/ /* Ammendment Parameter Definition */ #define AMD_OFFSET(a) CDocOffset(CDAmendmentData*,a) static CDParameterData amd_parameter_data[] = { { "issue" , PARM_NEW_STR, NULL, AMD_OFFSET(issue ), }, { "amend" , PARM_NEW_STR, NULL, AMD_OFFSET(amend ), }, { "detail" , PARM_NEW_STR, NULL, AMD_OFFSET(detail ), }, { "author" , PARM_NEW_STR, NULL, AMD_OFFSET(author ), }, { "date" , PARM_NEW_STR, NULL, AMD_OFFSET(date ), }, { "approve", PARM_NEW_STR, NULL, AMD_OFFSET(approve), }, { "agree" , PARM_NEW_STR, NULL, AMD_OFFSET(agree ), }, { NULL , 0 , NULL, 0 , }, }; /*----------------------------------------------------------------*/ static void CDocScriptAmendmentWriteLine (CDAmendment *, int, int); static void CDocScriptAmendmentWriteText (char *); static char *CDocScriptAmendmentsGetText (); // Initialise Amendments Control Variables ready to process amendments commands. extern void CDocScriptInitAmendments() { cdoc_document.part = CDOC_AMENDMENTS_PART; cdoc_document.sub_part = CDOC_NO_SUB_PART; /* Start Outputting Text to Temporary File */ amendments_temp_file = CDocScriptStartTempFile("Amendments"); cdoc_left_margin = 0; cdoc_right_margin = 38; cdoc_indent = 11; if (CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC) CDocScriptWriteCommand(CDOC_INDENT_TMPL, cdoc_indent); } // Process a Colon Command found in the Amendments section. extern void CDocScriptProcessAmendmentsCommand(CDColonCommand *colon_command) { /* Flush Paragraph */ if (cdoc_in_paragraph) CDocScriptOutputParagraph(); /* Get Text in Amendments Temporary File to add to previous Amendment */ char *text = CDocScriptAmendmentsGetText(); if (text != NULL) { CDAmendment *amendment = NULL; if (! amendment_list.empty()) amendment = amendment_list.back(); if (amendment == NULL || amendment->data.text != NULL) { amendment = new CDAmendment; amendment_list.push_back(amendment); } amendment->data.text = text; } /* If Issued or Amended Command then add Details to Amendments List */ if (strcmp(colon_command->getCommand().c_str(), "i") == 0 || strcmp(colon_command->getCommand().c_str(), "a") == 0) { /* Create and Initialise Amendments Structure */ CDAmendment *amendment = new CDAmendment; if (strcmp(colon_command->getCommand().c_str(), "i") == 0) amendment->data.type = AMENDMENT_ISSUED; else amendment->data.type = AMENDMENT_ADDED; amendment_list.push_back(amendment); /* Process Parameter/Value pairs to set the Amendments Structure */ CDocExtractParameterValues(colon_command->getParameters(), colon_command->getValues(), amd_parameter_data, (char *) amendment); if (amendment->data.detail != NULL) CStrUtil::toUpper(amendment->data.detail); } /* If we have and End Amendments Command (either directly or indirectly) then Output current Amendments List */ else if (strcmp(colon_command->getCommand().c_str(), "eamends" ) == 0 || strcmp(colon_command->getCommand().c_str(), "body" ) == 0 || strcmp(colon_command->getCommand().c_str(), "appendix") == 0) { CDocScriptTermAmendments(); /* Start new part as appropriate */ if (strcmp(colon_command->getCommand().c_str(), "body") == 0) cdoc_document.part = CDOC_BODY_PART; else if (strcmp(colon_command->getCommand().c_str(), "appendix") == 0) cdoc_document.part = CDOC_APPENDIX_PART; } else CDocScriptWarning("Invalid Amendments Command - %s %s", colon_command->getCommand().c_str(), colon_command->getText().c_str()); } // Terminate Amendments Section outputing Buffered amendments text. extern void CDocScriptTermAmendments() { /* Flush Paragraph */ if (cdoc_in_paragraph) CDocScriptOutputParagraph(); /* Get Text in Amendments Temporary File to add to previous Amendment */ char *text = CDocScriptAmendmentsGetText(); if (text != NULL) { CDAmendment *amendment = amendment_list.back(); if (amendment == NULL || amendment->data.text != NULL) { amendment = new CDAmendment; amendment_list.push_back(amendment); } amendment->data.text = text; } /*------------*/ /* End Outputting Text to Temporary File */ CDocScriptEndTempFile(amendments_temp_file); delete amendments_temp_file; /*------------*/ /* Write Header */ CDocScriptWriteCentreJustifiedPageHeader("List of Amendments"); CDocScriptSkipLine(); int no_amendments = amendment_list.size(); /* Output Amendments List */ /* Set up Tab Stops */ if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF) CDocScriptWriteCommand(".ta 0.2i 0.5i +2i +1i +1i\n"); /* Output Column Headers */ if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF) { CDocScriptWriteCommand(".BD \"\t\tDetails\tAuthor\tDate\tApprove\"\n"); CDocScriptSkipLine(); } else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC) { CDocScriptWriteText(FILL_TMPL, 9, 9, ' '); CDocScriptWriteText("%sDetails%s", CDocStartUnderline(), CDocEndUnderline()); CDocScriptWriteText(FILL_TMPL, 40, 40, ' '); CDocScriptWriteText("%sAuthor%s", CDocStartUnderline(), CDocEndUnderline()); CDocScriptWriteText(FILL_TMPL, 51, 51, ' '); CDocScriptWriteText("%sDate%s", CDocStartUnderline(), CDocEndUnderline()); CDocScriptWriteText(FILL_TMPL, 62, 62, ' '); CDocScriptWriteText("%sApprove%s", CDocStartUnderline(), CDocEndUnderline()); CDocScriptWriteText("\n"); CDocScriptSkipLine(); } else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_RAW_CC) { CDocScriptWriteLine("%s %-30s %-10s %-10s %-20s%s", CDocStartUnderline(), "Details", "Author", "Date", "Approve", CDocEndUnderline()); CDocScriptSkipLine(); } else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) { CDocScriptWriteCommand("<p>\n"); CDocScriptWriteCommand("<table width='100%%' border>\n"); CDocScriptWriteCommand("<tr>\n"); CDocScriptWriteCommand("<th>&nbsp;</th>\n"); CDocScriptWriteCommand("<th>Details</th>\n"); CDocScriptWriteCommand("<th>Author</th>\n"); CDocScriptWriteCommand("<th>Date</th>\n"); CDocScriptWriteCommand("<th>Approve</th>\n"); CDocScriptWriteCommand("</tr>\n"); } else { CDocScriptWriteLine(" %-30s %-10s %-10s %-20s", "Details", "Author", "Date", "Approve"); CDocScriptSkipLine(); } /* Output each Amendment Line */ int issue_no = 0; int amend_no = 0; for (int i = 1; i <= no_amendments; i++) { CDAmendment *amendment = amendment_list[i - 1]; if (amendment->data.type == DUMMY_AMENDMENT) CDocScriptAmendmentWriteText(amendment->data.text); else { if (amendment->data.type == AMENDMENT_ISSUED) { issue_no++; amend_no = 0; } else amend_no++; if ((issue_no > 0 || amend_no > 0) && CDocInst->getOutputFormat() != CDOC_OUTPUT_HTML) CDocScriptSkipLine(); CDocScriptAmendmentWriteLine(amendment, issue_no, amend_no); } } if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) { CDocScriptWriteCommand("</table>\n"); CDocScriptWriteCommand("<p>\n"); } /* Delete Amendments Structures and List */ for (int i = 1; i <= no_amendments; i++) { CDAmendment *amendment = amendment_list[i - 1]; delete amendment; } amendment_list.clear(); /* End Amendments Document Part */ cdoc_document.part = CDOC_NO_PART; cdoc_document.sub_part = CDOC_NO_SUB_PART; } // Write an Amendments line from the data stored in the Amendments structure. static void CDocScriptAmendmentWriteLine(CDAmendment *amendment, int issue_no, int amend_no) { char issue_string[16]; if (amend_no > 0) sprintf(issue_string, "%d%c", issue_no, amend_no + 'A' - 1); else sprintf(issue_string, "%d%c", issue_no, ' '); if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF) { CDocScriptWriteText("\t"); if (amendment->data.issue != NULL) CDocScriptWriteText("%s", amendment->data.issue); else CDocScriptWriteText("%s", issue_string); CDocScriptWriteText("\t"); if (amendment->data.detail != NULL) CDocScriptWriteText("%s", amendment->data.detail); else CDocScriptWriteText(""); CDocScriptWriteText("\t"); if (amendment->data.author != NULL) CDocScriptWriteText("%s", amendment->data.author); else CDocScriptWriteText(""); CDocScriptWriteText("\t"); if (amendment->data.date != NULL) CDocScriptWriteText("%s", amendment->data.date); else CDocScriptWriteText(""); CDocScriptWriteText("\t"); if (amendment->data.approve != NULL) CDocScriptWriteText("%s", amendment->data.approve); else CDocScriptWriteText(""); CDocScriptWriteText("\n"); } else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC) { CDocScriptWriteText(FILL_TMPL, 4, 4, ' '); CDocScriptWriteText("%-4s", amendment->data.issue != NULL ? amendment->data.issue : issue_string); CDocScriptWriteText(FILL_TMPL, 9, 9, ' '); CDocScriptWriteText("%-30s", amendment->data.detail != NULL ? amendment->data.detail : ""); CDocScriptWriteText(FILL_TMPL, 40, 40, ' '); CDocScriptWriteText("%-10s", amendment->data.author != NULL ? amendment->data.author : ""); CDocScriptWriteText(FILL_TMPL, 51, 51, ' '); CDocScriptWriteText("%-10s", amendment->data.date != NULL ? amendment->data.date : ""); CDocScriptWriteText(FILL_TMPL, 62, 62, ' '); CDocScriptWriteText("%-20s", amendment->data.approve != NULL ? amendment->data.approve : ""); CDocScriptWriteText("\n"); } else if (CDocInst->getOutputFormat() == CDOC_OUTPUT_HTML) { CDocScriptWriteCommand("<tr>\n"); CDocScriptWriteCommand("<td>%s</td>\n", amendment->data.issue != NULL ? amendment->data.issue : issue_string); CDocScriptWriteCommand("<td>%s</td>\n", amendment->data.detail != NULL ? amendment->data.detail : "&nbsp;" ); CDocScriptWriteCommand("<td>%s</td>\n", amendment->data.author != NULL ? amendment->data.author : "&nbsp;" ); CDocScriptWriteCommand("<td>%s</td>\n", amendment->data.date != NULL ? amendment->data.date : "&nbsp;" ); CDocScriptWriteCommand("<td>%s</td>\n", amendment->data.approve != NULL ? amendment->data.approve : "&nbsp;" ); CDocScriptWriteCommand("</tr>\n"); } else { CDocScriptWriteLine(" %-4s %-30s %-10s %-10s %-20s", amendment->data.issue != NULL ? amendment->data.issue : issue_string, amendment->data.detail != NULL ? amendment->data.detail : "", amendment->data.author != NULL ? amendment->data.author : "", amendment->data.date != NULL ? amendment->data.date : "", amendment->data.approve != NULL ? amendment->data.approve : ""); } if (amendment->data.text != NULL && amendment->data.text[0] != '\0') CDocScriptAmendmentWriteText(amendment->data.text); } // Write text associated with an amendment. static void CDocScriptAmendmentWriteText(char *text) { char *p1; char *p = text; while ((p1 = strchr(p, '\n')) != NULL) { *p1 = '\0'; if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF) { // CDocScriptWriteText("\t\t"); CDocScriptOutputTempFileLine(p); // CDocScriptWriteText("\n"); } else { // CDocScriptWriteText(" "); CDocScriptOutputTempFileLine(p); } p = p1 + 1; } if (*p != '\0') { if (CDocInst->getOutputFormat() == CDOC_OUTPUT_TROFF) { // CDocScriptWriteText("\t\t"); CDocScriptOutputTempFileLine(p); // CDocScriptWriteText("\n"); } else { // CDocScriptWriteText(" "); CDocScriptOutputTempFileLine(p); } } //CDocScriptSkipLine(); } // Get any text which was defined between the amendments commands. static char * CDocScriptAmendmentsGetText() { long no_read; struct stat file_stat; char *text = NULL; /*-----------*/ /* End Outputting Text to Temporary File */ CDocScriptEndTempFile(amendments_temp_file); /*-----------*/ int error = stat(amendments_temp_file->filename.c_str(), &file_stat); if (error == -1 || file_stat.st_size == 0) goto CDocScriptAmendmentsGetText_1; amendments_temp_file->fp = fopen(amendments_temp_file->filename.c_str(), "r"); if (amendments_temp_file->fp == NULL) goto CDocScriptAmendmentsGetText_1; text = new char [file_stat.st_size + 1]; no_read = fread(text, sizeof(char), file_stat.st_size + 1, amendments_temp_file->fp); text[no_read] = '\0'; fclose(amendments_temp_file->fp); /*-----------*/ CDocScriptAmendmentsGetText_1: delete amendments_temp_file; /* Start Outputting Text to Temporary File */ amendments_temp_file = CDocScriptStartTempFile("Amendments"); cdoc_left_margin = 0; cdoc_right_margin = 38; cdoc_indent = 11; if (CDocInst->getOutputFormat() == CDOC_OUTPUT_CDOC) CDocScriptWriteCommand(CDOC_INDENT_TMPL, cdoc_indent); return text; }
27.564639
93
0.63294
QtWorks
cbfe304763b786b823615c143eab5a26bb544307
2,140
cpp
C++
src/WebConf.cpp
VisaJE/DoomsdayTetris-2
a5f460ca2f8c55a533926c8ec2fe5248df2450e5
[ "FTL", "MIT" ]
1
2019-09-20T20:37:35.000Z
2019-09-20T20:37:35.000Z
src/WebConf.cpp
VisaJE/DoomsdayTetris-2
a5f460ca2f8c55a533926c8ec2fe5248df2450e5
[ "FTL", "MIT" ]
null
null
null
src/WebConf.cpp
VisaJE/DoomsdayTetris-2
a5f460ca2f8c55a533926c8ec2fe5248df2450e5
[ "FTL", "MIT" ]
null
null
null
#include "WebConf.h" #include <iostream> #include <vector> #include <cstdio> #include <sstream> #include <fstream> #include "Paths.h" #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/filewritestream.h" #include "rapidjson/filereadstream.h" using namespace rapidjson; using namespace tet; WebConf::WebConf() { serverConfig = Paths::serverConfigPath().c_str(); configuration = std::vector<ConfEntry>(); serviceEnabled = false; } void WebConf::initiate() { if (!readConf()) makeConf(); } WebConf::~WebConf() { } bool WebConf::readConf() { FILE* conf =fopen(serverConfig.c_str(), "rb"); if (!conf) { LOG("No config found at %s\n", serverConfig.c_str()); return false; } Document doc; char readBuffer[10000]; FileReadStream in(conf, readBuffer, sizeof(readBuffer)); doc.ParseStream(in); fclose(conf); if (checkValidity(&doc)) setConf(&doc); else { makeConf(); return false; } return true; } bool WebConf::checkValidity(Document *doc) { bool valid = true; if (!doc->IsObject()) valid = false; Value::MemberIterator enabled = doc->FindMember("enabled"); if (enabled == doc->MemberEnd()) valid = false; if (!enabled->value.IsBool()) valid = false; return valid; } void WebConf::setConf(Document *doc) { serviceEnabled= doc->FindMember("enabled")->value.GetBool(); for (const char* i : keys) { if (doc->HasMember(i)) { auto thisValue = doc->FindMember(i); if (thisValue->value.IsString()) { configuration.push_back({i, thisValue->value.GetString()}); } } } } void WebConf::makeConf() { serviceEnabled = false; std::stringstream defaultString; defaultString << "\{\n\"enabled\": false"; for (auto i : keys) { defaultString << ",\n\"" << i << "\": \"\""; } defaultString << "}"; remove (serverConfig.c_str()); std::ofstream out(serverConfig.c_str()); out << defaultString.str(); out.close(); }
22.291667
74
0.609346
VisaJE
02021723a676015654d72928189fa57966f6e418
3,065
hpp
C++
include/ftl/map_container_const_iterator.hpp
ftlorg/ftl
75a580043ddf011477f0fbcb0ed1dc01be37814d
[ "BSL-1.0" ]
47
2020-07-17T07:31:42.000Z
2022-02-18T10:31:45.000Z
include/ftl/map_container_const_iterator.hpp
ftlorg/ftl
75a580043ddf011477f0fbcb0ed1dc01be37814d
[ "BSL-1.0" ]
40
2020-07-23T09:01:39.000Z
2020-12-19T15:19:44.000Z
include/ftl/map_container_const_iterator.hpp
ftlorg/ftl
75a580043ddf011477f0fbcb0ed1dc01be37814d
[ "BSL-1.0" ]
1
2020-07-26T18:21:36.000Z
2020-07-26T18:21:36.000Z
// Copyright Grzegorz Litarowicz and Lukasz Gut 2020 - 2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) #pragma once #include <ftl/iterator_interface.hpp> #include <ftl/iterator_member_provider.hpp> #include <ftl/iterator_traits.hpp> #include <ftl/map.hpp> #include <iterator> namespace ftl { template<typename Key, typename T, typename Item = std::pair<const Key, T>> class map_container_const_iterator final : public iterator_interface<map_container_const_iterator<Key, T>> , public container_iterator_member_provider<map_container_const_iterator<Key, T>, typename std::iterator_traits<ftl::map_container_const_iterator<Key, T>>::iterator_category> { friend container_iterator_member_provider<map_container_const_iterator<Key, T>, std::random_access_iterator_tag>; friend container_iterator_member_provider<map_container_const_iterator<Key, T>, std::bidirectional_iterator_tag>; friend container_iterator_member_provider<map_container_const_iterator<Key, T>, std::forward_iterator_tag>; friend container_iterator_member_provider<map_container_const_iterator<Key, T>, std::input_iterator_tag>; friend container_iterator_member_provider<map_container_const_iterator<Key, T>>; friend iterator_interface<map_container_const_iterator<Key, T>>; public: using difference_type = typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::difference_type; using value_type = typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::value_type; using pointer = typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::pointer; using reference = typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::reference; using const_pointer = typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::const_pointer; using const_reference = typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::const_reference; using iterator_category = typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::iterator_category; using size_type = typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::size_type; using std_map_container_const_iterator = typename std::iterator_traits<ftl::map_container_const_iterator<Key, T, Item>>::std_map_container_const_iterator; map_container_const_iterator(std_map_container_const_iterator begin, std_map_container_const_iterator end) : current_{ begin }, begin_{ begin }, end_{ end } { } map_container_const_iterator(std_map_container_const_iterator current, std_map_container_const_iterator begin, std_map_container_const_iterator end) : current_{ current }, begin_{ begin }, end_{ end } { } private: mutable std_map_container_const_iterator current_; std_map_container_const_iterator begin_; std_map_container_const_iterator end_; }; }// namespace ftl
50.245902
122
0.804568
ftlorg
02024a9538028ed67ae53f0a4acc741c4f8e4b72
8,617
cpp
C++
tst/OpcUaStackCore/BuildInTypes/OpcUaVariantValue_t.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
108
2018-10-08T17:03:32.000Z
2022-03-21T00:52:26.000Z
tst/OpcUaStackCore/BuildInTypes/OpcUaVariantValue_t.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
287
2018-09-18T14:59:12.000Z
2022-01-13T12:28:23.000Z
tst/OpcUaStackCore/BuildInTypes/OpcUaVariantValue_t.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
32
2018-10-19T14:35:03.000Z
2021-11-12T09:36:46.000Z
#include "unittest.h" #include "OpcUaStackCore/BuildInTypes/OpcUaVariant.h" using namespace OpcUaStackCore; BOOST_AUTO_TEST_SUITE(OpcUaVariantValue_) BOOST_AUTO_TEST_CASE(OpcUaVariantValue_) { std::cout << "OpcUaVariantValue_t" << std::endl; } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_uint32_copyTo) { OpcUaVariantValue value1, value2; value1.variant((OpcUaUInt32)123); value1.copyTo(value2); BOOST_REQUIRE(value1.variant<OpcUaUInt32>() == 123); BOOST_REQUIRE(value2.variant<OpcUaUInt32>() == 123); value2.variant((OpcUaUInt32)456); BOOST_REQUIRE(value1.variant<OpcUaUInt32>() == 123); BOOST_REQUIRE(value2.variant<OpcUaUInt32>() == 456); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_localizedText_copyTo) { OpcUaLocalizedText::SPtr localizedTextSPtr1 = constructSPtr<OpcUaLocalizedText>(); OpcUaLocalizedText::SPtr localizedTextSPtr2; localizedTextSPtr1->locale("de"); localizedTextSPtr1->text("text1"); OpcUaVariantValue value1, value2; value1.variant(localizedTextSPtr1); value1.copyTo(value2); localizedTextSPtr1 = value1.variantSPtr<OpcUaLocalizedText>(); localizedTextSPtr2 = value2.variantSPtr<OpcUaLocalizedText>(); BOOST_REQUIRE(localizedTextSPtr1->locale().value() == "de"); BOOST_REQUIRE(localizedTextSPtr1->text().value() == "text1"); BOOST_REQUIRE(localizedTextSPtr2->locale().value() == "de"); BOOST_REQUIRE(localizedTextSPtr2->text().value() == "text1"); localizedTextSPtr1->text("text2"); BOOST_REQUIRE(localizedTextSPtr1->locale().value() == "de"); BOOST_REQUIRE(localizedTextSPtr1->text().value() == "text2"); BOOST_REQUIRE(localizedTextSPtr2->locale().value() == "de"); BOOST_REQUIRE(localizedTextSPtr2->text().value() == "text1"); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_Boolean) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("Boolean:true") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaBoolean); OpcUaBoolean value = variantValue.variant<OpcUaBoolean>(); BOOST_REQUIRE(value == true); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_SByte) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("SByte:-12") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaSByte); OpcUaSByte value = variantValue.variant<OpcUaSByte>(); BOOST_REQUIRE(value == -12); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_Byte) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("Byte:12") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaByte); OpcUaByte value = variantValue.variant<OpcUaByte>(); BOOST_REQUIRE(value == 12); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_Int16) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("Int16:-1234") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaInt16); OpcUaInt16 value = variantValue.variant<OpcUaInt16>(); BOOST_REQUIRE(value == -1234); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_UInt16) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("UInt16:1234") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaUInt16); OpcUaUInt16 value = variantValue.variant<OpcUaUInt16>(); BOOST_REQUIRE(value == 1234); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_Int32) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("Int32:-1234") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaInt32); OpcUaInt32 value = variantValue.variant<OpcUaInt32>(); BOOST_REQUIRE(value == -1234); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_UInt32) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("UInt32:1234") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaUInt32); OpcUaUInt32 value = variantValue.variant<OpcUaUInt32>(); BOOST_REQUIRE(value == 1234); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_Int64) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("Int64:-1234") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaInt64); OpcUaInt64 value = variantValue.variant<OpcUaInt64>(); BOOST_REQUIRE(value == -1234); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_UInt64) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("UInt64:1234") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaUInt64); OpcUaUInt64 value = variantValue.variant<OpcUaUInt64>(); BOOST_REQUIRE(value == 1234); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_Double) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("Double:1.1") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaDouble); OpcUaDouble value = variantValue.variant<OpcUaDouble>(); BOOST_REQUIRE(value > 1.09 && value < 1.11); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_Float) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("Float:1.1") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaFloat); OpcUaFloat value = variantValue.variant<OpcUaFloat>(); BOOST_REQUIRE(value > 1.09 && value < 1.11); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_DateTime) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("DateTime:20120101T101101") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaDateTime); OpcUaDateTime value = variantValue.variant<OpcUaDateTime>(); BOOST_REQUIRE(value.toISOString() == "20120101T101101"); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_StatusCode) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("StatusCode:Success") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaStatusCode); OpcUaStatusCode value = variantValue.variant<OpcUaStatusCode>(); BOOST_REQUIRE(value == Success); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_Guid) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("Guid:12345678-9ABC-DEF0-1234-56789ABCDEF0") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaGuid); OpcUaGuid::SPtr value = variantValue.variantSPtr<OpcUaGuid>(); std::string guidString = *value; BOOST_REQUIRE(guidString == "12345678-9ABC-DEF0-1234-56789ABCDEF0"); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_ByteString) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("ByteString:0102030405060708090A0B0C0E0F") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaByteString); OpcUaByteString::SPtr value = variantValue.variantSPtr<OpcUaByteString>(); BOOST_REQUIRE(value->toHexString() == "0102030405060708090A0B0C0E0F"); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_String) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("String:0102030405060708090A0B0C0E0F") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaString); OpcUaString::SPtr value = variantValue.variantSPtr<OpcUaString>(); BOOST_REQUIRE(value->value() == "0102030405060708090A0B0C0E0F"); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_NodeId) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("NodeId:ns=3;s=nodename") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaNodeId); OpcUaNodeId::SPtr value = variantValue.variantSPtr<OpcUaNodeId>(); BOOST_REQUIRE(value->namespaceIndex() == 3); BOOST_REQUIRE(value->nodeId<OpcUaString::SPtr>()->value() == "nodename"); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_QualifiedName) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("QualifiedName:1:string") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaQualifiedName); OpcUaQualifiedName::SPtr value = variantValue.variantSPtr<OpcUaQualifiedName>(); BOOST_REQUIRE(value->namespaceIndex() == 1); BOOST_REQUIRE(value->name().value() == "string"); } BOOST_AUTO_TEST_CASE(OpcUaVariantValue_fromString_LocalizedText) { OpcUaVariantValue variantValue; BOOST_REQUIRE(variantValue.fromString("LocalizedText:de,string") == true); BOOST_REQUIRE(variantValue.variantType() == OpcUaBuildInType_OpcUaLocalizedText); OpcUaLocalizedText::SPtr value = variantValue.variantSPtr<OpcUaLocalizedText>(); BOOST_REQUIRE(value->locale().value() == "de"); BOOST_REQUIRE(value->text().value() == "string"); } BOOST_AUTO_TEST_SUITE_END()
31.797048
93
0.799698
gianricardo
02040891dafb90e53001c2e859a50fce3d3691db
3,576
cpp
C++
pxr/imaging/hd/renderPass.cpp
DougRogers-DigitalFish/USD
d8a405a1344480f859f025c4f97085143efacb53
[ "BSD-2-Clause" ]
38
2019-03-05T18:34:28.000Z
2022-03-26T11:30:28.000Z
pxr/imaging/hd/renderPass.cpp
DougRogers-DigitalFish/USD
d8a405a1344480f859f025c4f97085143efacb53
[ "BSD-2-Clause" ]
5
2021-12-16T03:19:10.000Z
2022-03-31T23:14:02.000Z
pxr/imaging/hd/renderPass.cpp
DougRogers-DigitalFish/USD
d8a405a1344480f859f025c4f97085143efacb53
[ "BSD-2-Clause" ]
9
2019-08-10T02:40:50.000Z
2022-03-31T08:30:10.000Z
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/imaging/hd/renderPass.h" #include "pxr/imaging/hd/changeTracker.h" #include "pxr/imaging/hd/dirtyList.h" #include "pxr/imaging/hd/renderIndex.h" #include "pxr/imaging/hd/renderPassState.h" #include "pxr/imaging/hd/sceneDelegate.h" #include "pxr/imaging/hd/tokens.h" #include "pxr/base/tf/staticTokens.h" #include "pxr/base/tf/stringUtils.h" PXR_NAMESPACE_OPEN_SCOPE HdRenderPass::HdRenderPass(HdRenderIndex *index, HdRprimCollection const& collection) : _renderIndex(index) { SetRprimCollection(collection); } HdRenderPass::~HdRenderPass() { /*NOTHING*/ } void HdRenderPass::SetRprimCollection(HdRprimCollection const& col) { if (col == _collection) { return; } _collection = col; // update dirty list subscription for the new collection. // holding shared_ptr for the lifetime of the dirty list. bool isMinorChange = true; if (!_dirtyList || !_dirtyList->ApplyEdit(col)) { _dirtyList.reset(new HdDirtyList(_collection, *_renderIndex)); isMinorChange = false; } if (TfDebug::IsEnabled(HD_DIRTY_LIST)) { std::stringstream s; s << " Include: \n"; for (auto i : col.GetRootPaths()) { s << " - " << i << "\n"; } s << " Exclude: \n"; for (auto i : col.GetExcludePaths()) { s << " - " << i << "\n"; } s << " Repr: " << col.GetReprSelector() << "\n"; TF_DEBUG(HD_DIRTY_LIST).Msg("RenderPass(%p)::SetRprimCollection (%s) - " "constructing new DirtyList(%p) minorChange(%d) \n%s\n", (void*)this, col.GetName().GetText(), (void*)&*_dirtyList, isMinorChange, s.str().c_str()); } // Mark the collection dirty in derived classes. _MarkCollectionDirty(); } void HdRenderPass::Execute(HdRenderPassStateSharedPtr const &renderPassState, TfTokenVector const &renderTags) { _Execute(renderPassState, renderTags); } void HdRenderPass::Sync() { HD_TRACE_FUNCTION(); HF_MALLOC_TAG_FUNCTION(); // Enqueue the dirty list of prims to be synced during Hydra Sync. _renderIndex->EnqueuePrimsToSync(_dirtyList, _collection); // Give derived classes a chance to sync. _Sync(); } void HdRenderPass::Prepare(TfTokenVector const &renderTags) { HD_TRACE_FUNCTION(); HF_MALLOC_TAG_FUNCTION(); _Prepare(renderTags); } PXR_NAMESPACE_CLOSE_SCOPE
29.311475
80
0.667226
DougRogers-DigitalFish
020488f372a97cea57732f61db4c270581acce67
1,204
cpp
C++
src/scenes/hannahWhitney/hannahWhitney.cpp
yxcde/RTP_MIT_RECODED
181deb2e3228484fa9d4ed0e6bf3f4a639d99419
[ "MIT" ]
12
2019-10-28T19:07:59.000Z
2021-08-21T22:00:52.000Z
src/scenes/hannahWhitney/hannahWhitney.cpp
yxcde/RTP_MIT_RECODED
181deb2e3228484fa9d4ed0e6bf3f4a639d99419
[ "MIT" ]
1
2019-10-28T19:20:05.000Z
2019-10-28T20:14:24.000Z
src/scenes/hannahWhitney/hannahWhitney.cpp
yxcde/RTP_MIT_RECODED
181deb2e3228484fa9d4ed0e6bf3f4a639d99419
[ "MIT" ]
8
2019-10-28T19:11:30.000Z
2020-01-12T05:18:31.000Z
#include "hannahWhitney.h" void hannahWhitney::setup(){ // setup pramaters // if your original code use an ofxPanel instance dont use it here, instead // add your parameters to the "parameters" instance as follows. // param was declared in mitScene1.h //parameters.add(param.set("param", 5, 0, 100)); parameters.add(speed.set("speed", 1, 0, 5)); parameters.add(noise.set("noise", 10, 0, 100)); setAuthor("Hannah Lienhard"); setOriginalArtist("John Whitney"); loadCode("scenes/hannahWhitney/exampleCode.cpp"); } void hannahWhitney::update(){ } void hannahWhitney::draw(){ ofBackground(0); ofSetColor(255); float time = speed*ofGetElapsedTimef()*50; ofSeedRandom(noise); for (int z = 0; z < 10; z++){ float radius = fmod(time + ofMap(z, 0, 10, 0, 300), 300); ofPoint center(300,300); for (int i = 0; i < 100; i++){ float angle = ofMap(i, 0, 100, 0, TWO_PI); float offset = ofNoise(ofRandom(0.01, 0.06))*100; ofDrawCircle(center.x + offset+ radius * cos(angle), center.y + +offset+ radius * sin(angle), 3); } } }
28
75
0.585548
yxcde
0208cfad27722f229571d73aba766e592097b786
5,636
cpp
C++
src/journal_manager/replay/replay_stripe.cpp
hsungyang/poseidonos
0f523b36ccf0d70726364395ea96ac6ae3b845c3
[ "BSD-3-Clause" ]
38
2021-04-06T03:20:55.000Z
2022-03-02T09:33:28.000Z
src/journal_manager/replay/replay_stripe.cpp
gye-ul/poseidonos
bce8fe2cd1f36ede8647446ecc4cf8a9749e6918
[ "BSD-3-Clause" ]
19
2021-04-08T02:27:44.000Z
2022-03-23T00:59:04.000Z
src/journal_manager/replay/replay_stripe.cpp
gye-ul/poseidonos
bce8fe2cd1f36ede8647446ecc4cf8a9749e6918
[ "BSD-3-Clause" ]
28
2021-04-08T04:39:18.000Z
2022-03-24T05:56:00.000Z
/* * BSD LICENSE * Copyright (c) 2021 Samsung Electronics Corporation * 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 Samsung Electronics Corporation 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 "src/journal_manager/replay/replay_stripe.h" #include "src/include/pos_event_id.h" #include "src/journal_manager/replay/replay_event_factory.h" #include "src/logger/logger.h" namespace pos { // Constructor for product code ReplayStripe::ReplayStripe(StripeId vsid, IVSAMap* inputVsaMap, IStripeMap* inputStripeMap, IContextReplayer* ctxReplayer, IBlockAllocator* blockAllocator, IArrayInfo* arrayInfo, ActiveWBStripeReplayer* wbReplayer, ActiveUserStripeReplayer* userReplayer) : ReplayStripe(inputVsaMap, inputStripeMap, wbReplayer, userReplayer, nullptr, nullptr, nullptr) { status = new StripeReplayStatus(vsid); replayEventFactory = new ReplayEventFactory(status, inputVsaMap, inputStripeMap, ctxReplayer, blockAllocator, arrayInfo, wbReplayer); } // Constructor for unit test ReplayStripe::ReplayStripe(IVSAMap* inputVsaMap, IStripeMap* inputStripeMap, ActiveWBStripeReplayer* wbReplayer, ActiveUserStripeReplayer* userReplayer, StripeReplayStatus* inputStatus, ReplayEventFactory* factory, ReplayEventList* inputReplayEventList) : status(inputStatus), replayEventFactory(factory), wbStripeReplayer(wbReplayer), userStripeReplayer(userReplayer), vsaMap(inputVsaMap), stripeMap(inputStripeMap), replaySegmentInfo(true) { if (inputReplayEventList != nullptr) { replayEvents = *inputReplayEventList; } } ReplayStripe::~ReplayStripe(void) { for (auto replayEvent : replayEvents) { delete replayEvent; } replayEvents.clear(); delete status; delete replayEventFactory; } void ReplayStripe::AddLog(ReplayLog replayLog) { if (replayLog.segInfoFlushed == true) { replaySegmentInfo = false; } status->RecordLogFoundTime(replayLog.time); } int ReplayStripe::Replay(void) { int result = 0; if ((result = _ReplayEvents()) != 0) { return result; } status->Print(); return result; } void ReplayStripe::_CreateSegmentAllocationEvent(void) { ReplayEvent* segmentAllocation = replayEventFactory->CreateSegmentAllocationReplayEvent(status->GetUserLsid()); replayEvents.push_front(segmentAllocation); } void ReplayStripe::_CreateStripeAllocationEvent(void) { ReplayEvent* stripeAllocation = replayEventFactory->CreateStripeAllocationReplayEvent(status->GetVsid(), status->GetWbLsid()); replayEvents.push_front(stripeAllocation); } void ReplayStripe::_CreateStripeFlushReplayEvent(void) { StripeAddr dest = { .stripeLoc = IN_USER_AREA, .stripeId = status->GetUserLsid()}; ReplayEvent* stripeMapUpdate = replayEventFactory->CreateStripeMapUpdateReplayEvent(status->GetVsid(), dest); replayEvents.push_back(stripeMapUpdate); if (replaySegmentInfo == true) { ReplayEvent* flushEvent = replayEventFactory->CreateStripeFlushReplayEvent(status->GetVsid(), status->GetWbLsid(), status->GetUserLsid()); replayEvents.push_back(flushEvent); } } int ReplayStripe::_ReplayEvents(void) { int result = 0; for (auto replayEvent : replayEvents) { result = replayEvent->Replay(); if (result != 0) { return result; } } return result; } void ReplayStripe::DeleteBlockMapReplayEvents(void) { int numErasedLogs = 0; for (auto it = replayEvents.begin(); it != replayEvents.end();) { ReplayEvent* replayEvent = *it; if (replayEvent->GetType() == ReplayEventType::BLOCK_MAP_UPDATE) { it = replayEvents.erase(it); delete replayEvent; numErasedLogs++; } else { it++; } } int eventId = static_cast<int>(POS_EVENT_ID::JOURNAL_REPLAY_VOLUME_EVENT); POS_TRACE_DEBUG(eventId, "[Replay] {} block log of volume {} is skipped", numErasedLogs, status->GetVolumeId()); } } // namespace pos
30.301075
137
0.709368
hsungyang
0209710921734a953f6fe988de49529a58cfd8ba
58,870
cc
C++
third/blackwidow/src/blackwidow.cc
kxtry/pika
476a7cf1ae5d5518a744e5933ada59b8fd765f6e
[ "MIT" ]
null
null
null
third/blackwidow/src/blackwidow.cc
kxtry/pika
476a7cf1ae5d5518a744e5933ada59b8fd765f6e
[ "MIT" ]
2
2020-02-26T11:54:45.000Z
2021-05-20T11:26:21.000Z
third/blackwidow/src/blackwidow.cc
kxtry/pika
476a7cf1ae5d5518a744e5933ada59b8fd765f6e
[ "MIT" ]
null
null
null
// Copyright (c) 2017-present The blackwidow Authors. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. #include "blackwidow/blackwidow.h" #include "blackwidow/util.h" #include "src/mutex_impl.h" #include "src/redis_strings.h" #include "src/redis_hashes.h" #include "src/redis_sets.h" #include "src/redis_lists.h" #include "src/redis_zsets.h" #include "src/redis_hyperloglog.h" #include "src/lru_cache.h" namespace blackwidow { BlackWidow::BlackWidow() : strings_db_(nullptr), hashes_db_(nullptr), sets_db_(nullptr), zsets_db_(nullptr), lists_db_(nullptr), is_opened_(false), bg_tasks_cond_var_(&bg_tasks_mutex_), current_task_type_(kNone), bg_tasks_should_exit_(false), scan_keynum_exit_(false) { cursors_store_ = new LRUCache<std::string, std::string>(); cursors_store_->SetCapacity(5000); Status s = StartBGThread(); if (!s.ok()) { fprintf(stderr, "[FATAL] start bg thread failed, %s\n", s.ToString().c_str()); exit(-1); } } BlackWidow::~BlackWidow() { bg_tasks_should_exit_ = true; bg_tasks_cond_var_.Signal(); if (is_opened_) { rocksdb::CancelAllBackgroundWork(strings_db_->GetDB(), true); rocksdb::CancelAllBackgroundWork(hashes_db_->GetDB(), true); rocksdb::CancelAllBackgroundWork(sets_db_->GetDB(), true); rocksdb::CancelAllBackgroundWork(lists_db_->GetDB(), true); rocksdb::CancelAllBackgroundWork(zsets_db_->GetDB(), true); } int ret = 0; if ((ret = pthread_join(bg_tasks_thread_id_, NULL)) != 0) { fprintf(stderr, "pthread_join failed with bgtask thread error %d\n", ret); } delete strings_db_; delete hashes_db_; delete sets_db_; delete lists_db_; delete zsets_db_; delete cursors_store_; } static std::string AppendSubDirectory(const std::string& db_path, const std::string& sub_db) { if (db_path.back() == '/') { return db_path + sub_db; } else { return db_path + "/" + sub_db; } } Status BlackWidow::Open(const BlackwidowOptions& bw_options, const std::string& db_path) { mkpath(db_path.c_str(), 0755); strings_db_ = new RedisStrings(this, kStrings); Status s = strings_db_->Open( bw_options, AppendSubDirectory(db_path, "strings")); if (!s.ok()) { fprintf(stderr, "[FATAL] open kv db failed, %s\n", s.ToString().c_str()); exit(-1); } hashes_db_ = new RedisHashes(this, kHashes); s = hashes_db_->Open(bw_options, AppendSubDirectory(db_path, "hashes")); if (!s.ok()) { fprintf(stderr, "[FATAL] open hashes db failed, %s\n", s.ToString().c_str()); exit(-1); } sets_db_ = new RedisSets(this, kSets); s = sets_db_->Open(bw_options, AppendSubDirectory(db_path, "sets")); if (!s.ok()) { fprintf(stderr, "[FATAL] open set db failed, %s\n", s.ToString().c_str()); exit(-1); } lists_db_ = new RedisLists(this, kLists); s = lists_db_->Open(bw_options, AppendSubDirectory(db_path, "lists")); if (!s.ok()) { fprintf(stderr, "[FATAL] open list db failed, %s\n", s.ToString().c_str()); exit(-1); } zsets_db_ = new RedisZSets(this, kZSets); s = zsets_db_->Open(bw_options, AppendSubDirectory(db_path, "zsets")); if (!s.ok()) { fprintf(stderr, "[FATAL] open zset db failed, %s\n", s.ToString().c_str()); exit(-1); } is_opened_.store(true); return Status::OK(); } Status BlackWidow::GetStartKey(const DataType& dtype, int64_t cursor, std::string* start_key) { std::string index_key = DataTypeTag[dtype] + std::to_string(cursor); return cursors_store_->Lookup(index_key, start_key); } Status BlackWidow::StoreCursorStartKey(const DataType& dtype, int64_t cursor, const std::string& next_key) { std::string index_key = DataTypeTag[dtype] + std::to_string(cursor); return cursors_store_->Insert(index_key, next_key); } // Strings Commands Status BlackWidow::Set(const Slice& key, const Slice& value) { return strings_db_->Set(key, value); } Status BlackWidow::SetOnce(const Slice& key, const Slice& value) { return strings_db_->SetOnce(key, value); } Status BlackWidow::Setxx(const Slice& key, const Slice& value, int32_t* ret, const int32_t ttl) { return strings_db_->Setxx(key, value, ret, ttl); } Status BlackWidow::Get(const Slice& key, std::string* value) { return strings_db_->Get(key, value); } Status BlackWidow::GetSet(const Slice& key, const Slice& value, std::string* old_value) { return strings_db_->GetSet(key, value, old_value); } Status BlackWidow::SetBit(const Slice& key, int64_t offset, int32_t value, int32_t* ret) { return strings_db_->SetBit(key, offset, value, ret); } Status BlackWidow::GetBit(const Slice& key, int64_t offset, int32_t* ret) { return strings_db_->GetBit(key, offset, ret); } Status BlackWidow::MSet(const std::vector<KeyValue>& kvs) { return strings_db_->MSet(kvs); } Status BlackWidow::MGet(const std::vector<std::string>& keys, std::vector<ValueStatus>* vss) { return strings_db_->MGet(keys, vss); } Status BlackWidow::Setnx(const Slice& key, const Slice& value, int32_t* ret, const int32_t ttl) { return strings_db_->Setnx(key, value, ret, ttl); } Status BlackWidow::MSetnx(const std::vector<KeyValue>& kvs, int32_t* ret) { return strings_db_->MSetnx(kvs, ret); } Status BlackWidow::Setvx(const Slice& key, const Slice& value, const Slice& new_value, int32_t* ret, const int32_t ttl) { return strings_db_->Setvx(key, value, new_value, ret, ttl); } Status BlackWidow::Delvx(const Slice& key, const Slice& value, int32_t* ret) { return strings_db_->Delvx(key, value, ret); } Status BlackWidow::Setrange(const Slice& key, int64_t start_offset, const Slice& value, int32_t* ret) { return strings_db_->Setrange(key, start_offset, value, ret); } Status BlackWidow::Getrange(const Slice& key, int64_t start_offset, int64_t end_offset, std::string* ret) { return strings_db_->Getrange(key, start_offset, end_offset, ret); } Status BlackWidow::Append(const Slice& key, const Slice& value, int32_t* ret) { return strings_db_->Append(key, value, ret); } Status BlackWidow::BitCount(const Slice& key, int64_t start_offset, int64_t end_offset, int32_t *ret, bool have_range) { return strings_db_->BitCount(key, start_offset, end_offset, ret, have_range); } Status BlackWidow::BitOp(BitOpType op, const std::string& dest_key, const std::vector<std::string>& src_keys, int64_t* ret) { return strings_db_->BitOp(op, dest_key, src_keys, ret); } Status BlackWidow::BitPos(const Slice& key, int32_t bit, int64_t* ret) { return strings_db_->BitPos(key, bit, ret); } Status BlackWidow::BitPos(const Slice& key, int32_t bit, int64_t start_offset, int64_t* ret) { return strings_db_->BitPos(key, bit, start_offset, ret); } Status BlackWidow::BitPos(const Slice& key, int32_t bit, int64_t start_offset, int64_t end_offset, int64_t* ret) { return strings_db_->BitPos(key, bit, start_offset, end_offset, ret); } Status BlackWidow::Decrby(const Slice& key, int64_t value, int64_t* ret) { return strings_db_->Decrby(key, value, ret); } Status BlackWidow::Incrby(const Slice& key, int64_t value, int64_t* ret) { return strings_db_->Incrby(key, value, ret); } Status BlackWidow::Incrbyrange(const Slice& key, int64_t value, int64_t* ret, int64_t min_, int64_t max_) { return strings_db_->Incrbyrange(key, value, ret, min_, max_); } Status BlackWidow::Incrbyfloat(const Slice& key, const Slice& value, std::string* ret) { return strings_db_->Incrbyfloat(key, value, ret); } Status BlackWidow::Setex(const Slice& key, const Slice& value, int32_t ttl) { return strings_db_->Setex(key, value, ttl); } Status BlackWidow::Strlen(const Slice& key, int32_t* len) { return strings_db_->Strlen(key, len); } Status BlackWidow::PKSetexAt(const Slice& key, const Slice& value, int32_t timestamp) { return strings_db_->PKSetexAt(key, value, timestamp); } // Hashes Commands Status BlackWidow::HSet(const Slice& key, const Slice& field, const Slice& value, int32_t* res) { return hashes_db_->HSet(key, field, value, res); } Status BlackWidow::HSetOnce(const Slice& key, const Slice& field, const Slice& value, int32_t* res) { return hashes_db_->HSetOnce(key, field, value, res); } Status BlackWidow::HGet(const Slice& key, const Slice& field, std::string* value) { return hashes_db_->HGet(key, field, value); } Status BlackWidow::HMSet(const Slice& key, const std::vector<FieldValue>& fvs) { return hashes_db_->HMSet(key, fvs); } Status BlackWidow::HMGet(const Slice& key, const std::vector<std::string>& fields, std::vector<ValueStatus>* vss) { return hashes_db_->HMGet(key, fields, vss); } Status BlackWidow::HGetall(const Slice& key, std::vector<FieldValue>* fvs) { return hashes_db_->HGetall(key, fvs); } Status BlackWidow::HKeys(const Slice& key, std::vector<std::string>* fields) { return hashes_db_->HKeys(key, fields); } Status BlackWidow::HVals(const Slice& key, std::vector<std::string>* values) { return hashes_db_->HVals(key, values); } Status BlackWidow::HSetnx(const Slice& key, const Slice& field, const Slice& value, int32_t* ret) { return hashes_db_->HSetnx(key, field, value, ret); } Status BlackWidow::HLen(const Slice& key, int32_t* ret) { return hashes_db_->HLen(key, ret); } Status BlackWidow::HStrlen(const Slice& key, const Slice& field, int32_t* len) { return hashes_db_->HStrlen(key, field, len); } Status BlackWidow::HExists(const Slice& key, const Slice& field) { return hashes_db_->HExists(key, field); } Status BlackWidow::HIncrby(const Slice& key, const Slice& field, int64_t value, int64_t* ret) { return hashes_db_->HIncrby(key, field, value, ret); } Status BlackWidow::HIncrbyrange(const Slice& key, const Slice& field, int64_t value, int64_t* ret, int64_t min_, int64_t max_) { return hashes_db_->HIncrbyrange(key, field, value, ret, min_, max_); } Status BlackWidow::HIncrbyfloat(const Slice& key, const Slice& field, const Slice& by, std::string* new_value) { return hashes_db_->HIncrbyfloat(key, field, by, new_value); } Status BlackWidow::HDel(const Slice& key, const std::vector<std::string>& fields, int32_t* ret) { return hashes_db_->HDel(key, fields, ret); } Status BlackWidow::HScan(const Slice& key, int64_t cursor, const std::string& pattern, int64_t count, std::vector<FieldValue>* field_values, int64_t* next_cursor) { return hashes_db_->HScan(key, cursor, pattern, count, field_values, next_cursor); } Status BlackWidow::HScanx(const Slice& key, const std::string start_field, const std::string& pattern, int64_t count, std::vector<FieldValue>* field_values, std::string* next_field) { return hashes_db_->HScanx(key, start_field, pattern, count, field_values, next_field); } Status BlackWidow::PKHScanRange(const Slice& key, const Slice& field_start, const std::string& field_end, const Slice& pattern, int32_t limit, std::vector<FieldValue>* field_values, std::string* next_field) { return hashes_db_->PKHScanRange(key, field_start, field_end, pattern, limit, field_values, next_field); } Status BlackWidow::PKHRScanRange(const Slice& key, const Slice& field_start, const std::string& field_end, const Slice& pattern, int32_t limit, std::vector<FieldValue>* field_values, std::string* next_field) { return hashes_db_->PKHRScanRange(key, field_start, field_end, pattern, limit, field_values, next_field); } // Sets Commands Status BlackWidow::SAdd(const Slice& key, const std::vector<std::string>& members, int32_t* ret) { return sets_db_->SAdd(key, members, ret); } Status BlackWidow::SCard(const Slice& key, int32_t* ret) { return sets_db_->SCard(key, ret); } Status BlackWidow::SDiff(const std::vector<std::string>& keys, std::vector<std::string>* members) { return sets_db_->SDiff(keys, members); } Status BlackWidow::SDiffstore(const Slice& destination, const std::vector<std::string>& keys, int32_t* ret) { return sets_db_->SDiffstore(destination, keys, ret); } Status BlackWidow::SInter(const std::vector<std::string>& keys, std::vector<std::string>* members) { return sets_db_->SInter(keys, members); } Status BlackWidow::SInterstore(const Slice& destination, const std::vector<std::string>& keys, int32_t* ret) { return sets_db_->SInterstore(destination, keys, ret); } Status BlackWidow::SIsmember(const Slice& key, const Slice& member, int32_t* ret) { return sets_db_->SIsmember(key, member, ret); } Status BlackWidow::SMembers(const Slice& key, std::vector<std::string>* members) { return sets_db_->SMembers(key, members); } Status BlackWidow::SMove(const Slice& source, const Slice& destination, const Slice& member, int32_t* ret) { return sets_db_->SMove(source, destination, member, ret); } Status BlackWidow::SPop(const Slice& key, std::string* member) { bool need_compact = false; Status status = sets_db_->SPop(key, member, &need_compact); if (need_compact) { AddBGTask({kSets, kCompactKey, key.ToString()}); } return status; } Status BlackWidow::SRandmember(const Slice& key, int32_t count, std::vector<std::string>* members) { return sets_db_->SRandmember(key, count, members); } Status BlackWidow::SRem(const Slice& key, const std::vector<std::string>& members, int32_t* ret) { return sets_db_->SRem(key, members, ret); } Status BlackWidow::SUnion(const std::vector<std::string>& keys, std::vector<std::string>* members) { return sets_db_->SUnion(keys, members); } Status BlackWidow::SUnionstore(const Slice& destination, const std::vector<std::string>& keys, int32_t* ret) { return sets_db_->SUnionstore(destination, keys, ret); } Status BlackWidow::SScan(const Slice& key, int64_t cursor, const std::string& pattern, int64_t count, std::vector<std::string>* members, int64_t* next_cursor) { return sets_db_->SScan(key, cursor, pattern, count, members, next_cursor); } Status BlackWidow::LPush(const Slice& key, const std::vector<std::string>& values, uint64_t* ret) { return lists_db_->LPush(key, values, ret); } Status BlackWidow::RPush(const Slice& key, const std::vector<std::string>& values, uint64_t* ret) { return lists_db_->RPush(key, values, ret); } Status BlackWidow::LRange(const Slice& key, int64_t start, int64_t stop, std::vector<std::string>* ret) { return lists_db_->LRange(key, start, stop, ret); } Status BlackWidow::LTrim(const Slice& key, int64_t start, int64_t stop) { return lists_db_->LTrim(key, start, stop); } Status BlackWidow::LLen(const Slice& key, uint64_t* len) { return lists_db_->LLen(key, len); } Status BlackWidow::LPop(const Slice& key, std::string* element) { return lists_db_->LPop(key, element); } Status BlackWidow::RPop(const Slice& key, std::string* element) { return lists_db_->RPop(key, element); } Status BlackWidow::LIndex(const Slice& key, int64_t index, std::string* element) { return lists_db_->LIndex(key, index, element); } Status BlackWidow::LInsert(const Slice& key, const BeforeOrAfter& before_or_after, const std::string& pivot, const std::string& value, int64_t* ret) { return lists_db_->LInsert(key, before_or_after, pivot, value, ret); } Status BlackWidow::LPushx(const Slice& key, const Slice& value, uint64_t* len) { return lists_db_->LPushx(key, value, len); } Status BlackWidow::RPushx(const Slice& key, const Slice& value, uint64_t* len) { return lists_db_->RPushx(key, value, len); } Status BlackWidow::LRem(const Slice& key, int64_t count, const Slice& value, uint64_t* ret) { return lists_db_->LRem(key, count, value, ret); } Status BlackWidow::LSet(const Slice& key, int64_t index, const Slice& value) { return lists_db_->LSet(key, index, value); } Status BlackWidow::RPoplpush(const Slice& source, const Slice& destination, std::string* element) { return lists_db_->RPoplpush(source, destination, element); } Status BlackWidow::ZPopMax(const Slice& key, const int64_t count, std::vector<ScoreMember>* score_members){ return zsets_db_->ZPopMax(key, count, score_members); } Status BlackWidow::ZPopMin(const Slice& key, const int64_t count, std::vector<ScoreMember>* score_members){ return zsets_db_->ZPopMin(key, count, score_members); } Status BlackWidow::ZAdd(const Slice& key, const std::vector<ScoreMember>& score_members, int32_t* ret) { return zsets_db_->ZAdd(key, score_members, ret); } Status BlackWidow::ZCard(const Slice& key, int32_t* ret) { return zsets_db_->ZCard(key, ret); } Status BlackWidow::ZCount(const Slice& key, double min, double max, bool left_close, bool right_close, int32_t* ret) { return zsets_db_->ZCount(key, min, max, left_close, right_close, ret); } Status BlackWidow::ZIncrby(const Slice& key, const Slice& member, double increment, double* ret) { return zsets_db_->ZIncrby(key, member, increment, ret); } Status BlackWidow::ZRange(const Slice& key, int32_t start, int32_t stop, std::vector<ScoreMember>* score_members) { return zsets_db_->ZRange(key, start, stop, score_members); } Status BlackWidow::ZRangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, std::vector<ScoreMember>* score_members) { return zsets_db_->ZRangebyscore(key, min, max, left_close, right_close, score_members); } Status BlackWidow::ZRank(const Slice& key, const Slice& member, int32_t* rank) { return zsets_db_->ZRank(key, member, rank); } Status BlackWidow::ZRem(const Slice& key, std::vector<std::string> members, int32_t* ret) { return zsets_db_->ZRem(key, members, ret); } Status BlackWidow::ZRemrangebyrank(const Slice& key, int32_t start, int32_t stop, int32_t* ret) { return zsets_db_->ZRemrangebyrank(key, start, stop, ret); } Status BlackWidow::ZRemrangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, int32_t* ret) { return zsets_db_->ZRemrangebyscore(key, min, max, left_close, right_close, ret); } Status BlackWidow::ZRevrange(const Slice& key, int32_t start, int32_t stop, std::vector<ScoreMember>* score_members) { return zsets_db_->ZRevrange(key, start, stop, score_members); } Status BlackWidow::ZRevrangebyscore(const Slice& key, double min, double max, bool left_close, bool right_close, std::vector<ScoreMember>* score_members) { return zsets_db_->ZRevrangebyscore(key, min, max, left_close, right_close, score_members); } Status BlackWidow::ZRevrank(const Slice& key, const Slice& member, int32_t* rank) { return zsets_db_->ZRevrank(key, member, rank); } Status BlackWidow::ZScore(const Slice& key, const Slice& member, double* ret) { return zsets_db_->ZScore(key, member, ret); } Status BlackWidow::ZUnionstore(const Slice& destination, const std::vector<std::string>& keys, const std::vector<double>& weights, const AGGREGATE agg, int32_t* ret) { return zsets_db_->ZUnionstore(destination, keys, weights, agg, ret); } Status BlackWidow::ZInterstore(const Slice& destination, const std::vector<std::string>& keys, const std::vector<double>& weights, const AGGREGATE agg, int32_t* ret) { return zsets_db_->ZInterstore(destination, keys, weights, agg, ret); } Status BlackWidow::ZRangebylex(const Slice& key, const Slice& min, const Slice& max, bool left_close, bool right_close, std::vector<std::string>* members) { return zsets_db_->ZRangebylex(key, min, max, left_close, right_close, members); } Status BlackWidow::ZLexcount(const Slice& key, const Slice& min, const Slice& max, bool left_close, bool right_close, int32_t* ret) { return zsets_db_->ZLexcount(key, min, max, left_close, right_close, ret); } Status BlackWidow::ZRemrangebylex(const Slice& key, const Slice& min, const Slice& max, bool left_close, bool right_close, int32_t* ret) { return zsets_db_->ZRemrangebylex(key, min, max, left_close, right_close, ret); } Status BlackWidow::ZScan(const Slice& key, int64_t cursor, const std::string& pattern, int64_t count, std::vector<ScoreMember>* score_members, int64_t* next_cursor) { return zsets_db_->ZScan(key, cursor, pattern, count, score_members, next_cursor); } // Keys Commands int32_t BlackWidow::Expire(const Slice& key, int32_t ttl, std::map<DataType, Status>* type_status) { int32_t ret = 0; bool is_corruption = false; // Strings Status s = strings_db_->Expire(key, ttl); if (s.ok()) { ret++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kStrings] = s; } // Hash s = hashes_db_->Expire(key, ttl); if (s.ok()) { ret++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kHashes] = s; } // Sets s = sets_db_->Expire(key, ttl); if (s.ok()) { ret++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kSets] = s; } // Lists s = lists_db_->Expire(key, ttl); if (s.ok()) { ret++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kLists] = s; } // Zsets s = zsets_db_->Expire(key, ttl); if (s.ok()) { ret++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kZSets] = s; } if (is_corruption) { return -1; } else { return ret; } } int64_t BlackWidow::Del(const std::vector<std::string>& keys, std::map<DataType, Status>* type_status) { Status s; int64_t count = 0; bool is_corruption = false; for (const auto& key : keys) { // Strings Status s = strings_db_->Del(key); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kStrings] = s; } // Hashes s = hashes_db_->Del(key); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kHashes] = s; } // Sets s = sets_db_->Del(key); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kSets] = s; } // Lists s = lists_db_->Del(key); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kLists] = s; } // ZSets s = zsets_db_->Del(key); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kZSets] = s; } } if (is_corruption) { return -1; } else { return count; } } int64_t BlackWidow::DelByType(const std::vector<std::string>& keys, const DataType& type) { Status s; int64_t count = 0; bool is_corruption = false; for (const auto& key : keys) { switch (type) { // Strings case DataType::kStrings: { s = strings_db_->Del(key); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; } break; } // Hashes case DataType::kHashes: { s = hashes_db_->Del(key); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; } break; } // Sets case DataType::kSets: { s = sets_db_->Del(key); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; } break; } // Lists case DataType::kLists: { s = lists_db_->Del(key); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; } break; } // ZSets case DataType::kZSets: { s = zsets_db_->Del(key); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; } break; } case DataType::kAll: { return -1; } } } if (is_corruption) { return -1; } else { return count; } } int64_t BlackWidow::Exists(const std::vector<std::string>& keys, std::map<DataType, Status>* type_status) { int64_t count = 0; int32_t ret; uint64_t llen; std::string value; Status s; bool is_corruption = false; for (const auto& key : keys) { s = strings_db_->Get(key, &value); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kStrings] = s; } s = hashes_db_->HLen(key, &ret); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kHashes] = s; } s = sets_db_->SCard(key, &ret); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kSets] = s; } s = lists_db_->LLen(key, &llen); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kLists] = s; } s = zsets_db_->ZCard(key, &ret); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kZSets] = s; } } if (is_corruption) { return -1; } else { return count; } } int64_t BlackWidow::Scan(const DataType& dtype, int64_t cursor, const std::string& pattern, int64_t count, std::vector<std::string>* keys) { keys->clear(); bool is_finish; int64_t leftover_visits = count; int64_t step_length = count, cursor_ret = 0; std::string start_key, next_key, prefix; prefix = isTailWildcard(pattern) ? pattern.substr(0, pattern.size() - 1) : ""; if (cursor < 0) { return cursor_ret; } else { Status s = GetStartKey(dtype, cursor, &start_key); if (s.IsNotFound()) { // If want to scan all the databases, we start with the strings database start_key = (dtype == DataType::kAll ? DataTypeTag[kStrings] : DataTypeTag[dtype]) + prefix; cursor = 0; } } char key_type = start_key.at(0); start_key.erase(start_key.begin()); switch (key_type) { case 'k': is_finish = strings_db_->Scan(start_key, pattern, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("k") + next_key); break; } else if (is_finish) { if (DataType::kStrings == dtype) { cursor_ret = 0; break; } else if (!leftover_visits) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("h") + prefix); break; } } start_key = prefix; case 'h': is_finish = hashes_db_->Scan(start_key, pattern, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("h") + next_key); break; } else if (is_finish) { if (DataType::kHashes == dtype) { cursor_ret = 0; break; } else if (!leftover_visits) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("s") + prefix); break; } } start_key = prefix; case 's': is_finish = sets_db_->Scan(start_key, pattern, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("s") + next_key); break; } else if (is_finish) { if (DataType::kSets == dtype) { cursor_ret = 0; break; } else if (!leftover_visits) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("l") + prefix); break; } } start_key = prefix; case 'l': is_finish = lists_db_->Scan(start_key, pattern, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("l") + next_key); break; } else if (is_finish) { if (DataType::kLists == dtype) { cursor_ret = 0; break; } else if (!leftover_visits) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("z") + prefix); break; } } start_key = prefix; case 'z': is_finish = zsets_db_->Scan(start_key, pattern, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("z") + next_key); break; } else if (is_finish) { cursor_ret = 0; break; } } return cursor_ret; } int64_t BlackWidow::PKExpireScan(const DataType& dtype, int64_t cursor, int32_t min_ttl, int32_t max_ttl, int64_t count, std::vector<std::string>* keys) { keys->clear(); bool is_finish; int64_t leftover_visits = count; int64_t step_length = count, cursor_ret = 0; std::string start_key, next_key; int64_t curtime; rocksdb::Env::Default()->GetCurrentTime(&curtime); if (cursor < 0) { return cursor_ret; } else { Status s = GetStartKey(dtype, cursor, &start_key); if (s.IsNotFound()) { // If want to scan all the databases, we start with the strings database start_key = std::string(1, dtype == DataType::kAll ? DataTypeTag[kStrings] : DataTypeTag[dtype]); cursor = 0; } } char key_type = start_key.at(0); start_key.erase(start_key.begin()); switch (key_type) { case 'k': is_finish = strings_db_->PKExpireScan(start_key, curtime + min_ttl, curtime + max_ttl, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("k") + next_key); break; } else if (is_finish) { if (DataType::kStrings == dtype) { cursor_ret = 0; break; } else if (!leftover_visits) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("h")); break; } } start_key = ""; case 'h': is_finish = hashes_db_->PKExpireScan(start_key, curtime + min_ttl, curtime + max_ttl, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("h") + next_key); break; } else if (is_finish) { if (DataType::kHashes == dtype) { cursor_ret = 0; break; } else if (!leftover_visits) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("s")); break; } } start_key = ""; case 's': is_finish = sets_db_->PKExpireScan(start_key, curtime + min_ttl, curtime + max_ttl, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("s") + next_key); break; } else if (is_finish) { if (DataType::kSets == dtype) { cursor_ret = 0; break; } else if (!leftover_visits) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("l")); break; } } start_key = ""; case 'l': is_finish = lists_db_->PKExpireScan(start_key, curtime + min_ttl, curtime + max_ttl, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("l") + next_key); break; } else if (is_finish) { if (DataType::kLists == dtype) { cursor_ret = 0; break; } else if (!leftover_visits) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("z")); break; } } start_key = ""; case 'z': is_finish = zsets_db_->PKExpireScan(start_key, curtime + min_ttl, curtime + max_ttl, keys, &leftover_visits, &next_key); if (!leftover_visits && !is_finish) { cursor_ret = cursor + step_length; StoreCursorStartKey(dtype, cursor_ret, std::string("z") + next_key); break; } else if (is_finish) { cursor_ret = 0; break; } } return cursor_ret; } Status BlackWidow::PKScanRange(const DataType& data_type, const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, std::vector<std::string>* keys, std::vector<KeyValue>* kvs, std::string* next_key) { Status s; keys->clear(); next_key->clear(); switch (data_type) { case DataType::kStrings: s = strings_db_->PKScanRange(key_start, key_end, pattern, limit, kvs, next_key); break; case DataType::kHashes: s = hashes_db_->PKScanRange(key_start, key_end, pattern, limit, keys, next_key); break; case DataType::kLists: s = lists_db_->PKScanRange(key_start, key_end, pattern, limit, keys, next_key); break; case DataType::kZSets: s = zsets_db_->PKScanRange(key_start, key_end, pattern, limit, keys, next_key); break; case DataType::kSets: s = sets_db_->PKScanRange(key_start, key_end, pattern, limit, keys, next_key); break; default: s = Status::Corruption("Unsupported data types"); break; } return s; } Status BlackWidow::PKRScanRange(const DataType& data_type, const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, std::vector<std::string>* keys, std::vector<KeyValue>* kvs, std::string* next_key) { Status s; keys->clear(); next_key->clear(); switch (data_type) { case DataType::kStrings: s = strings_db_->PKRScanRange(key_start, key_end, pattern, limit, kvs, next_key); break; case DataType::kHashes: s = hashes_db_->PKRScanRange(key_start, key_end, pattern, limit, keys, next_key); break; case DataType::kLists: s = lists_db_->PKRScanRange(key_start, key_end, pattern, limit, keys, next_key); break; case DataType::kZSets: s = zsets_db_->PKRScanRange(key_start, key_end, pattern, limit, keys, next_key); break; case DataType::kSets: s = sets_db_->PKRScanRange(key_start, key_end, pattern, limit, keys, next_key); break; default: s = Status::Corruption("Unsupported data types"); break; } return s; } Status BlackWidow::PKPatternMatchDel(const DataType& data_type, const std::string& pattern, int32_t* ret) { Status s; switch (data_type) { case DataType::kStrings: s = strings_db_->PKPatternMatchDel(pattern, ret); break; case DataType::kHashes: s = hashes_db_->PKPatternMatchDel(pattern, ret); break; case DataType::kLists: s = lists_db_->PKPatternMatchDel(pattern, ret); break; case DataType::kZSets: s = zsets_db_->PKPatternMatchDel(pattern, ret); break; case DataType::kSets: s = sets_db_->PKPatternMatchDel(pattern, ret); break; default: s = Status::Corruption("Unsupported data type"); break; } return s; } Status BlackWidow::Scanx(const DataType& data_type, const std::string& start_key, const std::string& pattern, int64_t count, std::vector<std::string>* keys, std::string* next_key) { Status s; keys->clear(); next_key->clear(); switch (data_type) { case DataType::kStrings: strings_db_->Scan(start_key, pattern, keys, &count, next_key); break; case DataType::kHashes: hashes_db_->Scan(start_key, pattern, keys, &count, next_key); break; case DataType::kLists: lists_db_->Scan(start_key, pattern, keys, &count, next_key); break; case DataType::kZSets: zsets_db_->Scan(start_key, pattern, keys, &count, next_key); break; case DataType::kSets: sets_db_->Scan(start_key, pattern, keys, &count, next_key); break; default: Status::Corruption("Unsupported data types"); break; } return s; } int32_t BlackWidow::Expireat(const Slice& key, int32_t timestamp, std::map<DataType, Status>* type_status) { Status s; int32_t count = 0; bool is_corruption = false; s = strings_db_->Expireat(key, timestamp); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kStrings] = s; } s = hashes_db_->Expireat(key, timestamp); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kHashes] = s; } s = sets_db_->Expireat(key, timestamp); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kSets] = s; } s = lists_db_->Expireat(key, timestamp); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kLists] = s; } s = zsets_db_->Expireat(key, timestamp); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kLists] = s; } if (is_corruption) { return -1; } else { return count; } } int32_t BlackWidow::Persist(const Slice& key, std::map<DataType, Status>* type_status) { Status s; int32_t count = 0; bool is_corruption = false; s = strings_db_->Persist(key); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kStrings] = s; } s = hashes_db_->Persist(key); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kHashes] = s; } s = sets_db_->Persist(key); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kSets] = s; } s = lists_db_->Persist(key); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kLists] = s; } s = zsets_db_->Persist(key); if (s.ok()) { count++; } else if (!s.IsNotFound()) { is_corruption = true; (*type_status)[DataType::kLists] = s; } if (is_corruption) { return -1; } else { return count; } } std::map<DataType, int64_t> BlackWidow::TTL(const Slice& key, std::map<DataType, Status>* type_status) { Status s; std::map<DataType, int64_t> ret; int64_t timestamp = 0; s = strings_db_->TTL(key, &timestamp); if (s.ok() || s.IsNotFound()) { ret[DataType::kStrings] = timestamp; } else if (!s.IsNotFound()) { ret[DataType::kStrings] = -3; (*type_status)[DataType::kStrings] = s; } s = hashes_db_->TTL(key, &timestamp); if (s.ok() || s.IsNotFound()) { ret[DataType::kHashes] = timestamp; } else if (!s.IsNotFound()) { ret[DataType::kHashes] = -3; (*type_status)[DataType::kHashes] = s; } s = lists_db_->TTL(key, &timestamp); if (s.ok() || s.IsNotFound()) { ret[DataType::kLists] = timestamp; } else if (!s.IsNotFound()) { ret[DataType::kLists] = -3; (*type_status)[DataType::kLists] = s; } s = sets_db_->TTL(key, &timestamp); if (s.ok() || s.IsNotFound()) { ret[DataType::kSets] = timestamp; } else if (!s.IsNotFound()) { ret[DataType::kSets] = -3; (*type_status)[DataType::kSets] = s; } s = zsets_db_->TTL(key, &timestamp); if (s.ok() || s.IsNotFound()) { ret[DataType::kZSets] = timestamp; } else if (!s.IsNotFound()) { ret[DataType::kZSets] = -3; (*type_status)[DataType::kZSets] = s; } return ret; } // the sequence is kv, hash, list, zset, set Status BlackWidow::Type(const std::string &key, std::string* type) { type->clear(); Status s; std::string value; s = strings_db_->Get(key, &value); if (s.ok()) { *type = "string"; return s; } else if (!s.IsNotFound()) { return s; } int32_t hashes_len = 0; s = hashes_db_->HLen(key, &hashes_len); if (s.ok() && hashes_len != 0) { *type = "hash"; return s; } else if (!s.IsNotFound()) { return s; } uint64_t lists_len = 0; s = lists_db_->LLen(key, &lists_len); if (s.ok() && lists_len != 0) { *type = "list"; return s; } else if (!s.IsNotFound()) { return s; } int32_t zsets_size = 0; s = zsets_db_->ZCard(key, &zsets_size); if (s.ok() && zsets_size != 0) { *type = "zset"; return s; } else if (!s.IsNotFound()) { return s; } int32_t sets_size = 0; s = sets_db_->SCard(key, &sets_size); if (s.ok() && sets_size != 0) { *type = "set"; return s; } else if (!s.IsNotFound()) { return s; } *type = "none"; return Status::OK(); } Status BlackWidow::Keys(const DataType& data_type, const std::string& pattern, std::vector<std::string>* keys) { Status s; if (data_type == DataType::kStrings) { s = strings_db_->ScanKeys(pattern, keys); if (!s.ok()) return s; } else if (data_type == DataType::kHashes) { s = hashes_db_->ScanKeys(pattern, keys); if (!s.ok()) return s; } else if (data_type == DataType::kZSets) { s = zsets_db_->ScanKeys(pattern, keys); if (!s.ok()) return s; } else if (data_type == DataType::kSets) { s = sets_db_->ScanKeys(pattern, keys); if (!s.ok()) return s; } else if (data_type == DataType::kLists) { s = lists_db_->ScanKeys(pattern, keys); if (!s.ok()) return s; } else { s = strings_db_->ScanKeys(pattern, keys); if (!s.ok()) return s; s = hashes_db_->ScanKeys(pattern, keys); if (!s.ok()) return s; s = zsets_db_->ScanKeys(pattern, keys); if (!s.ok()) return s; s = sets_db_->ScanKeys(pattern, keys); if (!s.ok()) return s; s = lists_db_->ScanKeys(pattern, keys); if (!s.ok()) return s; } return s; } void BlackWidow::ScanDatabase(const DataType& type) { switch (type) { case kStrings: strings_db_->ScanDatabase(); break; case kHashes: hashes_db_->ScanDatabase(); break; case kSets: sets_db_->ScanDatabase(); break; case kZSets: zsets_db_->ScanDatabase(); break; case kLists: lists_db_->ScanDatabase(); break; case kAll: strings_db_->ScanDatabase(); hashes_db_->ScanDatabase(); sets_db_->ScanDatabase(); zsets_db_->ScanDatabase(); lists_db_->ScanDatabase(); break; } } // HyperLogLog Status BlackWidow::PfAdd(const Slice& key, const std::vector<std::string>& values, bool* update) { *update = false; if (values.size() >= kMaxKeys) { return Status::InvalidArgument("Invalid the number of key"); } std::string value, registers, result = ""; Status s = strings_db_->Get(key, &value); if (s.ok()) { registers = value; } else if (s.IsNotFound()) { registers = ""; } else { return s; } HyperLogLog log(kPrecision, registers); int32_t previous = static_cast<int32_t>(log.Estimate()); for (size_t i = 0; i < values.size(); ++i) { result = log.Add(values[i].data(), values[i].size()); } HyperLogLog update_log(kPrecision, result); int32_t now = static_cast<int32_t>(update_log.Estimate()); if (previous != now || (s.IsNotFound() && values.size() == 0)) { *update = true; } s = strings_db_->Set(key, result); return s; } Status BlackWidow::PfCount(const std::vector<std::string>& keys, int64_t* result) { if (keys.size() >= kMaxKeys || keys.size() <= 0) { return Status::InvalidArgument("Invalid the number of key"); } std::string value, first_registers; Status s = strings_db_->Get(keys[0], &value); if (s.ok()) { first_registers = std::string(value.data(), value.size()); } else if (s.IsNotFound()) { first_registers = ""; } HyperLogLog first_log(kPrecision, first_registers); for (size_t i = 1; i < keys.size(); ++i) { std::string value, registers; s = strings_db_->Get(keys[i], &value); if (s.ok()) { registers = value; } else if (s.IsNotFound()) { continue; } else { return s; } HyperLogLog log(kPrecision, registers); first_log.Merge(log); } *result = static_cast<int32_t>(first_log.Estimate()); return Status::OK(); } Status BlackWidow::PfMerge(const std::vector<std::string>& keys) { if (keys.size() >= kMaxKeys || keys.size() <= 0) { return Status::InvalidArgument("Invalid the number of key"); } Status s; std::string value, first_registers, result; s = strings_db_->Get(keys[0], &value); if (s.ok()) { first_registers = std::string(value.data(), value.size()); } else if (s.IsNotFound()) { first_registers = ""; } result = first_registers; HyperLogLog first_log(kPrecision, first_registers); for (size_t i = 1; i < keys.size(); ++i) { std::string value, registers; s = strings_db_->Get(keys[i], &value); if (s.ok()) { registers = std::string(value.data(), value.size()); } else if (s.IsNotFound()) { continue; } else { return s; } HyperLogLog log(kPrecision, registers); result = first_log.Merge(log); } s = strings_db_->Set(keys[0], result); return s; } static void* StartBGThreadWrapper(void* arg) { BlackWidow* bw = reinterpret_cast<BlackWidow*>(arg); bw->RunBGTask(); return NULL; } Status BlackWidow::StartBGThread() { int result = pthread_create(&bg_tasks_thread_id_, NULL, StartBGThreadWrapper, this); if (result != 0) { char msg[128]; snprintf(msg, sizeof(msg), "pthread create: %s", strerror(result)); return Status::Corruption(msg); } return Status::OK(); } Status BlackWidow::AddBGTask(const BGTask& bg_task) { bg_tasks_mutex_.Lock(); if (bg_task.type == kAll) { // if current task it is global compact, // clear the bg_tasks_queue_; std::queue<BGTask> empty_queue; bg_tasks_queue_.swap(empty_queue); } bg_tasks_queue_.push(bg_task); bg_tasks_cond_var_.Signal(); bg_tasks_mutex_.Unlock(); return Status::OK(); } Status BlackWidow::RunBGTask() { BGTask task; while (!bg_tasks_should_exit_) { bg_tasks_mutex_.Lock(); while (bg_tasks_queue_.empty() && !bg_tasks_should_exit_) { bg_tasks_cond_var_.Wait(); } if (!bg_tasks_queue_.empty()) { task = bg_tasks_queue_.front(); bg_tasks_queue_.pop(); } bg_tasks_mutex_.Unlock(); if (bg_tasks_should_exit_) { return Status::Incomplete("bgtask return with bg_tasks_should_exit true"); } if (task.operation == kCleanAll) { DoCompact(task.type); } else if (task.operation == kCompactKey) { CompactKey(task.type, task.argv); } } return Status::OK(); } Status BlackWidow::Compact(const DataType& type, bool sync) { if (sync) { return DoCompact(type); } else { AddBGTask({type, kCleanAll}); } return Status::OK(); } Status BlackWidow::DoCompact(const DataType& type) { if (type != kAll && type != kStrings && type != kHashes && type != kSets && type != kZSets && type != kLists) { return Status::InvalidArgument(""); } Status s; if (type == kStrings) { current_task_type_ = Operation::kCleanStrings; s = strings_db_->CompactRange(NULL, NULL); } else if (type == kHashes) { current_task_type_ = Operation::kCleanHashes; s = hashes_db_->CompactRange(NULL, NULL); } else if (type == kSets) { current_task_type_ = Operation::kCleanSets; s = sets_db_->CompactRange(NULL, NULL); } else if (type == kZSets) { current_task_type_ = Operation::kCleanZSets; s = zsets_db_->CompactRange(NULL, NULL); } else if (type == kLists) { current_task_type_ = Operation::kCleanLists; s = lists_db_->CompactRange(NULL, NULL); } else { current_task_type_ = Operation::kCleanAll; s = strings_db_->CompactRange(NULL, NULL); s = hashes_db_->CompactRange(NULL, NULL); s = sets_db_->CompactRange(NULL, NULL); s = zsets_db_->CompactRange(NULL, NULL); s = lists_db_->CompactRange(NULL, NULL); } current_task_type_ = Operation::kNone; return s; } Status BlackWidow::CompactKey(const DataType& type, const std::string& key) { std::string meta_start_key, meta_end_key; std::string data_start_key, data_end_key; CalculateMetaStartAndEndKey(key, &meta_start_key, &meta_end_key); CalculateDataStartAndEndKey(key, &data_start_key, &data_end_key); Slice slice_meta_begin(meta_start_key); Slice slice_meta_end(meta_end_key); Slice slice_data_begin(data_start_key); Slice slice_data_end(data_end_key); if (type == kSets) { sets_db_->CompactRange(&slice_meta_begin, &slice_meta_end, kMeta); sets_db_->CompactRange(&slice_data_begin, &slice_data_end, kData); } else if (type == kZSets) { zsets_db_->CompactRange(&slice_meta_begin, &slice_meta_end, kMeta); zsets_db_->CompactRange(&slice_data_begin, &slice_data_end, kData); } else if (type == kHashes) { hashes_db_->CompactRange(&slice_meta_begin, &slice_meta_end, kMeta); hashes_db_->CompactRange(&slice_data_begin, &slice_data_end, kData); } else if (type == kLists) { lists_db_->CompactRange(&slice_meta_begin, &slice_meta_end, kMeta); lists_db_->CompactRange(&slice_data_begin, &slice_data_end, kData); } return Status::OK(); } Status BlackWidow::SetMaxCacheStatisticKeys(uint32_t max_cache_statistic_keys) { std::vector<Redis*> dbs = {sets_db_, zsets_db_, hashes_db_, lists_db_}; for (const auto& db : dbs) { db->SetMaxCacheStatisticKeys(max_cache_statistic_keys); } return Status::OK(); } Status BlackWidow::SetSmallCompactionThreshold(uint32_t small_compaction_threshold) { std::vector<Redis*> dbs = {sets_db_, zsets_db_, hashes_db_, lists_db_}; for (const auto& db : dbs) { db->SetSmallCompactionThreshold(small_compaction_threshold); } return Status::OK(); } std::string BlackWidow::GetCurrentTaskType() { int type = current_task_type_; switch (type) { case kCleanAll: return "All"; case kCleanStrings: return "String"; case kCleanHashes: return "Hash"; case kCleanZSets: return "ZSet"; case kCleanSets: return "Set"; case kCleanLists: return "List"; case kNone: default: return "No"; } } Status BlackWidow::GetUsage(const std::string& property, uint64_t* const result) { *result = GetProperty(ALL_DB, property); return Status::OK(); } Status BlackWidow::GetUsage(const std::string& property, std::map<std::string, uint64_t>* const type_result) { type_result->clear(); (*type_result)[STRINGS_DB] = GetProperty(STRINGS_DB, property); (*type_result)[HASHES_DB] = GetProperty(HASHES_DB, property); (*type_result)[LISTS_DB] = GetProperty(LISTS_DB, property); (*type_result)[ZSETS_DB] = GetProperty(ZSETS_DB, property); (*type_result)[SETS_DB] = GetProperty(SETS_DB, property); return Status::OK(); } uint64_t BlackWidow::GetProperty(const std::string& db_type, const std::string& property) { uint64_t out = 0, result = 0; if (db_type == ALL_DB || db_type == STRINGS_DB) { strings_db_->GetProperty(property, &out); result += out; } if (db_type == ALL_DB || db_type == HASHES_DB) { hashes_db_->GetProperty(property, &out); result += out; } if (db_type == ALL_DB || db_type == LISTS_DB) { lists_db_->GetProperty(property, &out); result += out; } if (db_type == ALL_DB || db_type == ZSETS_DB) { zsets_db_->GetProperty(property, &out); result += out; } if (db_type == ALL_DB || db_type == SETS_DB) { sets_db_->GetProperty(property, &out); result += out; } return result; } Status BlackWidow::GetKeyNum(std::vector<KeyInfo>* key_infos) { KeyInfo key_info; // NOTE: keep the db order with string, hash, list, zset, set std::vector<Redis*> dbs = {strings_db_, hashes_db_, lists_db_, zsets_db_, sets_db_}; for (const auto& db : dbs) { // check the scanner was stopped or not, before scanning the next db if (scan_keynum_exit_) { break; } db->ScanKeyNum(&key_info); key_infos->push_back(key_info); } if (scan_keynum_exit_) { scan_keynum_exit_ = false; return Status::Corruption("exit"); } return Status::OK(); } Status BlackWidow::StopScanKeyNum() { scan_keynum_exit_ = true; return Status::OK(); } rocksdb::DB* BlackWidow::GetDBByType(const std::string& type) { if (type == STRINGS_DB) { return strings_db_->GetDB(); } else if (type == HASHES_DB) { return hashes_db_->GetDB(); } else if (type == LISTS_DB) { return lists_db_->GetDB(); } else if (type == SETS_DB) { return sets_db_->GetDB(); } else if (type == ZSETS_DB) { return zsets_db_->GetDB(); } else { return NULL; } } } // namespace blackwidow
30.282922
107
0.588109
kxtry
020fa493133b6e9da26f5f4c8311ae1bc6227599
36,430
cc
C++
modules/synApps_5_6/support/seq-2-1-3/src/pv/pvKtl.cc
A2-Collaboration/epics
b764a53bf449d9f6b54a1173c5e75a22cf95098c
[ "OML" ]
null
null
null
modules/synApps_5_6/support/seq-2-1-3/src/pv/pvKtl.cc
A2-Collaboration/epics
b764a53bf449d9f6b54a1173c5e75a22cf95098c
[ "OML" ]
null
null
null
modules/synApps_5_6/support/seq-2-1-3/src/pv/pvKtl.cc
A2-Collaboration/epics
b764a53bf449d9f6b54a1173c5e75a22cf95098c
[ "OML" ]
null
null
null
/* Implementation of EPICS sequencer KTL library (pvKtl) * * William Lupton, W. M. Keck Observatory */ // ### check all object creation and call cantProceed on failure // ### review locking policy (need to be clear on why, how and when) #include <stdio.h> #include <string.h> #include <sys/time.h> #include <sys/types.h> #include "gpHash.h" #include "pvKtl.h" #include "pvKtlCnv.h" /* handlers */ static void connectionHandler( ktlKeyword *variable, char *name, int connected ); static void accessHandler( char *name, pvCallback *callback, KTL_ANYPOLY *ktlValue, KTL_CONTEXT *context ); static void monitorHandler( char *name, ktlKeyword *keyword, KTL_ANYPOLY *ktlValue, KTL_CONTEXT *context ); static void commonHandler( char *name, pvCallback *callback, KTL_ANYPOLY *ktlValue, KTL_CONTEXT *context ); /* utilities */ static char *serviceName( const char *name ); /* service name from "srv.key" name */ static char *keywordName( const char *name ); /* keyword name from "srv.key" name */ static pvSevr sevrFromKTL( int status ); /* severity as pvSevr */ static pvStat statFromKTL( int status ); /* status as pvStat */ static pvType typeFromKTL( int type ); /* KTL type as pvType */ static int copyFromKTL( int ktlFlags, KTL_DATATYPE ktlType, int ktlCount, const KTL_ANYPOLY *ktlValue, pvType type, int count, pvValue *value ); /* copy KTL value to pvValue */ static int copyToKTL( pvType type, int count, const pvValue *value, KTL_DATATYPE ktlType, int ktlCount, KTL_POLYMORPH *ktlValue ); /* copy pvValue to KTL value */ static int mallocKTL( KTL_DATATYPE ktlType, int ktlCount, KTL_POLYMORPH *ktlValue ); /* alloc dynamic data ref'd by value */ static void freeKTL( KTL_DATATYPE ktlType, KTL_POLYMORPH *ktlValue ); /* free dynamic data ref'd by value */ /* invoke KTL function and send error details to system or variable object */ #define INVOKE(_function) \ do { \ int _status = _function; \ if ( _status >= 0 ) { \ setStatus( _status ); \ setStat( pvStatOK ); \ } \ else \ setError( _status, sevrFromKTL( _status ), \ statFromKTL( _status ), ktl_get_errtxt() ); \ } while ( FALSE ) /* lock / unlock shorthands */ #define LOCK getSystem()->lock() #define UNLOCK getSystem()->unlock() //////////////////////////////////////////////////////////////////////////////// /*+ * Routine: ktlSystem::ktlSystem * * Purpose: ktlSystem constructor * * Description: */ ktlSystem::ktlSystem( int debug ) : pvSystem( debug ), attach_( FALSE ) { if ( getDebug() > 0 ) printf( "%8p: ktlSystem::ktlSystem( %d )\n", this, debug ); } /*+ * Routine: ktlSystem::~ktlSystem * * Purpose: ktlSystem destructor * * Description: */ ktlSystem::~ktlSystem() { if ( getDebug() > 0 ) printf( "%8p: ktlSystem::~ktlSystem()\n", this ); } /*+ * Routine: ktlSystem::attach * * Purpose: ktlSystem attach routine * * Description: */ pvStat ktlSystem::attach() { if ( getDebug() > 0 ) printf( "%8p: ktlSystem::attach()\n", this ); // attach all services that are already open for ( ktlService *service = ktlService::first(); service != NULL; service = service->next() ) ( void ) ktl_ioctl( service->getHandle(), KTL_ATTACH ); // attach all future services as they are opened attach_ = TRUE; return pvStatOK; } /*+ * Routine: ktlSystem::flush * * Purpose: ktlSystem flush routine * * Description: */ pvStat ktlSystem::flush() { if ( getDebug() > 1 ) printf( "%8p: ktlSystem::flush()\n", this ); // KTL has no way of deferring buffer flush return pvStatOK; } /*+ * Routine: ktlSystem::pend * * Purpose: ktlSystem pend routine * * Description: */ pvStat ktlSystem::pend( double seconds, int wait ) { double secsAtStart; // OSI time at start double secsNow; // OSI time now double secsWaited; // number of seconds waited if ( getDebug() > 1 ) printf( "%8p: ktlSystem::pend( %g, %d )\n", this, seconds, wait ); // if wait==FALSE, should wait for all operations initiated via KTL_NOWAIT // (assuming that the keyword library really supports KTL_NOWAIT as // documented in KSD/28, which is very unlikely) // ### for now, ignore the above issue // utility macro for setting a timeval structure (not very portable) #define DOUBLE_TO_TIMEVAL(_t) { ( time_t ) (_t), \ ( long ) ( 1e6 * ( (_t) - ( int ) (_t) ) ) } // loop waiting for activity and handling events until the requested // timeout has elapsed (always go through the loop at least once in case // timeout is zero, which is a poll; negative timeout means for ever) for ( pvTimeGetCurrentDouble( &secsAtStart ), secsWaited = 0.0; secsWaited == 0.0 || seconds < 0.0 || secsWaited < seconds; pvTimeGetCurrentDouble( &secsNow ), secsWaited = secsNow - secsAtStart ) { // collect fds from all services fd_set *readfds = ktlService::getFdsetsAll(); // select (read fds only) int nfd; if ( seconds < 0.0 ) { nfd = select( FD_SETSIZE, readfds, NULL, NULL, NULL ); } else { // ### hard-code 0.1s pending better solution //struct timeval timeout = DOUBLE_TO_TIMEVAL( seconds - secsWaited); struct timeval timeout = DOUBLE_TO_TIMEVAL( 0.1 ); nfd = select( FD_SETSIZE, readfds, NULL, NULL, &timeout ); } // ignore EINTR; fail on other errors if ( nfd < 0 ) { if ( errno == EINTR ) { continue; } else { setError( -errno, pvSevrMAJOR, pvStatERROR, "select failure" ); return pvStatERROR; } } // continue or break on timeout (depending on "wait"; not an error) if ( nfd == 0 ) { if ( wait ) continue; else break; } // otherwise, dispatch all open services LOCK; pvStat stat = ktlService::dispatchAll(); UNLOCK; if ( stat != pvStatOK ) { return pvStatERROR; } } return pvStatOK; } /*+ * Routine: ktlSystem::newVariable * * Purpose: ktlSystem variable creation routine * * Description: */ pvVariable *ktlSystem::newVariable( const char *name, pvConnFunc func, void *priv, int debug ) { if ( getDebug() > 0 ) printf( "%8p: ktlSystem::newVariable( %s, %p, %p, %d )\n", this, name, func, priv, debug ); return new ktlVariable( this, name, func, priv, debug ); } //////////////////////////////////////////////////////////////////////////////// /* * list of ktlService objects (statically initialized) */ ELLLIST ktlService::list_ = {{NULL,NULL}, 0}; /*+ * Routine: ktlService::ktlService * * Purpose: ktlService constructor * * Description: */ ktlService::ktlService( ktlSystem *system, const char *name, int debug ) : debug_( debug ), name_( strdup( name ) ), flags_( 0 ), keys_( NULL ), status_( 0 ), sevr_( pvSevrNONE ), stat_( pvStatOK ), mess_( NULL ) { if ( getDebug() > 0 ) printf( "%8p: ktlService::ktlService( %s, %d )\n", this, name, debug ); handle_ = NULL; INVOKE( ktl_open( name_, "keyword", 0, &handle_ ) ); if ( system->getAttach() ) ( void ) ktl_ioctl( handle_, KTL_ATTACH ); // use KTL_SUPERSUPP to see whether KTL_SUPER is supported ( void ) ktl_ioctl( handle_, KTL_SUPERSUPP, &flags_ ); flags_ = flags_ ? ( KTL_SUPER | KTL_STAMP ) : 0; // create keyword hash table (aborts on failure) gphInitPvt( &keys_, 256 ); // ### not calling FDREG but perhaps should try to? // link into list of services node_.setData( this ); ellAdd( &list_, ( ELLNODE * ) &node_ ); } /*+ * Routine: ktlService::~ktlService * * Purpose: ktlService destructor * * Description: */ ktlService::~ktlService() { if ( getDebug() > 0 ) printf( "%8p: ktlService::~ktlService()\n", this ); // remove from list of services ellDelete( &list_, ( ELLNODE * ) &node_ ); // free keyword hash table memory gphFreeMem( keys_ ); // close KTL connection (ignore failure) INVOKE( ktl_close( handle_ ) ); // free name if ( name_ != NULL ) free( name_ ); } /*+ * Routine: ktlService::getService * * Purpose: ktlService static accessor routine * * Description: */ ktlService *ktlService::getService( ktlSystem *system, char *name, int debug ) { // search for service with this name; return if found; create if not ktlService *service; for ( service = ktlService::first(); service != NULL; service = service->next() ) { if ( strcmp( service->name_, name ) == 0 ) break; } return ( service != NULL ) ? service : new ktlService( system, name, debug); } /*+ * Routine: ktlService::first * * Purpose: ktlService first service routine * * Description: */ ktlService *ktlService::first() { ktlNode *node = ( ktlNode * ) ellFirst( &list_ ); return ( node != NULL ) ? ( ktlService * ) node->getData() : NULL; } /*+ * Routine: ktlService::next * * Purpose: ktlService next service routine * * Description: */ ktlService *ktlService::next() const { ktlNode *node = ( ktlNode * ) ellNext( ( ELLNODE * ) &node_ ); return ( node != NULL ) ? ( ktlService * ) node->getData() : NULL; } /*+ * Routine: ktlService::add * * Purpose: ktlService add keyword to hash table routine * * Description: */ void ktlService::add( const ktlKeyword *keyword ) { // ignore failure (means keyword had already been added) GPHENTRY *ent = gphAdd( keys_, keyword->getKeyName(), NULL ); if ( ent != NULL ) ent->userPvt = ( void * ) keyword; } /*+ * Routine: ktlService::remove * * Purpose: ktlService remove keyword from hash table routine * * Description: */ void ktlService::remove( const ktlKeyword *keyword ) { gphDelete( keys_, keyword->getKeyName(), NULL ); } /*+ * Routine: ktlService::find * * Purpose: ktlService find keyword in hash table routine * * Description: */ ktlKeyword *ktlService::find( const char *keyName ) { GPHENTRY *ent = gphFind( keys_, keyName, NULL ); return ( ent != NULL ) ? ( ktlKeyword * ) ent->userPvt : NULL; } /*+ * Routine: ktlService::getFdsetsAll * * Purpose: ktlService routine to return fd_set combining fds from all * open services * * Description: */ fd_set *ktlService::getFdsetsAll() { static fd_set fdset; FD_ZERO( &fdset ); for ( ktlService *service = ktlService::first(); service != NULL; service = service->next() ) { if ( service->handle_ == NULL ) continue; fd_set temp; ( void ) ktl_ioctl( service->handle_, KTL_FDSET, &temp ); for ( int fd = 0; fd < FD_SETSIZE; fd++ ) { if ( FD_ISSET( fd, &temp ) ) { FD_SET( fd, &fdset ); } } } return &fdset; } /*+ * Routine: ktlService::dispatchAll * * Purpose: ktlService routine to dispatch events on all open services * * Description: */ pvStat ktlService::dispatchAll() { for ( ktlService *service = ktlService::first(); service != NULL; service = service->next() ) { if ( service->handle_ == NULL ) continue; if ( ktl_dispatch( service->handle_ ) < 0 ) { service->setError( -1, pvSevrMAJOR, pvStatERROR, "dispatch failure" ); return pvStatERROR; } } return pvStatOK; } /*+ * Routine: ktlService::setError() * * Purpose: Copy error information * * Description: * * Function value: */ void ktlService::setError( int status, pvSevr sevr, pvStat stat, const char *mess ) { status_ = status; sevr_ = sevr; stat_ = stat; mess_ = Strdcpy( mess_, mess ); } //////////////////////////////////////////////////////////////////////////////// /*+ * Routine: ktlKeyword::ktlKeyword * * Purpose: ktlKeyword constructor * * Description: */ ktlKeyword::ktlKeyword( ktlService *service, const char *keyName, int debug ) : debug_( debug ), service_( service ), keyName_( strdup( keyName ) ), monitored_( FALSE ), status_( 0 ), sevr_( pvSevrNONE ), stat_( pvStatOK ), mess_( NULL ) { if ( getDebug() > 0 ) printf( "%8p: ktlKeyword::ktlKeyword( %d )\n", this, debug ); // add to service's hash table of keywords service->add( this ); // initialize list of associated variables ellInit( &list_ ); } /*+ * Routine: ktlKeyword::~ktlKeyword * * Purpose: ktlKeyword destructor * * Description: */ ktlKeyword::~ktlKeyword() { if ( getDebug() > 0 ) printf( "%8p: ktlKeyword::~ktlKeyword()\n", this ); // remove any remaining associated variables from list and free list for ( ktlVariable *variable = first(); variable != NULL; variable = next( variable ) ) { remove( variable ); } ellFree( &list_ ); // remove from service's hash table of keywords service_->remove( this ); // free keyword name if ( keyName_ != NULL ) free( ( char * ) keyName_ ); } /*+ * Routine: ktlKeyword::getKeyword * * Purpose: ktlKeyword static accessor routine * * Description: */ ktlKeyword *ktlKeyword::getKeyword( ktlService *service, const char *keyName, int debug ) { // search for keyword with this name; return if found; create if not ktlKeyword *keyword = service->find( keyName ); return ( keyword != NULL ) ? keyword : new ktlKeyword( service, keyName, debug ); } /*+ * Routine: ktlKeyword::add * * Purpose: ktlKeyword add variable routine * * Description: */ int ktlKeyword::add( ktlVariable *variable ) { if ( getDebug() > 0 ) printf( "%8p: ktlKeyword::add( %p )\n", this, variable ); ktlNode *node = variable->getNode(); node->setData( variable ); ellAdd( &list_, ( ELLNODE * ) node ); // attempt to enable connection handler INVOKE( ktl_ioctl( variable->getHandle(), KTL_KEYCONNREG, variable->getKeyName(), connectionHandler, this ) ); return getStatus(); } /*+ * Routine: ktlKeyword::remove * * Purpose: ktlKeyword remove variable routine * * Description: */ void ktlKeyword::remove( ktlVariable *variable ) { if ( getDebug() > 0 ) printf( "%8p: ktlKeyword::remove( %p )\n", this, variable ); ( void ) monitorOff( variable ); ellDelete( &list_, ( ELLNODE * ) variable->getNode() ); } /*+ * Routine: ktlKeyword::monitorOn * * Purpose: ktlKeyword monitor on variable routine * * Description: */ int ktlKeyword::monitorOn( ktlVariable *variable ) { if ( getDebug() > 0 ) printf( "%8p: ktlKeyword::monitorOn( %p, %d )\n", this, variable, monitored_ ); if ( ! monitored_++ ) { KTL_CONTEXT *context; INVOKE( ktl_context_create( variable->getHandle(), ( int(*)() ) monitorHandler, NULL, NULL, &context ) ); if ( getStat() == pvStatOK ) { int flags = KTL_ENABLEREADCONT | KTL_NOPRIME | variable->getFlags(); INVOKE( ktl_read( variable->getHandle(), flags, variable-> getKeyName(), ( void * ) this, NULL, context ) ); ( void ) ktl_context_delete( context ); } } return getStatus(); } /*+ * Routine: ktlKeyword::monitorOff * * Purpose: ktlKeyword monitor off variable routine * * Description: */ int ktlKeyword::monitorOff( ktlVariable *variable ) { if ( getDebug() > 0 ) printf( "%8p: ktlKeyword::monitorOff( %p, %d )\n", this, variable, monitored_ ); if ( ! --monitored_ ) { int flags = KTL_DISABLEREADCONT | variable->getFlags(); INVOKE( ktl_read( variable->getHandle(), flags, variable->getKeyName(), NULL, NULL, NULL ) ); } return getStatus(); } /*+ * Routine: ktlKeyword::first * * Purpose: ktlKeyword first variable routine * * Description: */ ktlVariable *ktlKeyword::first() { ktlNode *node = ( ktlNode * ) ellFirst( &list_ ); return ( node != NULL ) ? ( ktlVariable * ) node->getData() : NULL; } /*+ * Routine: ktlKeyword::next * * Purpose: ktlKeyword next variable routine * * Description: */ ktlVariable *ktlKeyword::next( ktlVariable *variable ) { ktlNode *node = ( ktlNode * ) ellNext( ( ELLNODE * ) variable->getNode() ); return ( node != NULL ) ? ( ktlVariable * ) node->getData() : NULL; } /*+ * Routine: ktlKeyword::setError() * * Purpose: Copy error information * * Description: * * Function value: */ void ktlKeyword::setError( int status, pvSevr sevr, pvStat stat, const char *mess ) { status_ = status; sevr_ = sevr; stat_ = stat; mess_ = Strdcpy( mess_, mess ); } //////////////////////////////////////////////////////////////////////////////// /*+ * Routine: ktlVariable::ktlVariable * * Purpose: ktlVariable constructor * * Description: */ ktlVariable::ktlVariable( ktlSystem *system, const char *name, pvConnFunc func, void *priv, int debug ) : pvVariable( system, name, func, priv, debug ), service_( ktlService::getService( system, serviceName( name ), getDebug())), keyName_( strdup( keywordName( name ) ) ), keyword_( ktlKeyword::getKeyword( service_, keyName_, getDebug() ) ), type_( KTL_DOUBLE ), count_( 1 ), readNot_( FALSE ), writeNot_( FALSE ), readCont_( FALSE ), connected_( FALSE ), monitor_( NULL ) { if ( getDebug() > 0 ) printf( "%8p: ktlVariable::ktlVariable( %s, %d )\n", this, name, debug ); // use KTL_FLAGS to check whether keyword exists // ### ignored at the moment (don't want to abort part of constructor // because complicates destructor) int flags; INVOKE( ktl_ioctl( getHandle(), KTL_FLAGS, keyName_, &flags ) ); // cache keyword attributes INVOKE( ktl_ioctl( getHandle(), KTL_TYPE | KTL_BINOUT, keyName_, &type_, &count_ ) ); KTL_IMPL_CAPS impl_caps; INVOKE( ktl_ioctl( getHandle(), KTL_IMPLCAPS, &impl_caps ) ); // ### will be FALSE (should have per keyword inquiry) readNot_ = impl_caps.read_notify; INVOKE( ktl_ioctl( getHandle(), KTL_CANWRITENOTIFY, keyName_, &writeNot_ ) ); INVOKE( ktl_ioctl( getHandle(), KTL_CANREADCONTINUOUS, keyName_, &readCont_ ) ); // monitor the keyword (won't result in any user callbacks being called // because no callback object has yet been allocated; is done to force // a connection request to be sent to the control system) INVOKE( keyword_->monitorOn( this ) ); // add variable to keyword object's list; this enables the connection // handler (interpret error as meaning that KTL_KEYCONNREG is not // supported, so mark connected and invoke function, if supplied) INVOKE( keyword_->add( this ) ); if ( getStat() != pvStatOK ) { connected_ = TRUE; if ( func != NULL ) ( *func ) ( ( void * ) this, connected_ ); } } /*+ * Routine: ktlVariable::~ktlVariable * * Purpose: ktlVariable destructor * * Description: */ ktlVariable::~ktlVariable() { if ( getDebug() > 0 ) printf( "%8p: ktlVariable::~ktlVariable( %s )\n", this, keyName_ ); // remove variable from keyword object's list keyword_->remove( this ); // ### if this is last variable for this keyword, destroy keyword // ### if this is last variable for this service, destroy service // free keyword name if ( keyName_ != NULL ) free( ( void * ) keyName_ ); } /*+ * Routine: ktlVariable::get * * Purpose: ktlVariable blocking get routine * * Description: */ pvStat ktlVariable::get( pvType type, int count, pvValue *value ) { if ( getDebug() > 0 ) printf( "%8p: ktlVariable::get( %d, %d )\n", this, type, count ); KTL_ANYPOLY ktlValue; LOCK; INVOKE( ktl_read( getHandle(), KTL_WAIT | getFlags() , keyName_, NULL, &ktlValue, NULL ) ); UNLOCK; if ( getStat() == pvStatOK ) { INVOKE( copyFromKTL( getFlags(), type_, count_, &ktlValue, type, count, value ) ); freeKTL( type_, KTL_POLYDATA( getFlags(), &ktlValue ) ); } return getStat(); } /*+ * Routine: ktlVariable::getNoBlock * * Purpose: ktlVariable non-blocking get routine * * Description: */ pvStat ktlVariable::getNoBlock( pvType type, int count, pvValue *value ) { if ( getDebug() > 0 ) printf( "%8p: ktlVariable::getNoBlock( %d, %d )\n", this, type, count ); KTL_ANYPOLY ktlValue; LOCK; INVOKE( ktl_read( getHandle(), KTL_NOWAIT | getFlags(), keyName_, NULL, &ktlValue, NULL ) ); UNLOCK; if ( getStat() == pvStatOK ) { INVOKE( copyFromKTL( getFlags(), type_, count_, &ktlValue, type, count, value ) ); freeKTL( type_, KTL_POLYDATA( getFlags(), &ktlValue ) ); } return getStat(); } /*+ * Routine: ktlVariable::getCallback * * Purpose: ktlVariable get with callback routine * * Description: */ pvStat ktlVariable::getCallback( pvType type, int count, pvEventFunc func, void *arg ) { if ( getDebug() > 0 ) printf( "%8p: ktlVariable::getCallback( %d, %d, %p, %p )\n", this, type, count, func, arg ); if ( !readNot_ ) { // ### larger than needed (status not checked) pvValue *value = new pvValue[count]; pvStat stat = get( type, count, value ); ( *func ) ( ( void * ) this, type, count, value, arg, stat ); delete [] value; } else { pvCallback *callback = new pvCallback( this, type, count, func, arg, getDebug() ); KTL_CONTEXT *context; INVOKE( ktl_context_create( getHandle(), ( int(*)() ) accessHandler, NULL, NULL, &context ) ); if ( getStat() == pvStatOK ) { LOCK; INVOKE( ktl_read( getHandle(), KTL_NOTIFY | getFlags(), keyName_, ( void * ) callback, NULL, context ) ); context->state = KTL_MESSAGE_STATE; UNLOCK; } } return getStat(); } /*+ * Routine: ktlVariable::put * * Purpose: ktlVariable blocking put routine * * Description: */ pvStat ktlVariable::put( pvType type, int count, pvValue *value ) { if ( getDebug() > 0 ) printf( "%8p: ktlVariable::put( %d, %d )\n", this, type, count ); KTL_POLYMORPH ktlValue; INVOKE( copyToKTL( type, count, value, type_, count_, &ktlValue ) ); if ( getStat() == pvStatOK ) { LOCK; INVOKE( ktl_write( getHandle(), KTL_WAIT, keyName_, NULL, &ktlValue, NULL ) ); UNLOCK; freeKTL( type_, &ktlValue ); } return getStat(); } /*+ * Routine: ktlVariable::putNoBlock * * Purpose: ktlVariable non-blocking put routine * * Description: */ pvStat ktlVariable::putNoBlock( pvType type, int count, pvValue *value ) { if ( getDebug() > 0 ) printf( "%8p: ktlVariable::putNoBlock( %d, %d )\n", this, type, count ); KTL_POLYMORPH ktlValue; INVOKE( copyToKTL( type, count, value, type_, count_, &ktlValue ) ); if ( getStat() == pvStatOK ) { LOCK; INVOKE( ktl_write( getHandle(), KTL_NOWAIT, keyName_, NULL, &ktlValue, NULL ) ); UNLOCK; freeKTL( type_, &ktlValue ); } return getStat(); } /*+ * Routine: ktlVariable::putCallback * * Purpose: ktlVariable put with callback routine * * Description: */ pvStat ktlVariable::putCallback( pvType type, int count, pvValue *value, pvEventFunc func, void *arg ) { if ( getDebug() > 0 ) printf( "%8p: ktlVariable::putCallback( %d, %d )\n", this, type, count ); if ( !writeNot_ ) { pvStat stat = put( type, count, value ); ( *func ) ( ( void * ) this, type, count, value, arg, stat ); } else { pvCallback *callback = new pvCallback( this, type, count, func, arg, getDebug() ); KTL_POLYMORPH ktlValue; INVOKE( copyToKTL( type, count, value, type_, count_, &ktlValue ) ); if ( getStat() == pvStatOK ) { KTL_CONTEXT *context; INVOKE( ktl_context_create( getHandle(), ( int(*)() ) accessHandler, NULL, NULL, &context ) ); if ( getStat() == pvStatOK ) { LOCK; INVOKE( ktl_write( getHandle(), KTL_NOTIFY, keyName_, ( void * ) callback, &ktlValue, context ) ); context->state = KTL_MESSAGE_STATE; UNLOCK; } } freeKTL( type_, &ktlValue ); } return getStat(); } /*+ * Routine: ktlVariable::monitorOn * * Purpose: ktlVariable monitor enable routine * * Description: */ pvStat ktlVariable::monitorOn( pvType type, int count, pvEventFunc func, void *arg, pvCallback **pCallback ) { if ( getDebug() > 0 ) printf( "%8p: ktlVariable::monitorOn( %s, %d, %d )\n", this, keyName_, type, count ); if ( !readCont_ ) { setError( -1, pvSevrMAJOR, pvStatERROR, "monitoring not supported" ); if ( pCallback != NULL ) *pCallback = NULL; // ### can only have single monitor enabled per variable (can have // multiple variables per keyword though) } else if ( monitor_ != NULL ) { setError( -1, pvSevrMAJOR, pvStatERROR, "monitor already enabled" ); if ( pCallback != NULL ) *pCallback = NULL; } else { monitor_ = new pvCallback( this, type, count, func, arg, getDebug() ); LOCK; INVOKE( keyword_->monitorOn( this ) ); UNLOCK; if ( pCallback != NULL ) *pCallback = monitor_; } return getStat(); } /*+ * Routine: ktlVariable::monitorOff * * Purpose: ktlVariable monitor disable routine * * Description: */ pvStat ktlVariable::monitorOff( pvCallback *callback ) { if ( getDebug() > 0 ) printf( "%8p: ktlVariable::monitorOff()\n", this ); LOCK; keyword_->monitorOff( this ); UNLOCK; // ### are we sure that no further monitors can be delivered? if ( monitor_ != NULL ) { delete monitor_; monitor_ = NULL; } return getStat(); } /*+ * Routine: ktlVariable::getType * * Purpose: ktlVariable "what type are we?" routine * * Description: */ pvType ktlVariable::getType() const { if ( getDebug() > 1 ) printf( "%8p: ktlVariable::getType()\n", this ); return typeFromKTL( type_ ); } //////////////////////////////////////////////////////////////////////////////// /*+ * Routine: connectionHandler * * Purpose: KTL connection handler * * Description: */ static void connectionHandler( ktlKeyword *keyword, char *, int connected ) { if ( keyword->getDebug() > 0 ) printf( "%8p: ktlKeyword::connectionHandler( %d )\n", keyword, connected ); for ( ktlVariable *variable = keyword->first(); variable != NULL; variable = keyword->next( variable ) ) { if ( variable->getDebug() > 0 ) printf( "%8p: ktlVariable::connectionHandler( %s, %d )\n", variable, variable->getKeyName(), connected ); variable->setConnected( connected ); pvConnFunc func = variable->getFunc(); if ( func != NULL ) ( *func ) ( ( void * ) variable, connected ); } } /*+ * Routine: accessHandler * * Purpose: KTL get/put completion event handler * * Description: */ static void accessHandler( char *keyName, pvCallback *callback, KTL_ANYPOLY *ktlValue, KTL_CONTEXT *context ) { ktlVariable *variable = ( ktlVariable * ) callback->getVariable(); int ktlFlags = variable->getFlags(); if ( variable->getDebug() > 0 ) printf( "%8p: ktlVariable::accessHandler( %s, %d )\n", variable, variable->getKeyName(), KTL_POLYDATA(ktlFlags,ktlValue)->i ); commonHandler( keyName, callback, ktlValue, context ); delete callback; } /*+ * Routine: monitorHandler * * Purpose: KTL monitor event handler * * Description: */ static void monitorHandler( char *keyName, ktlKeyword *keyword, KTL_ANYPOLY *ktlValue, KTL_CONTEXT *context ) { int ktlFlags = keyword->getFlags(); if ( keyword->getDebug() > 0 ) printf( "%8p: ktlKeyword::monitorHandler( %d )\n", keyword, KTL_POLYDATA(ktlFlags,ktlValue)->i ); for ( ktlVariable *variable = keyword->first(); variable != NULL; variable = keyword->next( variable ) ) { if ( variable->getDebug() > 0 ) printf( "%8p: ktlVariable::monitorHandler( %s )\n", variable, variable->getKeyName() ); pvCallback *monitor = variable->getMonitor(); if ( monitor != NULL ) commonHandler( keyName, monitor, ktlValue, context ); } } /*+ * Routine: commonHandler * * Purpose: KTL completion/monitor event handler (work routine) * * Description: */ static void commonHandler( char *, pvCallback *callback, KTL_ANYPOLY *ktlValue, KTL_CONTEXT *context ) { pvEventFunc func = callback->getFunc(); ktlVariable *variable = ( ktlVariable * ) callback->getVariable(); int ktlFlags = variable->getFlags(); KTL_DATATYPE ktlType = variable->getKtlType(); int ktlCount = variable->getCount(); pvType type = callback->getType(); int count = callback->getCount(); void *arg = callback->getArg(); // ### larger than needed (status not checked) pvValue *value = new pvValue[count]; // ### function not called if copy from KTL failed if ( copyFromKTL( ktlFlags, ktlType, ktlCount, ktlValue, type, count, value ) >= 0 ) { ( *func ) ( ( void * ) variable, type, count, value, arg, statFromKTL( context->status ) ); } delete [] value; } //////////////////////////////////////////////////////////////////////////////// /*+ * Routine: serviceName() * * Purpose: service name from "srv.key" name * * Description: */ static char *serviceName( const char *name ) { static char temp[256]; size_t len = strcspn( name, "." ); strncpy( temp, name, len ); temp[255] = '\0'; return temp; } /*+ * Routine: keywordName * * Purpose: keyword name from "srv.key" name * * Description: */ static char *keywordName( const char *name ) { static char temp[256]; size_t len = strcspn( name, "." ); strncpy( temp, name + len + 1, 256 - len - 1 ); temp[255] = '\0'; return temp; } /*+ * Routine: sevrFromKTL * * Purpose: extract pvSevr from KTL status * * Description: */ static pvSevr sevrFromKTL( int status ) { return ( status < 0 ) ? pvSevrERROR : pvSevrNONE; } /*+ * Routine: statFromKTL * * Purpose: extract pvStat from KTL status * * Description: */ static pvStat statFromKTL( int status ) { pvSevr sevr = sevrFromKTL( status ); return ( sevr == pvSevrNONE || sevr == pvSevrMINOR ) ? pvStatOK : pvStatERROR; } /*+ * Routine: typeFromKTL * * Purpose: extract pvType from KTL type * * Description: */ static pvType typeFromKTL( int type ) { switch ( type ) { case KTL_INT: return pvTypeLONG; case KTL_BOOLEAN: return pvTypeLONG; case KTL_ENUM: return pvTypeLONG; case KTL_ENUMM: return pvTypeLONG; case KTL_MASK: return pvTypeLONG; case KTL_FLOAT: return pvTypeFLOAT; case KTL_DOUBLE: return pvTypeDOUBLE; case KTL_STRING: return pvTypeSTRING; case KTL_INT_ARRAY: return pvTypeLONG; case KTL_FLOAT_ARRAY: return pvTypeFLOAT; case KTL_DOUBLE_ARRAY: return pvTypeDOUBLE; default: return pvTypeERROR; } } /*+ * Routine: copyFromKTL * * Purpose: copy KTL value to pvValue * * Description: */ static int copyFromKTL( int ktlFlags, KTL_DATATYPE ktlType, int ktlCount, const KTL_ANYPOLY *ktlValue, pvType type, int count, pvValue *value ) { // map types to ktlCnv's types (indices into conversion table) ktlCnv::type inpType = ktlCnv::getType( ktlType ); ktlCnv::type outType = ktlCnv::getType( type ); // if type is not simple, copy status, severity and time stamp // (note assumption that STAT and SEVR can be cast; this is in fact true) if ( !PV_SIMPLE( type ) ) { epicsTimeStamp stamp; if ( ktlFlags & KTL_SUPER ) { value->timeCharVal.status = ( pvStat ) ktlValue->super.stat; value->timeCharVal.severity = ( pvSevr ) ktlValue->super.sevr; if ( ktlFlags & KTL_STAMP ) { epicsTimeFromTimeval( &value->timeCharVal.stamp, &ktlValue->super.stamp ); } else { ( void ) epicsTimeGetCurrent( &stamp ); value->timeCharVal.stamp = stamp; } } else { ( void ) epicsTimeGetCurrent( &stamp ); value->timeCharVal.status = pvStatOK; value->timeCharVal.severity = pvSevrNONE; value->timeCharVal.stamp = stamp; } } // convert data const KTL_POLYMORPH *ktlData = KTL_POLYDATA( ktlFlags, ktlValue ); return ktlCnv::convert( inpType, ktlCount, KTL_VALPTR( ktlType, ktlData ), outType, count, PV_VALPTR( type, value ) ); } /*+ * Routine: copyToKTL * * Purpose: copy pvValue to KTL value * * Description: */ static int copyToKTL( pvType type, int count, const pvValue *value, KTL_DATATYPE ktlType, int ktlCount, KTL_POLYMORPH *ktlValue ) { // map types to ktlCnv's types (indices into conversion table) ktlCnv::type inpType = ktlCnv::getType( type ); ktlCnv::type outType = ktlCnv::getType( ktlType ); // allocate memory for KTL array or string if ( mallocKTL( ktlType, ktlCount, ktlValue ) < 0 ) return -1; // convert data return ktlCnv::convert( inpType, count, PV_VALPTR( type, value ), outType, ktlCount, KTL_VALPTR( ktlType, ktlValue )); } /*+ * Routine: mallocKTL * * Purpose: allocate dynamic data referenced from a polymorph * * Description: */ static int mallocKTL( KTL_DATATYPE ktlType, int ktlCount, KTL_POLYMORPH *ktlValue ) { switch ( ktlType ) { case KTL_STRING: ktlValue->s = new char[sizeof(pvString)]; if ( ktlValue->s == NULL ) goto error; break; case KTL_INT_ARRAY: ktlValue->ia = new int[ktlCount]; if ( ktlValue->ia == NULL ) goto error; break; case KTL_FLOAT_ARRAY: ktlValue->fa = new float[ktlCount]; if ( ktlValue->fa == NULL ) goto error; break; case KTL_DOUBLE_ARRAY: ktlValue->da = new double[ktlCount]; if ( ktlValue->da == NULL ) goto error; break; default: break; } return 0; error: ktl_set_errtxt( "memory allocation failure" ); return -1; } /*+ * Routine: freeKTL * * Purpose: free data referenced from a polymorph * * Description: */ static void freeKTL( KTL_DATATYPE ktlType, KTL_POLYMORPH *ktlValue ) { // do nothing if pointer (this is also ia, fa and da) is NULL if ( ktlValue->s == NULL ) return; switch ( ktlType ) { case KTL_STRING: delete [] ktlValue->s; break; case KTL_INT_ARRAY: delete [] ktlValue->ia; break; case KTL_FLOAT_ARRAY: delete [] ktlValue->fa; break; case KTL_DOUBLE_ARRAY: delete [] ktlValue->da; break; default: break; } } /* * pvKtl.cc,v * Revision 1.2 2001/02/16 18:45:39 mrk * changes for latest version of 3.14 * * Revision 1.1.1.1 2000/04/04 03:22:14 wlupton * first commit of seq-2-0-0 * * Revision 1.19 2000/03/31 23:01:41 wlupton * supported setStatus * * Revision 1.18 2000/03/29 23:28:05 wlupton * corrected comment typo * * Revision 1.17 2000/03/29 02:00:45 wlupton * monitor all keywords (forces connect request to be sent) * * Revision 1.16 2000/03/18 04:00:25 wlupton * converted to use new configure scheme * * Revision 1.15 2000/03/16 02:11:29 wlupton * supported KTL_ANYPOLY (plus misc other mods) * * Revision 1.14 2000/03/08 01:32:29 wlupton * cut out some early error exits in constructors (to avoid crashes in destructors) * * Revision 1.13 2000/03/07 19:55:32 wlupton * nearly sufficient tidying up * * Revision 1.12 2000/03/07 09:27:39 wlupton * drastically reduced use of references * * Revision 1.11 2000/03/07 08:46:29 wlupton * created ktlKeyword class (works but a bit messy) * * Revision 1.10 2000/03/06 19:21:04 wlupton * misc error reporting and type conversion mods * * Revision 1.9 2000/03/01 02:07:14 wlupton * converted to use new OSI library * * Revision 1.8 2000/02/19 01:12:22 wlupton * misc tidy-up and bug fixes * * Revision 1.7 2000/02/14 21:33:07 wlupton * fixed workshop 5.0 compilation error * * Revision 1.6 1999/10/12 02:53:13 wlupton * fixed KTL_NOTIFY support (cannot have been tested) * * Revision 1.5 1999/09/07 20:43:21 epics * increased debug level for pend() call * * Revision 1.4 1999/07/01 20:50:20 wlupton * Working under VxWorks * * Revision 1.3 1999/06/29 01:56:25 wlupton * always use 0.1s select() timeout because of startup problem seeing fds open * * Revision 1.2 1999/06/15 10:11:03 wlupton * demo sequence mostly working with KTL * * Revision 1.1 1999/06/11 02:20:32 wlupton * nearly working with KTL * */
25.709245
83
0.620231
A2-Collaboration
0211373261e4a69c016dbb3cd97997a936868459
1,467
cpp
C++
atcoder.jp/abc195/abc195_f/main.cpp
Shahraaz/CP_S5
2cfb5467841d660c1e47cb8338ea692f10ca6e60
[ "MIT" ]
3
2020-02-08T10:34:16.000Z
2020-02-09T10:23:19.000Z
atcoder.jp/abc195/abc195_f/main.cpp
Shahraaz/CP_S5
2cfb5467841d660c1e47cb8338ea692f10ca6e60
[ "MIT" ]
null
null
null
atcoder.jp/abc195/abc195_f/main.cpp
Shahraaz/CP_S5
2cfb5467841d660c1e47cb8338ea692f10ca6e60
[ "MIT" ]
2
2020-10-02T19:05:32.000Z
2021-09-08T07:01:49.000Z
#include <bits/stdc++.h> using namespace std; #ifdef LOCAL #include "/debug.h" #else #define db(...) #endif #define all(v) v.begin(), v.end() #define pb push_back using ll = long long; const int NAX = 2e5 + 5, MOD = 1000000007; vector<int> primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71}; int dp[80][1 << 21]; int64_t solveCase(int64_t A, int64_t B) { // TODO: edit here memset(dp, -1, sizeof dp); function<ll(ll, int)> solve = [&](ll curr, int mask) -> ll { if (curr == B + 1) return 1; auto &ret = dp[curr - A][mask]; if (ret >= 0) return ret; ret = solve(curr + 1, mask); bool ok = true; int nmask = mask; for (size_t i = 0; i < primes.size(); i++) if (curr % primes[i] == 0) { if ((mask >> i) & 1) ok = false; else nmask |= 1 << i; } if (ok) ret += solve(curr + 1, nmask); db(ret, curr, bitset<21>(mask)); return ret; }; return solve(A, 0); } // generated by oj-template v4.7.2 (https://github.com/online-judge-tools/template-generator) int main() { #ifndef LOCAL std::ios::sync_with_stdio(false); std::cin.tie(nullptr); #endif constexpr char endl = '\n'; int64_t A, B; cin >> A >> B; auto ans = solveCase(A, B); cout << ans << endl; return 0; }
24.864407
98
0.497614
Shahraaz
021a7093b387714c0e9a8e0b19e30baa4b9a3179
1,572
cpp
C++
mainwindow.cpp
jiangfangzheng/JfzQtFramework
676d9ac2c2d7bce90bf7e3b176a5cac26cc9eba5
[ "Apache-2.0" ]
1
2019-11-18T06:38:58.000Z
2019-11-18T06:38:58.000Z
mainwindow.cpp
jiangfangzheng/JfzQtFramework
676d9ac2c2d7bce90bf7e3b176a5cac26cc9eba5
[ "Apache-2.0" ]
null
null
null
mainwindow.cpp
jiangfangzheng/JfzQtFramework
676d9ac2c2d7bce90bf7e3b176a5cac26cc9eba5
[ "Apache-2.0" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include "skins/skins.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // Skin this->initSkins(); // 托盘 myTray = new SystemTray(this); connect(myTray,SIGNAL(showWidget()),this,SLOT(ShowWindow()));//关联信号和槽函数 connect(myTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(SystemTrayActivated(QSystemTrayIcon::ActivationReason))); } MainWindow::~MainWindow() { delete ui; } void MainWindow::initSkins() { // 对应的主题样式 mapStyle["黑色"] = QString(":/qss/black.css"); mapStyle["灰黑色"] = QString(":/qss/brown.css"); mapStyle["灰色"] = QString(":/qss/gray.css"); mapStyle["浅灰色"] = QString(":/qss/lightgray.css"); mapStyle["深灰色"] = QString(":/qss/darkgray.css"); mapStyle["银色"] = QString(":/qss/silvery.css"); mapStyle["淡蓝色"] = QString(":/qss/blue.css"); mapStyle["蓝色"] = QString(":/qss/dev.css"); // 下拉框选择 QStringList qssName; qssName << "黑色" << "灰黑色" << "灰色" << "浅灰色" << "深灰色" << "银色" << "淡蓝色" << "蓝色"; // ui->cboxSkins->addItems(qssName); // ui->cboxSkins->setCurrentIndex(5);// 个人最喜欢银,默认 // 直接赋值 QString qssFile = mapStyle["蓝色"]; Skins::setStyle(qssFile); } // 托盘相关 void MainWindow::ShowWindow() { this->showNormal(); this->raise(); this->activateWindow(); } void MainWindow::SystemTrayActivated(QSystemTrayIcon::ActivationReason reason) { switch(reason) { case QSystemTrayIcon::Trigger: { ShowWindow(); break; } case QSystemTrayIcon::DoubleClick: { ShowWindow(); break; } default: break; } }
22.782609
139
0.667939
jiangfangzheng
021d1f0c93284d9dd8db0d3cef62784aec55eebb
5,827
cpp
C++
lang/steve/Syntax.cpp
flowgrammable/steve-legacy
5e7cbc16280c199732d26a2cb0703422695abe16
[ "Apache-2.0" ]
1
2017-07-30T04:18:56.000Z
2017-07-30T04:18:56.000Z
lang/steve/Syntax.cpp
flowgrammable/steve-legacy
5e7cbc16280c199732d26a2cb0703422695abe16
[ "Apache-2.0" ]
null
null
null
lang/steve/Syntax.cpp
flowgrammable/steve-legacy
5e7cbc16280c199732d26a2cb0703422695abe16
[ "Apache-2.0" ]
null
null
null
#include <steve/Syntax.hpp> #include <steve/Print.hpp> #include <steve/Debug.hpp> namespace steve { void init_trees() { // Terms init_node(id_tree, "id-tree"); init_node(lit_tree, "lit-tree"); init_node(brace_tree, "brace-tree"); init_node(call_tree, "call-tree"); init_node(index_tree, "index-tree"); init_node(dot_tree, "dot-tree"); init_node(range_tree, "range-tree"); init_node(app_tree, "app-tree"); init_node(unary_tree, "unary-tree"); init_node(binary_tree, "binary-tree"); init_node(if_tree, "if-tree"); // Types init_node(record_tree, "record-tree"); init_node(variant_tree, "variant-tree"); init_node(enum_tree, "enum-tree"); // Statements init_node(block_tree, "block-tree"); init_node(return_tree, "return-tree"); init_node(break_tree, "break-tree"); init_node(cont_tree, "cont-tree"); init_node(while_tree, "while-tree"); init_node(switch_tree, "switch-tree"); init_node(load_tree, "load-tree"); // Declarations init_node(value_tree, "value-tree"); init_node(parm_tree, "parm-tree"); init_node(fn_tree, "fn-tree"); init_node(def_tree, "def-tree"); init_node(field_tree, "field-tree"); init_node(alt_tree, "alt-tree"); init_node(import_tree, "import-tree"); init_node(using_tree, "using-tree"); // Misc init_node(top_tree, "top-tree"); } // FIXME: A whole lot of this stuff is common in both Ast.cpp and // here. In fact, it's practically verbatim. It would not be amiss // to move much of this out to Node.cpp. namespace { struct sexpr { sexpr(Printer& p, const char* n) : printer(p) { print(printer, '('); print(printer, n); print_space(printer); } sexpr(Printer& p, String s) : sexpr(p, s.data()) { } template<typename T> sexpr(Printer& p, T* n) : sexpr(p, node_name(n)) { } ~sexpr() { print(printer, ')'); } Printer& printer; }; void debug_print(Printer&, Tree*); void debug_print(Printer& p, const Token* k) { print(p, k->text); } struct debug_printer { template<typename T> void operator()(Printer& p, T t) const { debug_print(p, t); } }; // Top-level match printing sequences-of-T. template<typename T> void debug_print(Printer& p, Seq<T>* s) { print(p, '('); print_separated(p, s, debug_printer(), space_separator()); print(p, ')'); } // Note that t->first is a token. template<typename T> inline void debug_terminal(Printer& p, T* t) { sexpr s(p, t); debug_print(p, t->first); } template<typename T> inline void debug_nullary(Printer& p, T* t) { sexpr s(p, t); } template<typename T> inline void debug_unary(Printer& p, T* t) { sexpr s(p, t); debug_print(p, t->first); } template<typename T> void debug_binary(Printer& p, T* t) { sexpr s(p, t); debug_print(p, t->first); print_space(p); debug_print(p, t->second); } template<typename T> inline void debug_ternary(Printer& p, T* t) { sexpr s(p, t); debug_print(p, t->first); print_space(p); debug_print(p, t->second); print_space(p); debug_print(p, t->third); } void debug_unary(Printer& p, Unary_tree* t) { sexpr s(p, t->op()->text); debug_print(p, t->arg()); } void debug_binary(Printer& p, Binary_tree* t) { sexpr s(p, t->op()->text); debug_print(p, t->left()); print_space(p); debug_print(p, t->right()); } void debug_top(Printer& p, Top_tree* t) { sexpr s(p, t); indent(p); print_newline(p); for (Tree* s : *t->first) { print_indent(p); debug_print(p, s); print_newline(p); } undent(p); print_indent(p); } void debug_print(Printer& p, Tree* t) { if (not t) { print(p, "()"); return; } switch (t->kind) { // Terms case id_tree: return debug_terminal(p, as<Id_tree>(t)); case lit_tree: return debug_terminal(p, as<Lit_tree>(t)); case brace_tree: return debug_unary(p, as<Brace_tree>(t)); case call_tree: return debug_binary(p, as<Call_tree>(t)); case index_tree: return debug_binary(p, as<Index_tree>(t)); case app_tree: return debug_binary(p, as<App_tree>(t)); case dot_tree: return debug_binary(p, as<Dot_tree>(t)); case range_tree: return debug_binary(p, as<Range_tree>(t)); case unary_tree: return debug_unary(p, as<Unary_tree>(t)); case binary_tree: return debug_binary(p, as<Binary_tree>(t)); case if_tree: return debug_ternary(p, as<If_tree>(t)); // Types case record_tree: return debug_unary(p, as<Record_tree>(t)); case variant_tree: return debug_binary(p, as<Variant_tree>(t)); case enum_tree: return debug_binary(p, as<Enum_tree>(t)); // Statements case return_tree: return debug_unary(p, as<Return_tree>(t)); case break_tree: return debug_nullary(p, as<Break_tree>(t)); case cont_tree: return debug_nullary(p, as<Cont_tree>(t)); case while_tree: return debug_binary(p, as<While_tree>(t)); case switch_tree: return debug_binary(p, as<Switch_tree>(t)); case case_tree: return debug_binary(p, as<Case_tree>(t)); case load_tree: return debug_unary(p, as<Load_tree>(t)); // Declarations case value_tree: return debug_binary(p, as<Value_tree>(t)); case parm_tree: return debug_ternary(p, as<Parm_tree>(t)); case fn_tree: return debug_ternary(p, as<Fn_tree>(t)); case def_tree: return debug_binary(p, as<Def_tree>(t)); case field_tree: return debug_ternary(p, as<Field_tree>(t)); case alt_tree: return debug_binary(p, as<Alt_tree>(t)); case import_tree: return debug_unary(p, as<Import_tree>(t)); case using_tree: return debug_unary(p, as<Using_tree>(t)); // Misc case top_tree: return debug_top(p, as<Top_tree>(t)); // Unhandled default: steve_unreachable("unhandled parse tree"); } } } // namespace std::ostream& operator<<(std::ostream& os, debug_tree d) { Printer p(os); debug_print(p, d.e); return os; } } // namespace steve
26.130045
66
0.665866
flowgrammable
0223e335169af73587acf33e192b13720d7cf256
4,795
hpp
C++
libs/iostreams/test/write_bidir_filter_test.hpp
zyiacas/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
198
2015-01-13T05:47:18.000Z
2022-03-09T04:46:46.000Z
libs/iostreams/test/write_bidir_filter_test.hpp
sdfict/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
9
2015-01-28T16:33:19.000Z
2020-04-12T23:03:28.000Z
libs/iostreams/test/write_bidir_filter_test.hpp
sdfict/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
139
2015-01-15T20:09:31.000Z
2022-01-31T15:21:16.000Z
// (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com) // (C) Copyright 2004-2007 Jonathan Turkanis // 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://www.boost.org/libs/iostreams for documentation. #ifndef BOOST_IOSTREAMS_TEST_WRITE_INOUT_FILTER_HPP_INCLUDED #define BOOST_IOSTREAMS_TEST_WRITE_INOUT_FILTER_HPP_INCLUDED #include <fstream> #include <boost/iostreams/combine.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/test/test_tools.hpp> #include "detail/filters.hpp" #include "detail/sequence.hpp" #include "detail/temp_file.hpp" #include "detail/verification.hpp" void write_bidirectional_filter_test() { using namespace std; using namespace boost; using namespace boost::iostreams; using namespace boost::iostreams::test; lowercase_file lower; BOOST_IOS::openmode mode = out_mode | BOOST_IOS::trunc; { temp_file lower2; filebuf dest; filtering_stream<bidirectional> out; dest.open(lower2.name().c_str(), mode); out.push(combine(toupper_filter(), tolower_filter())); out.push(dest); write_data_in_chars(out); out.reset(); dest.close(); BOOST_CHECK_MESSAGE( compare_files(lower2.name(), lower.name()), "failed writing to a filtering_stream<bidirectional> in chars with an " "output filter" ); } { // OutputFilter. temp_file lower2; filebuf dest; filtering_stream<bidirectional> out; out.push(combine(toupper_filter(), tolower_filter())); dest.open(lower2.name().c_str(), mode); out.push(dest); write_data_in_chunks(out); out.reset(); dest.close(); BOOST_CHECK_MESSAGE( compare_files(lower2.name(), lower.name()), "failed writing to a filtering_stream<bidirectional> in chunks with an " "output filter" ); } { temp_file lower2; filebuf dest; filtering_stream<bidirectional> out; out.push(combine(toupper_filter(), tolower_multichar_filter()), 0); dest.open(lower2.name().c_str(), mode); out.push(dest); write_data_in_chars(out); out.reset(); dest.close(); BOOST_CHECK_MESSAGE( compare_files(lower2.name(), lower.name()), "failed writing to a filtering_stream<bidirectional> in chars " "with a multichar output filter with no buffer" ); } { temp_file lower2; filebuf dest; filtering_stream<bidirectional> out; out.push(combine(toupper_filter(), tolower_multichar_filter()), 0); dest.open(lower2.name().c_str(), mode); out.push(dest); write_data_in_chunks(out); out.reset(); dest.close(); BOOST_CHECK_MESSAGE( compare_files(lower2.name(), lower.name()), "failed writing to a filtering_stream<bidirectional> in chunks " "with a multichar output filter with no buffer" ); } { temp_file lower2; filebuf dest; filtering_stream<bidirectional> out; out.push(combine(toupper_filter(), tolower_multichar_filter())); dest.open(lower2.name().c_str(), mode); out.push(dest); write_data_in_chars(out); out.reset(); dest.close(); BOOST_CHECK_MESSAGE( compare_files(lower2.name(), lower.name()), "failed writing to a filtering_stream<bidirectional> in chars " "with a multichar output filter" ); } { temp_file lower2; filebuf dest; filtering_stream<bidirectional> out; out.push(combine(toupper_filter(), tolower_multichar_filter())); dest.open(lower2.name().c_str(), mode); out.push(dest); write_data_in_chunks(out); out.reset(); dest.close(); BOOST_CHECK_MESSAGE( compare_files(lower2.name(), lower.name()), "failed writing to a filtering_stream<bidirectional> in chunks " "with a buffered output filter" ); } } #endif // #ifndef BOOST_IOSTREAMS_TEST_WRITE_BIDIRECTIONAL_FILTER_HPP_INCLUDED
35.518519
85
0.572471
zyiacas
0227bf12c90e0a56a4e0729185a2f700f4eab792
21,446
cpp
C++
test/queuemanager.cpp
bogdasar1985/newsboat
3ccc76b45ea86116d25a3dd7602a95350f878c77
[ "MIT" ]
null
null
null
test/queuemanager.cpp
bogdasar1985/newsboat
3ccc76b45ea86116d25a3dd7602a95350f878c77
[ "MIT" ]
null
null
null
test/queuemanager.cpp
bogdasar1985/newsboat
3ccc76b45ea86116d25a3dd7602a95350f878c77
[ "MIT" ]
null
null
null
#include "queuemanager.h" #include "3rd-party/catch.hpp" #include "test_helpers/chmod.h" #include "test_helpers/envvar.h" #include "test_helpers/misc.h" #include "test_helpers/tempfile.h" #include "cache.h" #include "configcontainer.h" #include "rssfeed.h" #include "rssitem.h" #include "utils.h" using namespace newsboat; SCENARIO("Smoke test for QueueManager", "[QueueManager]") { GIVEN("A fresh instance of QueueManager") { ConfigContainer cfg; Cache cache(":memory:", &cfg); auto item = std::make_shared<RssItem>(&cache); const std::string enclosure_url("https://example.com/podcast.mp3"); item->set_enclosure_url(enclosure_url); item->set_enclosure_type("audio/mpeg"); auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/news.atom"); test_helpers::TempFile queue_file; QueueManager manager(&cfg, queue_file.get_path()); THEN("the queue file is not automatically created") { REQUIRE_FALSE(test_helpers::file_exists(queue_file.get_path())); } WHEN("enqueue_url() is called") { const auto result = manager.enqueue_url(item, feed); THEN("the return value indicates success") { REQUIRE(result.status == EnqueueStatus::QUEUED_SUCCESSFULLY); REQUIRE(result.extra_info == ""); } THEN("the queue file contains an entry") { REQUIRE(test_helpers::file_exists(queue_file.get_path())); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 2); REQUIRE(test_helpers::starts_with(enclosure_url, lines[0])); REQUIRE(test_helpers::ends_with(R"(/podcast.mp3")", lines[0])); REQUIRE(lines[1] == ""); } THEN("the item is marked as enqueued") { REQUIRE(item->enqueued()); } } WHEN("enqueue_url() is called on the same item twice in a row") { manager.enqueue_url(item, feed); const auto result = manager.enqueue_url(item, feed); THEN("the second call indicates that the enclosure is already in the queue") { REQUIRE(result.status == EnqueueStatus::URL_QUEUED_ALREADY); REQUIRE(result.extra_info == enclosure_url); } THEN("the queue file contains a single entry") { REQUIRE(test_helpers::file_exists(queue_file.get_path())); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 2); REQUIRE(test_helpers::starts_with(enclosure_url, lines[0])); REQUIRE(test_helpers::ends_with(R"(/podcast.mp3")", lines[0])); REQUIRE(lines[1] == ""); } THEN("the item is marked as enqueued") { REQUIRE(item->enqueued()); } } WHEN("enqueue_url() is called for multiple different items") { const auto result = manager.enqueue_url(item, feed); auto item2 = std::make_shared<RssItem>(&cache); item2->set_enclosure_url("https://www.example.com/another.mp3"); item2->set_enclosure_type("audio/mpeg"); const auto result2 = manager.enqueue_url(item2, feed); auto item3 = std::make_shared<RssItem>(&cache); item3->set_enclosure_url("https://joe.example.com/vacation.jpg"); item3->set_enclosure_type("image/jpeg"); const auto result3 = manager.enqueue_url(item3, feed); THEN("return values indicate success") { REQUIRE(result.status == EnqueueStatus::QUEUED_SUCCESSFULLY); REQUIRE(result.extra_info == ""); REQUIRE(result2.status == EnqueueStatus::QUEUED_SUCCESSFULLY); REQUIRE(result2.extra_info == ""); REQUIRE(result3.status == EnqueueStatus::QUEUED_SUCCESSFULLY); REQUIRE(result3.extra_info == ""); } THEN("the queue file contains three entries") { REQUIRE(test_helpers::file_exists(queue_file.get_path())); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 4); REQUIRE(lines[0] != ""); REQUIRE(lines[1] != ""); REQUIRE(lines[2] != ""); REQUIRE(lines[3] == ""); } THEN("items are marked as enqueued") { REQUIRE(item->enqueued()); REQUIRE(item2->enqueued()); REQUIRE(item3->enqueued()); } } } } SCENARIO("enqueue_url() errors if the filename is already used", "[QueueManager]") { GIVEN("Pristine QueueManager and two RssItems") { ConfigContainer cfg; Cache cache(":memory:", &cfg); auto item1 = std::make_shared<RssItem>(&cache); const std::string enclosure_url1("https://example.com/podcast.mp3"); item1->set_enclosure_url(enclosure_url1); item1->set_enclosure_type("audio/mpeg"); auto item2 = std::make_shared<RssItem>(&cache); const std::string enclosure_url2("https://example.com/~joe/podcast.mp3"); item2->set_enclosure_url(enclosure_url2); item2->set_enclosure_type("audio/mpeg"); auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/news.atom"); test_helpers::TempFile queue_file; QueueManager manager(&cfg, queue_file.get_path()); WHEN("first item is enqueued") { const auto result = manager.enqueue_url(item1, feed); THEN("the return value indicates success") { REQUIRE(result.status == EnqueueStatus::QUEUED_SUCCESSFULLY); REQUIRE(result.extra_info == ""); } THEN("the queue file contains a corresponding entry") { REQUIRE(test_helpers::file_exists(queue_file.get_path())); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 2); REQUIRE(test_helpers::starts_with(enclosure_url1, lines[0])); REQUIRE(test_helpers::ends_with(R"(/podcast.mp3")", lines[0])); REQUIRE(lines[1] == ""); } THEN("the item is marked as enqueued") { REQUIRE(item1->enqueued()); } AND_WHEN("second item is enqueued") { const auto result = manager.enqueue_url(item2, feed); THEN("the return value indicates that the filename is already used") { REQUIRE(result.status == EnqueueStatus::OUTPUT_FILENAME_USED_ALREADY); // That field contains a path to the temporary directory, // so we simply check that it's not empty. REQUIRE(result.extra_info != ""); } THEN("the queue file still contains a single entry") { REQUIRE(test_helpers::file_exists(queue_file.get_path())); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 2); REQUIRE(test_helpers::starts_with(enclosure_url1, lines[0])); REQUIRE(test_helpers::ends_with(R"(/podcast.mp3")", lines[0])); REQUIRE(lines[1] == ""); } THEN("the item is NOT marked as enqueued") { REQUIRE_FALSE(item2->enqueued()); } } } } } SCENARIO("enqueue_url() errors if the queue file can't be opened for writing", "[QueueManager]") { GIVEN("Pristine QueueManager, an RssItem, and an uneditable queue file") { ConfigContainer cfg; Cache cache(":memory:", &cfg); auto item = std::make_shared<RssItem>(&cache); item->set_enclosure_url("https://example.com/podcast.mp3"); item->set_enclosure_type("audio/mpeg"); auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/news.atom"); test_helpers::TempFile queue_file; QueueManager manager(&cfg, queue_file.get_path()); test_helpers::copy_file("data/empty-file", queue_file.get_path()); // The file is read-only test_helpers::Chmod uneditable_queue_file(queue_file.get_path(), 0444); WHEN("enqueue_url() is called") { const auto result = manager.enqueue_url(item, feed); THEN("the return value indicates the file couldn't be written to") { REQUIRE(result.status == EnqueueStatus::QUEUE_FILE_OPEN_ERROR); REQUIRE(result.extra_info == queue_file.get_path()); } THEN("the item is NOT marked as enqueued") { REQUIRE_FALSE(item->enqueued()); } } } } TEST_CASE("QueueManager puts files into a location configured by `download-path`", "[QueueManager]") { ConfigContainer cfg; SECTION("path with a slash at the end") { cfg.set_configvalue("download-path", "/tmp/nonexistent-newsboat/"); } SECTION("path without a slash at the end") { cfg.set_configvalue("download-path", "/tmp/nonexistent-newsboat"); } Cache cache(":memory:", &cfg); auto item1 = std::make_shared<RssItem>(&cache); const std::string enclosure_url1("https://example.com/podcast.mp3"); item1->set_enclosure_url(enclosure_url1); item1->set_enclosure_type("audio/mpeg"); auto item2 = std::make_shared<RssItem>(&cache); const std::string enclosure_url2("https://example.com/~joe/podcast.ogg"); item2->set_enclosure_url(enclosure_url2); item2->set_enclosure_type("audio/vorbis"); auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/podcasts.atom"); test_helpers::TempFile queue_file; QueueManager manager(&cfg, queue_file.get_path()); const auto result1 = manager.enqueue_url(item1, feed); REQUIRE(result1.status == EnqueueStatus::QUEUED_SUCCESSFULLY); REQUIRE(result1.extra_info == ""); REQUIRE(item1->enqueued()); const auto result2 = manager.enqueue_url(item2, feed); REQUIRE(result2.status == EnqueueStatus::QUEUED_SUCCESSFULLY); REQUIRE(result2.extra_info == ""); REQUIRE(item2->enqueued()); REQUIRE(test_helpers::file_exists(queue_file.get_path())); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 3); REQUIRE(lines[0] == R"(https://example.com/podcast.mp3 "/tmp/nonexistent-newsboat/podcast.mp3")"); REQUIRE(lines[1] == R"(https://example.com/~joe/podcast.ogg "/tmp/nonexistent-newsboat/podcast.ogg")"); REQUIRE(lines[2] == ""); } TEST_CASE("QueueManager names files according to the `download-filename-format` setting", "[QueueManager]") { ConfigContainer cfg; // We set the download-path to a fixed value to ensure that we know // *exactly* how the result should look. cfg.set_configvalue("download-path", "/example/"); Cache cache(":memory:", &cfg); auto item = std::make_shared<RssItem>(&cache); item->set_enclosure_url("https://example.com/~adam/podcast.mp3"); item->set_enclosure_type("audio/mpeg"); auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/podcasts.atom"); test_helpers::TempFile queue_file; QueueManager manager(&cfg, queue_file.get_path()); SECTION("%n for current feed title, with slashes replaced by underscores") { cfg.set_configvalue("download-filename-format", "%n"); feed->set_title("Feed title/theme"); manager.enqueue_url(item, feed); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 2); REQUIRE(lines[0] == R"(https://example.com/~adam/podcast.mp3 "/example/Feed title_theme")"); REQUIRE(lines[1] == ""); } SECTION("%h for the enclosure URL's hostname") { cfg.set_configvalue("download-filename-format", "%h"); manager.enqueue_url(item, feed); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 2); REQUIRE(lines[0] == R"(https://example.com/~adam/podcast.mp3 "/example/example.com")"); REQUIRE(lines[1] == ""); } SECTION("%u for the enclosure URL's basename") { cfg.set_configvalue("download-filename-format", "%u"); manager.enqueue_url(item, feed); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 2); REQUIRE(lines[0] == R"(https://example.com/~adam/podcast.mp3 "/example/podcast.mp3")"); REQUIRE(lines[1] == ""); } SECTION("%F, %m, %b, %d, %H, %M, %S, %y, and %Y to render items's publication date with strftime") { // %H is sensitive to the timezone, so reset it to UTC for a time being test_helpers::TzEnvVar tzEnv; tzEnv.set("UTC"); cfg.set_configvalue("download-filename-format", "%F, %m, %b, %d, %H, %M, %S, %y, and %Y"); // Tue, 06 Apr 2021 15:38:19 +0000 item->set_pubDate(1617723499); manager.enqueue_url(item, feed); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 2); REQUIRE(lines[0] == R"(https://example.com/~adam/podcast.mp3 "/example/2021-04-06, 04, Apr, 06, 15, 38, 19, 21, and 2021")"); REQUIRE(lines[1] == ""); } SECTION("%t for item title, with slashes replaced by underscores") { cfg.set_configvalue("download-filename-format", "%t"); item->set_title("Rain/snow/sun in a single day"); manager.enqueue_url(item, feed); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 2); REQUIRE(lines[0] == R"(https://example.com/~adam/podcast.mp3 "/example/Rain_snow_sun in a single day")"); REQUIRE(lines[1] == ""); } SECTION("%e for enclosure's filename extension") { cfg.set_configvalue("download-filename-format", "%e"); manager.enqueue_url(item, feed); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 2); REQUIRE(lines[0] == R"(https://example.com/~adam/podcast.mp3 "/example/mp3")"); REQUIRE(lines[1] == ""); } SECTION("%N for the feed's title (even if `feed` passed into a function is different)") { cfg.set_configvalue("download-filename-format", "%N"); SECTION("`feed` argument is irrelevant") { feed->set_title("Relevant feed"); item->set_feedptr(feed); auto irrelevant_feed = std::make_shared<RssFeed>(&cache, "https://example.com/podcasts.atom"); irrelevant_feed->set_title("Irrelevant"); manager.enqueue_url(item, irrelevant_feed); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 2); REQUIRE(lines[0] == R"(https://example.com/~adam/podcast.mp3 "/example/Relevant feed")"); REQUIRE(lines[1] == ""); } SECTION("`feed` argument is relevant") { feed->set_title("Relevant feed"); item->set_feedptr(feed); manager.enqueue_url(item, feed); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 2); REQUIRE(lines[0] == R"(https://example.com/~adam/podcast.mp3 "/example/Relevant feed")"); REQUIRE(lines[1] == ""); } } } TEST_CASE("autoenqueue() adds all enclosures of all items to the queue", "[QueueManager]") { GIVEN("Pristine QueueManager and a feed of three items") { ConfigContainer cfg; Cache cache(":memory:", &cfg); auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/podcasts.atom"); auto item1 = std::make_shared<RssItem>(&cache); item1->set_enclosure_url("https://example.com/~adam/podcast.mp3"); item1->set_enclosure_type("audio/mpeg"); feed->add_item(item1); auto item2 = std::make_shared<RssItem>(&cache); item2->set_enclosure_url("https://example.com/episode.ogg"); item2->set_enclosure_type("audio/vorbis"); feed->add_item(item2); auto item3 = std::make_shared<RssItem>(&cache); item3->set_enclosure_url("https://example.com/~fae/painting.jpg"); item3->set_enclosure_type("image/jpeg"); feed->add_item(item3); test_helpers::TempFile queue_file; QueueManager manager(&cfg, queue_file.get_path()); WHEN("autoenqueue() is called") { const auto result = manager.autoenqueue(feed); THEN("the return value indicates success") { REQUIRE(result.status == EnqueueStatus::QUEUED_SUCCESSFULLY); REQUIRE(result.extra_info == ""); } THEN("the queue file contains three entries") { REQUIRE(test_helpers::file_exists(queue_file.get_path())); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 4); REQUIRE(lines[0] != ""); REQUIRE(lines[1] != ""); REQUIRE(lines[2] != ""); REQUIRE(lines[3] == ""); } THEN("items are marked as enqueued") { REQUIRE(item1->enqueued()); REQUIRE(item2->enqueued()); REQUIRE(item3->enqueued()); } } } } SCENARIO("autoenqueue() errors if the filename is already used", "[QueueManager]") { GIVEN("Pristine QueueManager and a feed of two items") { ConfigContainer cfg; Cache cache(":memory:", &cfg); auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/news.atom"); auto item1 = std::make_shared<RssItem>(&cache); const std::string enclosure_url1("https://example.com/podcast.mp3"); item1->set_enclosure_url(enclosure_url1); item1->set_enclosure_type("audio/mpeg"); feed->add_item(item1); auto item2 = std::make_shared<RssItem>(&cache); const std::string enclosure_url2("https://example.com/~joe/podcast.mp3"); item2->set_enclosure_url(enclosure_url2); item2->set_enclosure_type("audio/mpeg"); feed->add_item(item2); test_helpers::TempFile queue_file; QueueManager manager(&cfg, queue_file.get_path()); WHEN("autoenqueue() is called") { const auto result = manager.autoenqueue(feed); THEN("the return value indicates that the filename is already used") { REQUIRE(result.status == EnqueueStatus::OUTPUT_FILENAME_USED_ALREADY); // That field contains a path to the temporary directory, // so we simply check that it's not empty. REQUIRE(result.extra_info != ""); } THEN("the queue file still contains a single entry") { REQUIRE(test_helpers::file_exists(queue_file.get_path())); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 2); REQUIRE(test_helpers::starts_with(enclosure_url1, lines[0])); REQUIRE(test_helpers::ends_with(R"(/podcast.mp3")", lines[0])); REQUIRE(lines[1] == ""); } THEN("the first item is enqueued, the second one isn't") { REQUIRE(item1->enqueued()); REQUIRE_FALSE(item2->enqueued()); } } } } SCENARIO("autoenqueue() errors if the queue file can't be opened for writing", "[QueueManager]") { GIVEN("Pristine QueueManager, a single-item feed, and an uneditable queue file") { ConfigContainer cfg; Cache cache(":memory:", &cfg); auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/news.atom"); auto item = std::make_shared<RssItem>(&cache); item->set_enclosure_url("https://example.com/podcast.mp3"); item->set_enclosure_type("audio/mpeg"); feed->add_item(item); test_helpers::TempFile queue_file; QueueManager manager(&cfg, queue_file.get_path()); test_helpers::copy_file("data/empty-file", queue_file.get_path()); // The file is read-only test_helpers::Chmod uneditable_queue_file(queue_file.get_path(), 0444); WHEN("autoenqueue() is called") { const auto result = manager.autoenqueue(feed); THEN("the return value indicates the file couldn't be written to") { REQUIRE(result.status == EnqueueStatus::QUEUE_FILE_OPEN_ERROR); REQUIRE(result.extra_info == queue_file.get_path()); } THEN("the item is NOT marked as enqueued") { REQUIRE_FALSE(item->enqueued()); } } } } TEST_CASE("autoenqueue() skips already-enqueued items", "[QueueManager]") { ConfigContainer cfg; // We set the download-path to a fixed value to ensure that we know // *exactly* how the result should look. cfg.set_configvalue("download-path", "/example/"); Cache cache(":memory:", &cfg); auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/news.atom"); auto item1 = std::make_shared<RssItem>(&cache); item1->set_enclosure_url("https://example.com/podcast.mp3"); item1->set_enclosure_type("audio/mpeg"); feed->add_item(item1); auto item2 = std::make_shared<RssItem>(&cache); item2->set_enclosure_url("https://example.com/podcast2.mp3"); item2->set_enclosure_type("audio/mpeg"); item2->set_enqueued(true); feed->add_item(item2); auto item3 = std::make_shared<RssItem>(&cache); item3->set_enclosure_url("https://example.com/podcast3.mp3"); item3->set_enclosure_type("audio/mpeg"); feed->add_item(item3); test_helpers::TempFile queue_file; QueueManager manager(&cfg, queue_file.get_path()); const auto result = manager.autoenqueue(feed); REQUIRE(result.status == EnqueueStatus::QUEUED_SUCCESSFULLY); REQUIRE(result.extra_info == ""); REQUIRE(test_helpers::file_exists(queue_file.get_path())); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 3); REQUIRE(lines[0] == R"(https://example.com/podcast.mp3 "/example/podcast.mp3")"); REQUIRE(lines[1] == R"(https://example.com/podcast3.mp3 "/example/podcast3.mp3")"); REQUIRE(lines[2] == ""); } TEST_CASE("autoenqueue() only enqueues HTTP and HTTPS URLs", "[QueueManager]") { ConfigContainer cfg; // We set the download-path to a fixed value to ensure that we know // *exactly* how the result should look. cfg.set_configvalue("download-path", "/example/"); Cache cache(":memory:", &cfg); auto feed = std::make_shared<RssFeed>(&cache, "https://example.com/news.atom"); auto item1 = std::make_shared<RssItem>(&cache); item1->set_enclosure_url("https://example.com/podcast.mp3"); item1->set_enclosure_type("audio/mpeg"); feed->add_item(item1); auto item2 = std::make_shared<RssItem>(&cache); item2->set_enclosure_url("http://example.com/podcast2.mp3"); item2->set_enclosure_type("audio/mpeg"); feed->add_item(item2); auto item3 = std::make_shared<RssItem>(&cache); item3->set_enclosure_url("ftp://user@example.com/podcast3.mp3"); item3->set_enclosure_type("audio/mpeg"); feed->add_item(item3); test_helpers::TempFile queue_file; QueueManager manager(&cfg, queue_file.get_path()); const auto result = manager.autoenqueue(feed); REQUIRE(result.status == EnqueueStatus::QUEUED_SUCCESSFULLY); REQUIRE(result.extra_info == ""); REQUIRE(test_helpers::file_exists(queue_file.get_path())); const auto lines = test_helpers::file_contents(queue_file.get_path()); REQUIRE(lines.size() == 3); REQUIRE(lines[0] == R"(https://example.com/podcast.mp3 "/example/podcast.mp3")"); REQUIRE(lines[1] == R"(http://example.com/podcast2.mp3 "/example/podcast2.mp3")"); REQUIRE(lines[2] == ""); }
32.741985
108
0.698126
bogdasar1985
022b965947434f1dd36d4fb5de90befa2c568d30
22,449
cxx
C++
inetsrv/iis/admin/adsi/adsiis/var2sec.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/iis/admin/adsi/adsiis/var2sec.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/iis/admin/adsi/adsiis/var2sec.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1997. // // File: var2sec.cxx // // Contents: // // Functions: // // History: 25-Apr-97 KrishnaG Created. // //---------------------------------------------------------------------------- #include "iis.hxx" #pragma hdrstop HRESULT ConvertSecurityDescriptorToSecDes( IADsSecurityDescriptor FAR * pSecDes, PSECURITY_DESCRIPTOR * ppSecurityDescriptor, PDWORD pdwSDLength ) { HRESULT hr = S_OK; SECURITY_DESCRIPTOR AbsoluteSD; PSECURITY_DESCRIPTOR pRelative = NULL; BOOL Defaulted = FALSE; BOOL DaclPresent = FALSE; BOOL SaclPresent = FALSE; BOOL fDaclDefaulted = FALSE; BOOL fSaclDefaulted = FALSE; BOOL fOwnerDefaulted = FALSE; BOOL fGroupDefaulted = FALSE; PSID pOwnerSid = NULL; PSID pGroupSid = NULL; PACL pDacl = NULL; PACL pSacl = NULL; DWORD dwSDLength = 0; DWORD dwRet = 0; BOOL dwStatus = 0; LONG lControlFlags = 0; SECURITY_DESCRIPTOR_CONTROL dwControlFlags = 0; SECURITY_DESCRIPTOR_CONTROL dwControlMask = SE_DACL_AUTO_INHERIT_REQ | SE_DACL_AUTO_INHERITED | SE_DACL_PROTECTED | SE_SACL_AUTO_INHERIT_REQ | SE_SACL_AUTO_INHERITED | SE_SACL_PROTECTED; // // Initialize *pSizeSD = 0; // dwRet = InitializeSecurityDescriptor ( &AbsoluteSD, SECURITY_DESCRIPTOR_REVISION1 ); if (!dwRet) { hr = E_FAIL; BAIL_ON_FAILURE(hr); } hr = pSecDes->get_Control(&lControlFlags); BAIL_ON_FAILURE(hr); dwControlFlags = dwControlMask & (SECURITY_DESCRIPTOR_CONTROL)lControlFlags; dwStatus = SetSecurityDescriptorControl( &AbsoluteSD, dwControlMask, dwControlFlags ); if (!dwStatus) { hr = HRESULT_FROM_WIN32(GetLastError()); BAIL_ON_FAILURE(hr); } hr = GetOwnerSecurityIdentifier( pSecDes, &pOwnerSid, &fOwnerDefaulted ); BAIL_ON_FAILURE(hr); dwStatus = SetSecurityDescriptorOwner( &AbsoluteSD, pOwnerSid, fOwnerDefaulted ); if (!dwStatus) { hr = HRESULT_FROM_WIN32(GetLastError()); BAIL_ON_FAILURE(hr); } hr = GetGroupSecurityIdentifier( pSecDes, &pGroupSid, &fGroupDefaulted ); BAIL_ON_FAILURE(hr); dwStatus = SetSecurityDescriptorGroup( &AbsoluteSD, pGroupSid, fGroupDefaulted ); if (!dwStatus) { hr = HRESULT_FROM_WIN32(GetLastError()); BAIL_ON_FAILURE(hr); } hr = GetDacl( pSecDes, &pDacl, &fDaclDefaulted ); BAIL_ON_FAILURE(hr); if (pDacl || fDaclDefaulted) { DaclPresent = TRUE; } dwStatus = SetSecurityDescriptorDacl( &AbsoluteSD, DaclPresent, pDacl, fDaclDefaulted ); if (!dwStatus) { hr = HRESULT_FROM_WIN32(GetLastError()); BAIL_ON_FAILURE(hr); } hr = GetSacl( pSecDes, &pSacl, &fSaclDefaulted ); BAIL_ON_FAILURE(hr); if (pSacl || fSaclDefaulted) { SaclPresent = TRUE; } dwStatus = SetSecurityDescriptorSacl( &AbsoluteSD, SaclPresent, pSacl, fSaclDefaulted ); if (!dwStatus) { hr = HRESULT_FROM_WIN32(GetLastError()); BAIL_ON_FAILURE(hr); } dwSDLength = GetSecurityDescriptorLength( &AbsoluteSD ); pRelative = AllocADsMem(dwSDLength); if (!pRelative) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } if (!MakeSelfRelativeSD (&AbsoluteSD, pRelative, &dwSDLength)) { FreeADsMem(pRelative); hr = HRESULT_FROM_WIN32(GetLastError()); BAIL_ON_FAILURE(hr); } *ppSecurityDescriptor = pRelative; *pdwSDLength = dwSDLength; cleanup: if (pDacl) { FreeADsMem(pDacl); } if (pSacl) { FreeADsMem(pSacl); } if (pOwnerSid) { FreeADsMem(pOwnerSid); } if (pGroupSid) { FreeADsMem(pGroupSid); } RRETURN(hr); error: if (pRelative) { FreeADsMem(pRelative); } *ppSecurityDescriptor = NULL; *pdwSDLength = 0; goto cleanup; } HRESULT GetOwnerSecurityIdentifier( IADsSecurityDescriptor FAR * pSecDes, PSID * ppSid, PBOOL pfOwnerDefaulted ) { BSTR bstrOwner = NULL; DWORD dwSidSize = 0; HRESULT hr = S_OK; VARIANT_BOOL varBool = VARIANT_FALSE; hr = pSecDes->get_Owner( &bstrOwner ); BAIL_ON_FAILURE(hr); hr = pSecDes->get_OwnerDefaulted( &varBool ); BAIL_ON_FAILURE(hr); if (varBool == VARIANT_FALSE) { if (bstrOwner && *bstrOwner) { hr = ConvertTrusteeToSid( bstrOwner, ppSid, &dwSidSize ); BAIL_ON_FAILURE(hr); *pfOwnerDefaulted = FALSE; }else { *ppSid = NULL; *pfOwnerDefaulted = FALSE; } }else { *ppSid = NULL; dwSidSize = 0; *pfOwnerDefaulted = TRUE; } error: if (bstrOwner) { ADsFreeString(bstrOwner); } RRETURN(hr); } HRESULT GetGroupSecurityIdentifier( IADsSecurityDescriptor FAR * pSecDes, PSID * ppSid, PBOOL pfGroupDefaulted ) { BSTR bstrGroup = NULL; DWORD dwSidSize = 0; HRESULT hr = S_OK; VARIANT_BOOL varBool = VARIANT_FALSE; hr = pSecDes->get_Group( &bstrGroup ); BAIL_ON_FAILURE(hr); hr = pSecDes->get_GroupDefaulted( &varBool ); BAIL_ON_FAILURE(hr); if (varBool == VARIANT_FALSE) { if (bstrGroup && *bstrGroup) { hr = ConvertTrusteeToSid( bstrGroup, ppSid, &dwSidSize ); BAIL_ON_FAILURE(hr); *pfGroupDefaulted = FALSE; }else { *ppSid = NULL; *pfGroupDefaulted = FALSE; } }else { *ppSid = NULL; dwSidSize = 0; *pfGroupDefaulted = TRUE; } error: if (bstrGroup) { ADsFreeString(bstrGroup); } RRETURN(hr); } HRESULT GetDacl( IADsSecurityDescriptor FAR * pSecDes, PACL * ppDacl, PBOOL pfDaclDefaulted ) { IADsAccessControlList FAR * pDiscAcl = NULL; IDispatch FAR * pDispatch = NULL; HRESULT hr = S_OK; VARIANT_BOOL varBool = VARIANT_FALSE; hr = pSecDes->get_DaclDefaulted( &varBool ); BAIL_ON_FAILURE(hr); if (varBool == VARIANT_FALSE) { *pfDaclDefaulted = FALSE; }else { *pfDaclDefaulted = TRUE; } hr = pSecDes->get_DiscretionaryAcl( &pDispatch ); BAIL_ON_FAILURE(hr); if (!pDispatch) { *ppDacl = NULL; goto error; } hr = pDispatch->QueryInterface( IID_IADsAccessControlList, (void **)&pDiscAcl ); BAIL_ON_FAILURE(hr); hr = ConvertAccessControlListToAcl( pDiscAcl, ppDacl ); BAIL_ON_FAILURE(hr); error: if (pDispatch) { pDispatch->Release(); } if (pDiscAcl) { pDiscAcl->Release(); } RRETURN(hr); } HRESULT GetSacl( IADsSecurityDescriptor FAR * pSecDes, PACL * ppSacl, PBOOL pfSaclDefaulted ) { IADsAccessControlList FAR * pSystemAcl = NULL; IDispatch FAR * pDispatch = NULL; HRESULT hr = S_OK; VARIANT_BOOL varBool = VARIANT_FALSE; hr = pSecDes->get_SaclDefaulted( &varBool ); BAIL_ON_FAILURE(hr); if (varBool == VARIANT_FALSE) { *pfSaclDefaulted = FALSE; }else { *pfSaclDefaulted = TRUE; } hr = pSecDes->get_SystemAcl( &pDispatch ); BAIL_ON_FAILURE(hr); if (!pDispatch) { *ppSacl = NULL; goto error; } hr = pDispatch->QueryInterface( IID_IADsAccessControlList, (void **)&pSystemAcl ); BAIL_ON_FAILURE(hr); hr = ConvertAccessControlListToAcl( pSystemAcl, ppSacl ); BAIL_ON_FAILURE(hr); error: if (pDispatch) { pDispatch->Release(); } if (pSystemAcl) { pSystemAcl->Release(); } RRETURN(hr); } HRESULT ConvertAccessControlListToAcl( IADsAccessControlList FAR * pAccessList, PACL * ppAcl ) { IUnknown * pUnknown = NULL; IEnumVARIANT * pEnumerator = NULL; HRESULT hr = S_OK; DWORD i = 0; DWORD cReturned = 0; VARIANT varAce; DWORD dwAceCount = 0; IADsAccessControlEntry FAR * pAccessControlEntry = NULL; LPBYTE pTempAce = NULL; DWORD dwCount = 0; PACL pAcl = NULL; DWORD dwAclSize = 0; PACE_HEADER * ppAceHdr = NULL; DWORD dwRet = 0; BOOL bRet = 0; DWORD dwAclRevision = 0; hr = pAccessList->get_AceCount((long *)&dwAceCount); BAIL_ON_FAILURE(hr); hr = pAccessList->get__NewEnum( &pUnknown ); BAIL_ON_FAILURE(hr); hr = pUnknown->QueryInterface( IID_IEnumVARIANT, (void FAR * FAR *)&pEnumerator ); BAIL_ON_FAILURE(hr); ppAceHdr = (PACE_HEADER *)AllocADsMem(sizeof(PACE_HEADER)*dwAceCount); if (!ppAceHdr) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } for (i = 0; i < dwAceCount; i++) { VariantInit(&varAce); hr = pEnumerator->Next( 1, &varAce, &cReturned ); CONTINUE_ON_FAILURE(hr); hr = (V_DISPATCH(&varAce))->QueryInterface( IID_IADsAccessControlEntry, (void **)&pAccessControlEntry ); CONTINUE_ON_FAILURE(hr); hr = ConvertAccessControlEntryToAce( pAccessControlEntry, &(pTempAce) ); VariantClear(&varAce); if (pAccessControlEntry) { pAccessControlEntry->Release(); pAccessControlEntry = NULL; } if (SUCCEEDED(hr)) { *(ppAceHdr + dwCount) = (PACE_HEADER)pTempAce; dwCount++; } } hr = ComputeTotalAclSize(ppAceHdr, dwCount, &dwAclSize); BAIL_ON_FAILURE(hr); pAcl = (PACL)AllocADsMem(dwAclSize); if (!pAcl) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } #if 0 hr = pAccessList->get_AclRevision((long *)&dwAclRevision); BAIL_ON_FAILURE(hr); #else dwAclRevision = ACL_REVISION; #endif bRet = InitializeAcl( pAcl, dwAclSize, dwAclRevision ); if (!bRet) { dwRet = GetLastError(); hr = HRESULT_FROM_WIN32(dwRet); BAIL_ON_FAILURE(hr); } for (i = 0; i < dwCount; i++) { bRet = AddAce( pAcl, dwAclRevision, i, (LPBYTE)*(ppAceHdr + i), (*(ppAceHdr + i))->AceSize ); if (!bRet) { dwRet = GetLastError(); hr = HRESULT_FROM_WIN32(dwRet); BAIL_ON_FAILURE(hr); } } *ppAcl = pAcl; error: if (ppAceHdr) { for (i = 0; i < dwCount; i++) { if (*(ppAceHdr + i)) { FreeADsMem(*(ppAceHdr + i)); } } FreeADsMem(ppAceHdr); } if (pUnknown) { pUnknown->Release(); } if (pEnumerator) { pEnumerator->Release(); } RRETURN(hr); } HRESULT ConvertAccessControlEntryToAce( IADsAccessControlEntry * pAccessControlEntry, LPBYTE * ppAce ) { DWORD dwAceType = 0; HRESULT hr = S_OK; BSTR bstrTrustee = NULL; PSID pSid = NULL; DWORD dwSidSize = 0; DWORD dwAceFlags = 0; DWORD dwAccessMask = 0; DWORD dwAceSize = 0; LPBYTE pAce = NULL; PACCESS_MASK pAccessMask = NULL; PSID pSidAddress = NULL; PUSHORT pCompoundAceType = NULL; DWORD dwCompoundAceType = 0; PACE_HEADER pAceHeader = NULL; LPBYTE pOffset = NULL; BSTR bstrObjectTypeClsid = NULL; BSTR bstrInheritedObjectTypeClsid = NULL; GUID ObjectTypeGUID; GUID InheritedObjectTypeGUID; PULONG pFlags; DWORD dwFlags = 0; hr = pAccessControlEntry->get_AceType((LONG *)&dwAceType); BAIL_ON_FAILURE(hr); hr = pAccessControlEntry->get_Trustee(&bstrTrustee); BAIL_ON_FAILURE(hr); hr = ConvertTrusteeToSid( bstrTrustee, &pSid, &dwSidSize ); BAIL_ON_FAILURE(hr); hr = pAccessControlEntry->get_AceFlags((long *)&dwAceFlags); BAIL_ON_FAILURE(hr); hr = pAccessControlEntry->get_AccessMask((long *)&dwAccessMask); BAIL_ON_FAILURE(hr); // // we will compensateby adding the entire ACE size // dwAceSize = dwSidSize - sizeof(ULONG); switch (dwAceType) { case ACCESS_ALLOWED_ACE_TYPE: dwAceSize += sizeof(ACCESS_ALLOWED_ACE); pAce = (LPBYTE)AllocADsMem(dwAceSize); if (!pAce) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } pAceHeader = (PACE_HEADER)pAce; pAceHeader->AceType = (UCHAR)dwAceType; pAceHeader->AceFlags = (UCHAR)dwAceFlags; pAceHeader->AceSize = (USHORT)dwAceSize; pAccessMask = (PACCESS_MASK)((LPBYTE)pAceHeader + sizeof(ACE_HEADER)); *pAccessMask = (ACCESS_MASK)dwAccessMask; pSidAddress = (PSID)((LPBYTE)pAccessMask + sizeof(ACCESS_MASK)); memcpy(pSidAddress, pSid, dwSidSize); break; case ACCESS_DENIED_ACE_TYPE: dwAceSize += sizeof(ACCESS_ALLOWED_ACE); pAce = (LPBYTE)AllocADsMem(dwAceSize); if (!pAce) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } pAceHeader = (PACE_HEADER)pAce; pAceHeader->AceType = (UCHAR)dwAceType; pAceHeader->AceFlags = (UCHAR)dwAceFlags; pAceHeader->AceSize = (USHORT)dwAceSize; pAccessMask = (PACCESS_MASK)((LPBYTE)pAceHeader + sizeof(ACE_HEADER)); *pAccessMask = (ACCESS_MASK)dwAccessMask; pSidAddress = (PSID)((LPBYTE)pAccessMask + sizeof(ACCESS_MASK)); memcpy(pSidAddress, pSid, dwSidSize); break; case SYSTEM_AUDIT_ACE_TYPE: dwAceSize += sizeof(ACCESS_ALLOWED_ACE); pAce = (LPBYTE)AllocADsMem(dwAceSize); if (!pAce) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } pAceHeader = (PACE_HEADER)pAce; pAceHeader->AceType = (UCHAR)dwAceType; pAceHeader->AceFlags = (UCHAR)dwAceFlags; pAceHeader->AceSize = (USHORT)dwAceSize; pAccessMask = (PACCESS_MASK)((LPBYTE)pAceHeader + sizeof(ACE_HEADER)); *pAccessMask = (ACCESS_MASK)dwAccessMask; pSidAddress = (PSID)((LPBYTE)pAccessMask + sizeof(ACCESS_MASK)); memcpy(pSidAddress, pSid, dwSidSize); break; case SYSTEM_ALARM_ACE_TYPE: dwAceSize += sizeof(ACCESS_ALLOWED_ACE); pAce = (LPBYTE)AllocADsMem(dwAceSize); if (!pAce) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } pAceHeader = (PACE_HEADER)pAce; pAceHeader->AceType = (UCHAR)dwAceType; pAceHeader->AceFlags = (UCHAR)dwAceFlags; pAceHeader->AceSize = (USHORT)dwAceSize; pAccessMask = (PACCESS_MASK)((LPBYTE)pAceHeader + sizeof(ACE_HEADER)); *pAccessMask = (ACCESS_MASK)dwAccessMask; pSidAddress = (PSID)((LPBYTE)pAccessMask + sizeof(ACCESS_MASK)); memcpy(pSidAddress, pSid, dwSidSize); break; case ACCESS_ALLOWED_COMPOUND_ACE_TYPE: dwAceSize += sizeof(COMPOUND_ACCESS_ALLOWED_ACE); pAce = (LPBYTE)AllocADsMem(dwAceSize); if (!pAce) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } pAceHeader = (PACE_HEADER)pAce; pAceHeader->AceType = (UCHAR)dwAceType; pAceHeader->AceFlags = (UCHAR)dwAceFlags; pAceHeader->AceSize = (USHORT)dwAceSize; pAccessMask = (PACCESS_MASK)((LPBYTE)pAceHeader + sizeof(ACE_HEADER)); *pAccessMask = (ACCESS_MASK)dwAccessMask; pCompoundAceType = (PUSHORT)(pAccessMask + sizeof(ACCESS_MASK)); *pCompoundAceType = (USHORT)dwCompoundAceType; // // Fill in the reserved field here. // pSidAddress = (PSID)((LPBYTE)pCompoundAceType + sizeof(DWORD)); memcpy(pSidAddress, pSid, dwSidSize); break; case ACCESS_ALLOWED_OBJECT_ACE_TYPE: case ACCESS_DENIED_OBJECT_ACE_TYPE: case SYSTEM_AUDIT_OBJECT_ACE_TYPE: case SYSTEM_ALARM_OBJECT_ACE_TYPE: hr = pAccessControlEntry->get_AceFlags((LONG *)&dwAceFlags); BAIL_ON_FAILURE(hr); hr = pAccessControlEntry->get_Flags((LONG *)&dwFlags); BAIL_ON_FAILURE(hr); if (dwFlags & ACE_OBJECT_TYPE_PRESENT) { dwAceSize += sizeof(GUID); } if (dwFlags & ACE_INHERITED_OBJECT_TYPE_PRESENT) { dwAceSize += sizeof(GUID); } hr = pAccessControlEntry->get_ObjectType(&bstrObjectTypeClsid); BAIL_ON_FAILURE(hr); hr = CLSIDFromString(bstrObjectTypeClsid, &ObjectTypeGUID); BAIL_ON_FAILURE(hr); hr = pAccessControlEntry->get_InheritedObjectType(&bstrInheritedObjectTypeClsid); BAIL_ON_FAILURE(hr); hr = CLSIDFromString(bstrInheritedObjectTypeClsid, &InheritedObjectTypeGUID); BAIL_ON_FAILURE(hr); dwAceSize += sizeof(ACCESS_ALLOWED_OBJECT_ACE); pAce = (LPBYTE)AllocADsMem(dwAceSize); if (!pAce) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } pAceHeader = (PACE_HEADER)pAce; pAceHeader->AceType = (UCHAR)dwAceType; pAceHeader->AceFlags = (UCHAR)dwAceFlags; pAceHeader->AceSize = (USHORT)dwAceSize; pAccessMask = (PACCESS_MASK)((LPBYTE)pAceHeader + sizeof(ACE_HEADER)); *pAccessMask = (ACCESS_MASK)dwAccessMask; // // Fill in Flags // pOffset = (LPBYTE)((LPBYTE)pAceHeader + sizeof(ACE_HEADER) + sizeof(ACCESS_MASK)); pFlags = (PULONG)(pOffset); *pFlags = dwFlags; pOffset += sizeof(ULONG); if (dwFlags & ACE_OBJECT_TYPE_PRESENT) { memcpy(pOffset, &ObjectTypeGUID, sizeof(GUID)); pOffset += sizeof(GUID); } if (dwFlags & ACE_INHERITED_OBJECT_TYPE_PRESENT) { memcpy(pOffset, &InheritedObjectTypeGUID, sizeof(GUID)); pOffset += sizeof(GUID); } pSidAddress = (PSID)((LPBYTE)pOffset); memcpy(pSidAddress, pSid, dwSidSize); break; } *ppAce = pAce; error: if (bstrTrustee) { ADsFreeString(bstrTrustee); } if (pSid) { FreeADsMem(pSid); } RRETURN(hr); } HRESULT ComputeTotalAclSize( PACE_HEADER * ppAceHdr, DWORD dwAceCount, PDWORD pdwAclSize ) { DWORD i = 0; PACE_HEADER pAceHdr = NULL; DWORD dwAceSize = 0; DWORD dwAclSize = 0; for (i = 0; i < dwAceCount; i++) { pAceHdr = *(ppAceHdr + i); dwAceSize = pAceHdr->AceSize; dwAclSize += dwAceSize; } dwAclSize += sizeof(ACL); *pdwAclSize = dwAclSize; RRETURN(S_OK); } HRESULT ConvertTrusteeToSid( BSTR bstrTrustee, PSID * ppSid, PDWORD pdwSidSize ) { HRESULT hr = S_OK; BYTE Sid[MAX_PATH]; DWORD dwSidSize = sizeof(Sid); DWORD dwRet = 0; WCHAR szDomainName[MAX_PATH]; DWORD dwDomainSize = sizeof(szDomainName)/sizeof(WCHAR); SID_NAME_USE eUse; LPWSTR pszTrustee = (LPWSTR)bstrTrustee; PSID pSid = NULL; dwSidSize = sizeof(Sid); if ((*pszTrustee == (WCHAR)'\\') || (*pszTrustee == WCHAR('/'))){ pszTrustee++; } dwRet = LookupAccountName( NULL, pszTrustee, Sid, &dwSidSize, szDomainName, &dwDomainSize, (PSID_NAME_USE)&eUse ); if (!dwRet) { BAIL_ON_FAILURE(hr = HRESULT_FROM_WIN32(GetLastError())); } pSid = AllocADsMem(dwSidSize); if (!pSid) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } memcpy(pSid, Sid, dwSidSize); *pdwSidSize = dwSidSize; *ppSid = pSid; error: RRETURN(hr); }
23.191116
92
0.526928
npocmaka
022e8cdc7fd979350a932c73f852b0e1b194b98d
5,516
cpp
C++
modules/fraction-calc-by-using-gcd/test/test_fraction-calc.cpp
gurylev-nikita/devtools-course-practice
bab6ba4e39f04940e27c9ac148505eb152c05d17
[ "CC-BY-4.0" ]
null
null
null
modules/fraction-calc-by-using-gcd/test/test_fraction-calc.cpp
gurylev-nikita/devtools-course-practice
bab6ba4e39f04940e27c9ac148505eb152c05d17
[ "CC-BY-4.0" ]
3
2021-04-22T17:12:19.000Z
2021-05-14T12:16:25.000Z
modules/fraction-calc-by-using-gcd/test/test_fraction-calc.cpp
taktaev-artyom/devtools-course-practice
7cf19defe061c07cfb3ebb71579456e807430a5d
[ "CC-BY-4.0" ]
null
null
null
// Copyright 2021 Yurin Stanislav #include <gtest/gtest.h> #include <tuple> #include "include/fraction.h" typedef testing::TestWithParam<int> Can_create_one_parametres_constructor; TEST_P(Can_create_one_parametres_constructor, can_create_constructor) { int n = GetParam(); Fraction f(n); ASSERT_EQ(n, f.getNumerator()); } INSTANTIATE_TEST_CASE_P(, Can_create_one_parametres_constructor, testing::Values(3, 29) ); typedef testing::TestWithParam<std::tuple<int, int>> Can_create_two_parametres_constructor; TEST_P(Can_create_two_parametres_constructor, can_create_constructor) { int n = std::get<0>(GetParam()); int d = std::get<1>(GetParam()); Fraction f(n, d); ASSERT_EQ(d, f.getDenominator()); } INSTANTIATE_TEST_CASE_P(, Can_create_two_parametres_constructor, testing::Values(std::make_tuple(2, 3), std::make_tuple(43, 99)) ); TEST(Fraction, throws_on_zero_denominator) { ASSERT_ANY_THROW(Fraction f(29, 0)); } TEST(Fraction, default_fraction_creating) { Fraction f; ASSERT_EQ(0, f.getNumerator()); ASSERT_EQ(1, f.getDenominator()); } TEST(Fraction, fraction_with_negative_parametres_becomes_positive) { Fraction f(-1, -2); ASSERT_EQ(1, f.getNumerator()); ASSERT_EQ(2, f.getDenominator()); } TEST(Fraction, moves_minus_to_numerator) { Fraction f(1, -2); ASSERT_EQ(-1, f.getNumerator()); ASSERT_EQ(2, f.getDenominator()); } typedef testing::TestWithParam<std::tuple<int, int, int, int>> Reduction_par; TEST_P(Reduction_par, reduction) { int n = std::get<0>(GetParam()); int d = std::get<1>(GetParam()); Fraction f(n, d); ASSERT_EQ(std::get<2>(GetParam()), f.getNumerator()); ASSERT_EQ(std::get<3>(GetParam()), f.getDenominator()); } INSTANTIATE_TEST_CASE_P(, Reduction_par, testing::Values(std::make_tuple(3, 6, 1, 2), std::make_tuple(8, -32, -1, 4)) ); typedef testing::TestWithParam<std::tuple<int, int, int>> gcd_par; TEST_P(gcd_par, ) { Fraction f; ASSERT_EQ(std::get<0>(GetParam()), f.gcd(std::get<1>(GetParam()), std::get<2>(GetParam()))); } INSTANTIATE_TEST_CASE_P(, gcd_par, testing::Values(std::make_tuple(3, 3, 6), std::make_tuple(6, 18, 30)) ); TEST(Fraction, gcd_negative_parameter) { Fraction f; ASSERT_ANY_THROW(f.gcd(-18, 30)); } typedef testing::TestWithParam<std::tuple<int, int, int>> lcm_par; TEST_P(lcm_par, ) { Fraction f; ASSERT_EQ(std::get<0>(GetParam()), f.lcm(std::get<1>(GetParam()), std::get<2>(GetParam()))); } INSTANTIATE_TEST_CASE_P(, lcm_par, testing::Values(std::make_tuple(36, 12, 18), std::make_tuple(15, 15, 3)) ); TEST(Fraction, lcm_negative_parameter) { Fraction f; ASSERT_ANY_THROW(f.lcm(-12, 18)); } TEST(Fraction, can_self_appropriation) { Fraction f(2, 3); f = f; ASSERT_EQ(2, f.getNumerator()); ASSERT_EQ(3, f.getDenominator()); } TEST(Fraction, comparison_operator_overloading) { Fraction f1(2, 3); Fraction f2; f2 = f1; ASSERT_EQ(2, f2.getNumerator()); ASSERT_EQ(3, f2.getDenominator()); } typedef testing::TestWithParam<std::tuple<int, int, int, int, int, int>> plus_par; TEST_P(plus_par, ) { Fraction f1(std::get<0>(GetParam()), std::get<1>(GetParam())); Fraction f2(std::get<2>(GetParam()), std::get<3>(GetParam())); Fraction f3; f3 = f1 + f2; ASSERT_EQ(std::get<4>(GetParam()), f3.getNumerator()); ASSERT_EQ(std::get<5>(GetParam()), f3.getDenominator()); } INSTANTIATE_TEST_CASE_P(, plus_par, testing::Values(std::make_tuple(2, 3, 3, 4, 17, 12), std::make_tuple(-3, 5, 4, 7, -1, 35)) ); typedef testing::TestWithParam<std::tuple<int, int, int, int, int, int>> minus_par; TEST_P(minus_par, ) { Fraction f1(std::get<0>(GetParam()), std::get<1>(GetParam())); Fraction f2(std::get<2>(GetParam()), std::get<3>(GetParam())); Fraction f3; f3 = f1 - f2; ASSERT_EQ(std::get<4>(GetParam()), f3.getNumerator()); ASSERT_EQ(std::get<5>(GetParam()), f3.getDenominator()); } INSTANTIATE_TEST_CASE_P(, minus_par, testing::Values(std::make_tuple(2, 5, 4, 3, -14, 15), std::make_tuple(3, 8, 11, -5, 103, 40)) ); typedef testing::TestWithParam<std::tuple<int, int, int, int, int, int>> multi_par; TEST_P(multi_par, ) { Fraction f1(std::get<0>(GetParam()), std::get<1>(GetParam())); Fraction f2(std::get<2>(GetParam()), std::get<3>(GetParam())); Fraction f3; f3 = f1 * f2; ASSERT_EQ(std::get<4>(GetParam()), f3.getNumerator()); ASSERT_EQ(std::get<5>(GetParam()), f3.getDenominator()); } INSTANTIATE_TEST_CASE_P(, multi_par, testing::Values(std::make_tuple(3, 2, 8, 11, 12, 11), std::make_tuple(7, -4, -9, 3, 21, 4)) ); typedef testing::TestWithParam<std::tuple<int, int, int, int, int, int>> dev_par; TEST_P(dev_par, ) { Fraction f1(std::get<0>(GetParam()), std::get<1>(GetParam())); Fraction f2(std::get<2>(GetParam()), std::get<3>(GetParam())); Fraction f3; f3 = f1 / f2; ASSERT_EQ(std::get<4>(GetParam()), f3.getNumerator()); ASSERT_EQ(std::get<5>(GetParam()), f3.getDenominator()); } INSTANTIATE_TEST_CASE_P(, dev_par, testing::Values(std::make_tuple(13, 11, 4, 5, 65, 44), std::make_tuple(14, -6, -15, -2, -14, 45)) );
24.959276
72
0.624184
gurylev-nikita
02302931af860c17425a037e76f15ed0e75bbcf7
19,549
cc
C++
common/system/dvfs_manager.cc
NoCModellingLab/Graphite
1b4bb98f5bfb96ca394b71e7ef3e9e500a1e3997
[ "MIT" ]
94
2015-02-21T09:44:03.000Z
2022-03-13T03:06:19.000Z
common/system/dvfs_manager.cc
NoCModellingLab/Graphite
1b4bb98f5bfb96ca394b71e7ef3e9e500a1e3997
[ "MIT" ]
null
null
null
common/system/dvfs_manager.cc
NoCModellingLab/Graphite
1b4bb98f5bfb96ca394b71e7ef3e9e500a1e3997
[ "MIT" ]
36
2015-01-09T16:48:18.000Z
2022-03-13T03:06:21.000Z
#include <string.h> #include <utility> #include <iostream> using std::make_pair; #include "dvfs_manager.h" #include "memory_manager.h" #include "simulator.h" #include "tile.h" #include "core.h" #include "network_model.h" #include "core_model.h" #include "packetize.h" #include "utils.h" #include "tile_energy_monitor.h" DVFSManager::DVFSLevels DVFSManager::_dvfs_levels; double DVFSManager::_max_frequency; DVFSManager::DomainType DVFSManager::_dvfs_domain_map; UInt32 DVFSManager::_synchronization_delay_cycles; DVFSManager::DVFSManager(UInt32 technology_node, Tile* tile): _tile(tile) { // register callbacks _tile->getNetwork()->registerCallback(DVFS_SET_REQUEST, setDVFSCallback, this); _tile->getNetwork()->registerCallback(DVFS_GET_REQUEST, getDVFSCallback, this); _tile->getNetwork()->registerCallback(GET_TILE_ENERGY_REQUEST, getTileEnergyCallback, this); } DVFSManager::~DVFSManager() { // unregister callback _tile->getNetwork()->unregisterCallback(DVFS_SET_REQUEST); _tile->getNetwork()->unregisterCallback(DVFS_GET_REQUEST); _tile->getNetwork()->unregisterCallback(GET_TILE_ENERGY_REQUEST); } // Called from common/user/dvfs int DVFSManager::getDVFS(tile_id_t tile_id, module_t module_mask, double* frequency, double* voltage) { // Invalid tile id error if (tile_id < 0 || (unsigned int) tile_id >= Config::getSingleton()->getApplicationTiles()) { return -1; } // Invalid domain error bool valid_domain = false; for (DomainType::iterator it = _dvfs_domain_map.begin(); it != _dvfs_domain_map.end(); it++){ if (module_mask == it->second.first){ valid_domain = true; break; } } if (!valid_domain) return -2; // send request UnstructuredBuffer send_buffer; send_buffer << module_mask; core_id_t remote_core_id = {tile_id, MAIN_CORE_TYPE}; _tile->getNetwork()->netSend(remote_core_id, DVFS_GET_REQUEST, send_buffer.getBuffer(), send_buffer.size()); // receive reply core_id_t this_core_id = {_tile->getId(), MAIN_CORE_TYPE}; NetPacket packet = _tile->getNetwork()->netRecv(remote_core_id, this_core_id, DVFS_GET_REPLY); UnstructuredBuffer recv_buffer; recv_buffer << std::make_pair(packet.data, packet.length); int rc; recv_buffer >> rc; recv_buffer >> *frequency; recv_buffer >> *voltage; return rc; } int DVFSManager::setDVFS(tile_id_t tile_id, int module_mask, double frequency, voltage_option_t voltage_flag) { // Invalid tile error if (tile_id < 0 || (unsigned int) tile_id >= Config::getSingleton()->getApplicationTiles()) return -1; // Invalid domain error bool valid_domain = false; for (DomainType::iterator it = _dvfs_domain_map.begin(); it != _dvfs_domain_map.end(); it++){ if (module_mask == it->second.first){ valid_domain = true; break; } } if (!valid_domain) return -2; // Get current time Time curr_time = _tile->getCore()->getModel()->getCurrTime(); // send request UnstructuredBuffer send_buffer; send_buffer << module_mask << frequency << voltage_flag << curr_time; core_id_t remote_core_id = {tile_id, MAIN_CORE_TYPE}; _tile->getNetwork()->netSend(remote_core_id, DVFS_SET_REQUEST, send_buffer.getBuffer(), send_buffer.size()); // receive reply core_id_t this_core_id = {_tile->getId(), MAIN_CORE_TYPE}; NetPacket packet = _tile->getNetwork()->netRecv(remote_core_id, this_core_id, DVFS_SET_REPLY); UnstructuredBuffer recv_buffer; recv_buffer << std::make_pair(packet.data, packet.length); int rc; recv_buffer >> rc; return rc; } void DVFSManager::doGetDVFS(module_t module_mask, core_id_t requester) { double frequency, voltage; int rc = 0; if (module_mask & CORE){ rc = _tile->getCore()->getDVFS(frequency, voltage); } else if (module_mask & L1_ICACHE){ rc = _tile->getMemoryManager()->getDVFS(L1_ICACHE, frequency, voltage); } else if (module_mask & L1_DCACHE){ rc = _tile->getMemoryManager()->getDVFS(L1_DCACHE, frequency, voltage); } else if (module_mask & L2_CACHE){ rc = _tile->getMemoryManager()->getDVFS(L2_CACHE, frequency, voltage); } else if (module_mask & DIRECTORY){ rc = _tile->getMemoryManager()->getDVFS(DIRECTORY, frequency, voltage); } else if (module_mask & NETWORK_USER){ NetworkModel* user_network_model = _tile->getNetwork()->getNetworkModelFromPacketType(USER); rc = user_network_model->getDVFS(frequency, voltage); } else if (module_mask & NETWORK_MEMORY){ NetworkModel* mem_network_model = _tile->getNetwork()->getNetworkModelFromPacketType(SHARED_MEM); rc = mem_network_model->getDVFS(frequency, voltage); } else{ rc = -2; } UnstructuredBuffer send_buffer; send_buffer << rc << frequency << voltage; _tile->getNetwork()->netSend(requester, DVFS_GET_REPLY, send_buffer.getBuffer(), send_buffer.size()); } void DVFSManager::doSetDVFS(int module_mask, double frequency, voltage_option_t voltage_flag, const Time& curr_time, core_id_t requester) { int rc = 0, rc_tmp = 0; // Invalid voltage option if (voltage_flag != HOLD && voltage_flag != AUTO){ rc = -3; } // Invalid frequency else if (frequency <= 0 || frequency > _max_frequency){ rc = -4; } // Parse mask and set frequency and voltage else{ if (module_mask & CORE){ rc_tmp = _tile->getCore()->setDVFS(frequency, voltage_flag, curr_time); if (rc_tmp != 0) rc = rc_tmp; } if (module_mask & L1_ICACHE){ rc_tmp = _tile->getMemoryManager()->setDVFS(L1_ICACHE, frequency, voltage_flag, curr_time); if (rc_tmp != 0) rc = rc_tmp; } if (module_mask & L1_DCACHE){ rc_tmp = _tile->getMemoryManager()->setDVFS(L1_DCACHE, frequency, voltage_flag, curr_time); if (rc_tmp != 0) rc = rc_tmp; } if (module_mask & L2_CACHE){ rc_tmp = _tile->getMemoryManager()->setDVFS(L2_CACHE, frequency, voltage_flag, curr_time); if (rc_tmp != 0) rc = rc_tmp; } if ((MemoryManager::getCachingProtocolType() != PR_L1_SH_L2_MSI && MemoryManager::getCachingProtocolType() != PR_L1_SH_L2_MESI) && (module_mask & DIRECTORY)){ rc_tmp = _tile->getMemoryManager()->setDVFS(DIRECTORY, frequency, voltage_flag, curr_time); if (rc_tmp != 0 && module_mask != TILE) rc = rc_tmp; } if (module_mask & NETWORK_USER){ NetworkModel* user_network_model = _tile->getNetwork()->getNetworkModelFromPacketType(USER); rc_tmp = user_network_model->setDVFS(frequency, voltage_flag, curr_time); if (rc_tmp != 0) rc = rc_tmp; } if (module_mask & NETWORK_MEMORY){ NetworkModel* mem_network_model = _tile->getNetwork()->getNetworkModelFromPacketType(SHARED_MEM); rc_tmp = mem_network_model->setDVFS(frequency, voltage_flag, curr_time); if (rc_tmp != 0) rc = rc_tmp; } } UnstructuredBuffer send_buffer; send_buffer << rc; _tile->getNetwork()->netSend(requester, DVFS_SET_REPLY, send_buffer.getBuffer(), send_buffer.size()); } // Called over the network (callbacks) void getDVFSCallback(void* obj, NetPacket packet) { UnstructuredBuffer recv_buffer; recv_buffer << std::make_pair(packet.data, packet.length); module_t module_type; recv_buffer >> module_type; DVFSManager* dvfs_manager = (DVFSManager* ) obj; dvfs_manager->doGetDVFS(module_type, packet.sender); } void setDVFSCallback(void* obj, NetPacket packet) { UnstructuredBuffer recv_buffer; recv_buffer << std::make_pair(packet.data, packet.length); int module_mask; double frequency; voltage_option_t voltage_flag; Time curr_time; recv_buffer >> module_mask; recv_buffer >> frequency; recv_buffer >> voltage_flag; recv_buffer >> curr_time; DVFSManager* dvfs_manager = (DVFSManager* ) obj; dvfs_manager->doSetDVFS(module_mask, frequency, voltage_flag, curr_time, packet.sender); } // Called to initialize DVFS void DVFSManager::initializeDVFS() { DVFSManager::initializeDVFSLevels(); DVFSManager::initializeDVFSDomainMap(); _synchronization_delay_cycles = Sim()->getCfg()->getInt("dvfs/synchronization_delay"); } // Called to initialize DVFS Levels void DVFSManager::initializeDVFSLevels() { UInt32 technology_node = 0; try { technology_node = Sim()->getCfg()->getInt("general/technology_node"); _max_frequency = Sim()->getCfg()->getFloat("general/max_frequency"); } catch (...) { LOG_PRINT_ERROR("Could not either read [general/technology_node] or [general/max_frequency] from the cfg file"); } string input_filename = Sim()->getGraphiteHome() + "/technology/dvfs_levels_" + convertToString<UInt32>(technology_node) + "nm.cfg"; ifstream input_file(input_filename.c_str()); while (1) { char line_c[1024]; input_file.getline(line_c, 1024); string line(line_c); if (input_file.gcount() == 0) break; line = trimSpaces(line); if (line == "") continue; if (line[0] == '#') // Comment continue; vector<string> tokens; splitIntoTokens(line, tokens, " "); double voltage = convertFromString<double>(tokens[0]); double frequency_factor = convertFromString<double>(tokens[1]); _dvfs_levels.push_back(make_pair(voltage, frequency_factor * _max_frequency)); } } // Called to initialize DVFS domain map void DVFSManager::initializeDVFSDomainMap() { _dvfs_domain_map[INVALID_MODULE] = pair<module_t, double>(INVALID_MODULE, _max_frequency); string dvfs_domains_list_str; try { dvfs_domains_list_str = Sim()->getCfg()->getString("dvfs/domains"); } catch(...) { fprintf(stderr, "ERROR: Could not read [dvfs/domains] from the cfg file\n"); exit(EXIT_FAILURE); } vector<string> dvfs_domains_list_vec; parseList(dvfs_domains_list_str, dvfs_domains_list_vec, "<>"); // parse each domain for (vector<string>::iterator list_it = dvfs_domains_list_vec.begin(); list_it != dvfs_domains_list_vec.end(); list_it++) { vector<string> dvfs_parameter_tuple; parseList(*list_it, dvfs_parameter_tuple, ","); SInt32 param_num = 0; double frequency = 0; module_t domain_mask = INVALID_MODULE; vector<module_t> domain_modules; vector<string> domain_modules_str; for (vector<string>::iterator param_it = dvfs_parameter_tuple.begin(); param_it != dvfs_parameter_tuple.end(); param_it ++) { if (param_num == 0){ frequency = convertFromString<double>(*param_it); if (frequency <= 0) { fprintf(stderr, "Error: Invalid frequency(%g GHz), must be greater than zero\n", frequency); exit(EXIT_FAILURE); } } else{ // create domain mask string module = trimSpaces(*param_it); domain_modules_str.push_back(module); if (module == "CORE"){ domain_mask = (module_t) (domain_mask | CORE); domain_modules.push_back(CORE); } else if (module == "L1_ICACHE"){ domain_mask = (module_t) (domain_mask | L1_ICACHE); domain_modules.push_back(L1_ICACHE); } else if (module == "L1_DCACHE"){ domain_mask = (module_t) (domain_mask | L1_DCACHE); domain_modules.push_back(L1_DCACHE); } else if (module == "L2_CACHE"){ domain_mask = (module_t) (domain_mask | L2_CACHE); domain_modules.push_back(L2_CACHE); } else if (module == "DIRECTORY"){ domain_mask = (module_t) (domain_mask | DIRECTORY); domain_modules.push_back(DIRECTORY); } else if (module == "NETWORK_USER"){ domain_mask = (module_t) (domain_mask | NETWORK_USER); domain_modules.push_back(NETWORK_USER); } else if (module == "NETWORK_MEMORY"){ domain_mask = (module_t) (domain_mask | NETWORK_MEMORY); domain_modules.push_back(NETWORK_MEMORY); } else{ fprintf(stderr, "Unrecognized DVFS module (%s)\n", module.c_str()); exit(EXIT_FAILURE); } } param_num ++; } pair<module_t,double> domain_value(domain_mask, frequency); for (unsigned int i=0; i<domain_modules.size(); i++){ LOG_ASSERT_ERROR(_dvfs_domain_map.find(domain_modules[i]) == _dvfs_domain_map.end(), "DVFS module (%s) can only be listed once", domain_modules_str[i].c_str()); _dvfs_domain_map[domain_modules[i]] = domain_value; } } // check if all modules are listed LOG_ASSERT_ERROR(_dvfs_domain_map.find(CORE) != _dvfs_domain_map.end(),"DVFS module CORE must be listed in a DVFS domain"); LOG_ASSERT_ERROR(_dvfs_domain_map.find(L1_ICACHE) != _dvfs_domain_map.end(),"DVFS module L1_ICACHE must be listed in a DVFS domain"); LOG_ASSERT_ERROR(_dvfs_domain_map.find(L1_DCACHE) != _dvfs_domain_map.end(),"DVFS module L1_DCACHE must be listed in a DVFS domain"); LOG_ASSERT_ERROR(_dvfs_domain_map.find(L2_CACHE) != _dvfs_domain_map.end(),"DVFS module L2_CACHE must be listed in a DVFS domain"); LOG_ASSERT_ERROR(_dvfs_domain_map.find(DIRECTORY) != _dvfs_domain_map.end(),"DVFS module DIRECTORY must be listed in a DVFS domain"); LOG_ASSERT_ERROR(_dvfs_domain_map.find(NETWORK_USER) != _dvfs_domain_map.end(),"DVFS module NETWORK_USER must be listed in a DVFS domain"); LOG_ASSERT_ERROR(_dvfs_domain_map.find(NETWORK_MEMORY) != _dvfs_domain_map.end(),"DVFS module NETWORK_MEMORY must be listed in a DVFS domain"); } UInt32 DVFSManager::getSynchronizationDelay() { return _synchronization_delay_cycles; } int DVFSManager::getVoltage(double &voltage, voltage_option_t voltage_flag, double frequency) { int rc = 0; switch (voltage_flag) { case HOLD: // above max frequency for current voltage if (voltage < getMinVoltage(frequency)){ rc = -5; } break; case AUTO: voltage = getMinVoltage(frequency); break; default: LOG_PRINT_ERROR("Unrecognized voltage flag %i.", voltage_flag); break; } return rc; } int DVFSManager::getInitialFrequencyAndVoltage(module_t module, double &frequency, double &voltage) { frequency = _dvfs_domain_map[module].second; int rc = DVFSManager::getVoltage(voltage, AUTO, frequency); return rc; } void DVFSManager::getTileEnergy(tile_id_t tile_id, double *energy) { // send request UnstructuredBuffer send_buffer; core_id_t remote_core_id = {tile_id, MAIN_CORE_TYPE}; _tile->getNetwork()->netSend(remote_core_id, GET_TILE_ENERGY_REQUEST, send_buffer.getBuffer(), send_buffer.size()); // receive reply core_id_t this_core_id = {_tile->getId(), MAIN_CORE_TYPE}; NetPacket packet = _tile->getNetwork()->netRecv(remote_core_id, this_core_id, GET_TILE_ENERGY_REPLY); UnstructuredBuffer recv_buffer; recv_buffer << std::make_pair(packet.data, packet.length); recv_buffer >> *energy; } void DVFSManager::doGetTileEnergy(core_id_t requester) { double energy = _tile->getTileEnergyMonitor()->getTileEnergy(); UnstructuredBuffer send_buffer; send_buffer << energy; _tile->getNetwork()->netSend(requester, GET_TILE_ENERGY_REPLY, send_buffer.getBuffer(), send_buffer.size()); } void getTileEnergyCallback(void* obj, NetPacket packet) { DVFSManager* dvfs_manager = (DVFSManager* ) obj; dvfs_manager->doGetTileEnergy(packet.sender); } const DVFSManager::DVFSLevels& DVFSManager::getDVFSLevels() { return _dvfs_levels; } module_t DVFSManager::getDVFSDomain(module_t module_type) { LOG_ASSERT_ERROR(_dvfs_domain_map.find(module_type) != _dvfs_domain_map.end(), "Cannot get DVFS domain: Invalid module(%d).", module_type); return _dvfs_domain_map[module_type].first; } double DVFSManager::getMaxFrequency(double voltage) { for (DVFSLevels::const_iterator it = _dvfs_levels.begin(); it != _dvfs_levels.end(); it++) { if (voltage == (*it).first) return (*it).second; } LOG_PRINT_ERROR("Could not find voltage(%g V) in DVFS Levels list", voltage); return 0.0; } bool DVFSManager::hasSameDVFSDomain(module_t module1, module_t module2) { return _dvfs_domain_map[module1].first == _dvfs_domain_map[module2].first; } module_t DVFSManager::convertToModule(MemComponent::Type component){ switch(component){ case MemComponent::L1_ICACHE: return L1_ICACHE; case MemComponent::L1_DCACHE: return L1_DCACHE; case MemComponent::L2_CACHE: return L2_CACHE; case MemComponent::DRAM_DIRECTORY: return DIRECTORY; default: LOG_PRINT_ERROR("Unknown memory component."); break; } return INVALID_MODULE; } void DVFSManager::printAsynchronousMap(ostream& os, module_t module, AsynchronousMap &asynchronous_map) { if (asynchronous_map.empty()) return; AsynchronousMap::iterator it; for (it = asynchronous_map.begin(); it != asynchronous_map.end(); it++){ if (it->second.getTime() != 0) break; } if (it == asynchronous_map.end()) return; string padding(" "); if (module == CORE) padding = ""; os << padding + " Asynchronous communication: " << endl; if (asynchronous_map.find(CORE) != asynchronous_map.end() && !hasSameDVFSDomain(module, CORE)) os << padding + " Core (in nanoseconds): " << asynchronous_map[CORE].toNanosec() << endl; if (asynchronous_map.find(L1_ICACHE) != asynchronous_map.end() && !hasSameDVFSDomain(module, L1_ICACHE)) os << padding + " L1-I Cache (in nanoseconds): " << asynchronous_map[L1_ICACHE].toNanosec() << endl; if (asynchronous_map.find(L1_DCACHE) != asynchronous_map.end() && !hasSameDVFSDomain(module, L1_DCACHE)) os << padding + " L1-D Cache (in nanoseconds): " << asynchronous_map[L1_DCACHE].toNanosec() << endl; if (asynchronous_map.find(L2_CACHE) != asynchronous_map.end() && !hasSameDVFSDomain(module, L2_CACHE)) os << padding + " L2 Cache (in nanoseconds): " << asynchronous_map[L2_CACHE].toNanosec() << endl; if (asynchronous_map.find(DIRECTORY) != asynchronous_map.end() && !hasSameDVFSDomain(module, DIRECTORY)) os << padding + " Directory (in nanoseconds): " << asynchronous_map[DIRECTORY].toNanosec() << endl; if (asynchronous_map.find(NETWORK_USER) != asynchronous_map.end() && !hasSameDVFSDomain(module, NETWORK_USER)) os << padding + " User Nework (in nanoseconds): " << asynchronous_map[NETWORK_USER].toNanosec() << endl; if (asynchronous_map.find(NETWORK_MEMORY) != asynchronous_map.end() && !hasSameDVFSDomain(module, NETWORK_MEMORY)) os << padding + " Memory Nework (in nanoseconds): " << asynchronous_map[NETWORK_MEMORY].toNanosec() << endl; } double DVFSManager::getMinVoltage(double frequency) { for (DVFSLevels::const_reverse_iterator it = _dvfs_levels.rbegin(); it != _dvfs_levels.rend(); it++) { if (frequency <= (*it).second) return (*it).first; } LOG_PRINT_ERROR("Could not determine voltage for frequency(%g GHz)", frequency); return 0.0; }
34.057491
164
0.674459
NoCModellingLab
0232802607ad516a0c835f7e054b1575e1853625
2,026
cpp
C++
aws-cpp-sdk-comprehendmedical/source/ComprehendMedicalErrors.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-comprehendmedical/source/ComprehendMedicalErrors.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-comprehendmedical/source/ComprehendMedicalErrors.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-02-28T21:36:42.000Z
2022-02-28T21:36:42.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/core/client/AWSError.h> #include <aws/core/utils/HashingUtils.h> #include <aws/comprehendmedical/ComprehendMedicalErrors.h> using namespace Aws::Client; using namespace Aws::Utils; using namespace Aws::ComprehendMedical; namespace Aws { namespace ComprehendMedical { namespace ComprehendMedicalErrorMapper { static const int INTERNAL_SERVER_HASH = HashingUtils::HashString("InternalServerException"); static const int INVALID_ENCODING_HASH = HashingUtils::HashString("InvalidEncodingException"); static const int TOO_MANY_REQUESTS_HASH = HashingUtils::HashString("TooManyRequestsException"); static const int TEXT_SIZE_LIMIT_EXCEEDED_HASH = HashingUtils::HashString("TextSizeLimitExceededException"); static const int INVALID_REQUEST_HASH = HashingUtils::HashString("InvalidRequestException"); AWSError<CoreErrors> GetErrorForName(const char* errorName) { int hashCode = HashingUtils::HashString(errorName); if (hashCode == INTERNAL_SERVER_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(ComprehendMedicalErrors::INTERNAL_SERVER), false); } else if (hashCode == INVALID_ENCODING_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(ComprehendMedicalErrors::INVALID_ENCODING), false); } else if (hashCode == TOO_MANY_REQUESTS_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(ComprehendMedicalErrors::TOO_MANY_REQUESTS), true); } else if (hashCode == TEXT_SIZE_LIMIT_EXCEEDED_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(ComprehendMedicalErrors::TEXT_SIZE_LIMIT_EXCEEDED), false); } else if (hashCode == INVALID_REQUEST_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(ComprehendMedicalErrors::INVALID_REQUEST), false); } return AWSError<CoreErrors>(CoreErrors::UNKNOWN, false); } } // namespace ComprehendMedicalErrorMapper } // namespace ComprehendMedical } // namespace Aws
34.931034
115
0.793189
Neusoft-Technology-Solutions
0232eeb510200469751013099396a3adc5fc492f
3,196
cpp
C++
Tap_The_Rainbow/traitement_images.cpp
arnaudricaud/Tap_The_Rainbow
0250783e9ddced9e21560e7ebd201206dc4cd2f7
[ "MIT" ]
null
null
null
Tap_The_Rainbow/traitement_images.cpp
arnaudricaud/Tap_The_Rainbow
0250783e9ddced9e21560e7ebd201206dc4cd2f7
[ "MIT" ]
8
2017-04-04T12:32:17.000Z
2017-06-06T15:11:55.000Z
Tap_The_Rainbow/traitement_images.cpp
arnaudricaud/Tap_The_Rainbow
0250783e9ddced9e21560e7ebd201206dc4cd2f7
[ "MIT" ]
null
null
null
#include "traitement_images.h" #include <QElapsedTimer> Traitement_images::Traitement_images() { } void Traitement_images::reconstruction(Mat calibration, Mat capture){ //DEBUT Mat origine = calibration.clone(); Mat frame = capture.clone(); //MATRICE SOUSTRACTION ET NIVEAU DE GRIS Mat soustraction; Mat imgNDG; //ELEMENT STRUCTURANT Mat kernel1 = getStructuringElement(MORPH_ELLIPSE,Size(1,1)); //detection de contour cvtColor(origine,imgNDG,CV_RGB2GRAY); Canny(imgNDG,imgNDG,100,100); morphologyEx(imgNDG,imgNDG,MORPH_DILATE,kernel1); //Dilatation floodFill(imgNDG,cv::Point(50,10),Scalar(255)); //Remplissage bitwise_not(imgNDG,imgNDG); //Complémentaire // Récupération des RONDS uniquement! (Evite légèrement le pb des ombres) for (int i=0;i<imgNDG.cols;i++){ for (int j=0;j<imgNDG.rows;j++){ if((int)imgNDG.at<uchar>(j,i)==0){ origine.at<Vec3b>(j,i)[0]=0; origine.at<Vec3b>(j,i)[1]=0; origine.at<Vec3b>(j,i)[2]=0; } } } // soustraction soustraction=origine-frame; //SOUSTRACTION => Doigt sur les ronds // binarisation cvtColor(soustraction,soustraction,CV_RGB2GRAY); threshold(soustraction,soustraction,35,255,CV_THRESH_BINARY); //35 //PREND 66ms // detection de couleur et son detectCouleur(origine, soustraction); } void Traitement_images::detectCouleur(Mat image, Mat mask){ //DEBUT TIMER float compteur=0; float valeur=0; float moyenne=0; cvtColor(image,image,CV_BGR2HSV); for (int i=0;i<mask.cols;i++){ for (int j=0;j<mask.rows;j++){ if((int)mask.at<uchar>(j,i)!=0){ compteur++; valeur=valeur+image.at<Vec3b>(j,i)[0];//Valeurs autours de 50/60 } } } //PREND 24 ms //DEBUT TIMER // determination de la couleur moyenne=valeur/compteur; //imshow("resultat finale",image); //QElapsedTimer timer; //timer.start(); float teinte=0; teinte=moyenne*360/180; if (compteur>1000){ if(teinte>15 && teinte<45){ qDebug()<<"orange"; }else if(teinte>=45 && teinte<75){ qDebug()<<"jaune"; note.playNote(2); }else if(teinte>=75 && teinte<105){ qDebug()<<"jaune-vert"; }else if(teinte>=105 && teinte<135){ qDebug()<<"vert"; note.playNote(4); }else if(teinte>=135 && teinte<165){ qDebug()<<"bleu-vert"; }else if(teinte>=165 && teinte<195){ qDebug()<<"cyan"; }else if(teinte>=195 && teinte<225){ qDebug()<<"bleu moyen"; note.playNote(1); }else if(teinte>=225 && teinte<255){ qDebug()<<"bleu "; }else if(teinte>=255 && teinte<285){ qDebug()<<"violet"; }else if(teinte>=285 && teinte<315){ qDebug()<<"magenta"; note.playNote(5); }else if(teinte>=315 && teinte<345){ qDebug()<<"rose"; }else{ qDebug()<<"rouge"; note.playNote(3); } } //PRENDS 13 ms }
27.791304
80
0.566333
arnaudricaud
023c8262be32991debf319bf51b6071b9b1d9457
98,660
cpp
C++
admin/activec/designer/vb98ctls/mssnapd/mssnapd/pstoolbr.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/activec/designer/vb98ctls/mssnapd/mssnapd/pstoolbr.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/activec/designer/vb98ctls/mssnapd/mssnapd/pstoolbr.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//=-------------------------------------------------------------------------------------- // pstoolbr.cpp //=-------------------------------------------------------------------------------------- // // Copyright (c) 1999, Microsoft Corporation. // All Rights Reserved. // // Information Contained Herein Is Proprietary and Confidential. // //=------------------------------------------------------------------------------------= // // URL View Property Sheet implementation //=-------------------------------------------------------------------------------------= #include "pch.h" #include "common.h" #include "pstoolbr.h" // for ASSERT and FAIL // SZTHISFILE //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// // // Toolbar Property Page General // //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// //=-------------------------------------------------------------------------------------- // IUnknown *CToolbarGeneralPage::Create(IUnknown *pUnkOuter) //=-------------------------------------------------------------------------------------- // // Notes // IUnknown *CToolbarGeneralPage::Create(IUnknown *pUnkOuter) { CToolbarGeneralPage *pNew = New CToolbarGeneralPage(pUnkOuter); return pNew->PrivateUnknown(); } //=-------------------------------------------------------------------------------------- // CToolbarGeneralPage::CToolbarGeneralPage(IUnknown *pUnkOuter) //=-------------------------------------------------------------------------------------- // // Notes // CToolbarGeneralPage::CToolbarGeneralPage ( IUnknown *pUnkOuter ) : CSIPropertyPage(pUnkOuter, OBJECT_TYPE_PPGTOOLBRGENERAL), m_piMMCToolbar(0), m_piSnapInDesignerDef(0) { } //=-------------------------------------------------------------------------------------- // CToolbarGeneralPage::~CToolbarGeneralPage() //=-------------------------------------------------------------------------------------- // // Notes // CToolbarGeneralPage::~CToolbarGeneralPage() { RELEASE(m_piMMCToolbar); RELEASE(m_piSnapInDesignerDef); } //=-------------------------------------------------------------------------------------- // CToolbarGeneralPage::OnInitializeDialog() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarGeneralPage::OnInitializeDialog() { HRESULT hr = S_OK; hr = RegisterTooltip(IDC_COMBO_TB_ILS, IDS_TT_TB_IMAGE_LIST); IfFailGo(hr); hr = RegisterTooltip(IDC_EDIT_TB_TAG, IDS_TT_TB_TAG); IfFailGo(hr); Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarGeneralPage::OnNewObjects() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarGeneralPage::OnNewObjects() { HRESULT hr = S_OK; IUnknown *pUnk = NULL; DWORD dwDummy = 0; IObjectModel *piObjectModel = NULL; VARIANT vtTag; ::VariantInit(&vtTag); if (NULL != m_piMMCToolbar) goto Error; // Handle only one object pUnk = FirstControl(&dwDummy); if (pUnk == NULL) { hr = SID_E_INTERNAL; EXCEPTION_CHECK_GO(hr); } hr = pUnk->QueryInterface(IID_IMMCToolbar, reinterpret_cast<void **>(&m_piMMCToolbar)); if (FAILED(hr)) { hr = SID_E_INTERNAL; EXCEPTION_CHECK_GO(hr); } hr = pUnk->QueryInterface(IID_IObjectModel, reinterpret_cast<void **>(&piObjectModel)); if (FAILED(hr)) { hr = SID_E_INTERNAL; EXCEPTION_CHECK_GO(hr); } hr = piObjectModel->GetSnapInDesignerDef(&m_piSnapInDesignerDef); if (FAILED(hr)) { hr = SID_E_INTERNAL; EXCEPTION_CHECK_GO(hr); } hr = InitializeImageListCombo(); IfFailGo(hr); hr = InitializeImageListValue(); IfFailGo(hr); hr = m_piMMCToolbar->get_Tag(&vtTag); IfFailGo(hr); hr = SetDlgText(vtTag, IDC_EDIT_TB_TAG); IfFailGo(hr); m_bInitialized = true; Error: ::VariantClear(&vtTag); RELEASE(piObjectModel); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarGeneralPage::InitializeImageListCombo() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarGeneralPage::InitializeImageListCombo() { HRESULT hr = S_OK; IMMCImageLists *piMMCImageLists = NULL; long lCount = 0; int lIndex = 0; VARIANT varIndex; IMMCImageList *piMMCImageList = NULL; BSTR bstrILName = NULL; int iResult = 0; ASSERT(NULL != m_piSnapInDesignerDef, "InitializeImageListCombo: m_piSnapInDesignerDef is NULL"); ::VariantInit(&varIndex); hr = m_piSnapInDesignerDef->get_ImageLists(&piMMCImageLists); IfFailGo(hr); hr = piMMCImageLists->get_Count(&lCount); IfFailGo(hr); for (lIndex = 1; lIndex <= lCount; ++lIndex) { varIndex.vt = VT_I4; varIndex.lVal = lIndex; hr = piMMCImageLists->get_Item(varIndex, &piMMCImageList); IfFailGo(hr); hr = piMMCImageList->get_Name(&bstrILName); IfFailGo(hr); hr = AddCBBstr(IDC_COMBO_TB_ILS, bstrILName, 0); IfFailGo(hr); FREESTRING(bstrILName); RELEASE(piMMCImageList); } Error: FREESTRING(bstrILName); ::VariantClear(&varIndex); RELEASE(piMMCImageList); RELEASE(piMMCImageLists); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarGeneralPage::InitializeImageListValue() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarGeneralPage::InitializeImageListValue() { HRESULT hr = S_OK; IMMCImageList *piMMCImageList = NULL; BSTR bstrName = NULL; ASSERT(m_piMMCToolbar != NULL, "InitializeImageListValue: m_piMMCToolbar is NULL"); hr = m_piMMCToolbar->get_ImageList(reinterpret_cast<MMCImageList **>(&piMMCImageList)); IfFailGo(hr); if (NULL != piMMCImageList) { hr = piMMCImageList->get_Name(&bstrName); IfFailGo(hr); hr = SelectCBBstr(IDC_COMBO_TB_ILS, bstrName); IfFailGo(hr); } Error: FREESTRING(bstrName); RELEASE(piMMCImageList); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarGeneralPage::OnApply() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarGeneralPage::OnApply() { HRESULT hr = S_OK; ASSERT(m_piMMCToolbar != NULL, "OnApply: m_piMMCToolbar is NULL"); hr = ApplyImageList(); IfFailGo(hr); hr = ApplyTag(); IfFailGo(hr); Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarGeneralPage::ApplyImageList() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarGeneralPage::ApplyImageList() { HRESULT hr = S_OK; BSTR bstrImageList = NULL; IMMCImageLists *piMMCImageLists = NULL; IMMCImageList *piMMCImageList = NULL; VARIANT varIndex; ASSERT(m_piMMCToolbar != NULL, "ApplyImageList: m_piMMCToolbar is NULL"); ::VariantInit(&varIndex); hr = GetCBSelection(IDC_COMBO_TB_ILS, &bstrImageList); IfFailGo(hr); hr = m_piSnapInDesignerDef->get_ImageLists(&piMMCImageLists); IfFailGo(hr); varIndex.vt = VT_BSTR; varIndex.bstrVal = ::SysAllocString(bstrImageList); hr = piMMCImageLists->get_Item(varIndex, &piMMCImageList); IfFailGo(hr); hr = m_piMMCToolbar->putref_ImageList(reinterpret_cast<MMCImageList *>(piMMCImageList)); IfFailGo(hr); Error: ::VariantClear(&varIndex); RELEASE(piMMCImageList); RELEASE(piMMCImageLists); FREESTRING(bstrImageList); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarGeneralPage::ApplyTag() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarGeneralPage::ApplyTag() { HRESULT hr = S_OK; BSTR bstrTag = NULL; VARIANT vtTag; ASSERT(m_piMMCToolbar != NULL, "ApplyTag: m_piMMCToolbar is NULL"); ::VariantInit(&vtTag); hr = GetDlgText(IDC_EDIT_TB_TAG, &bstrTag); IfFailGo(hr); vtTag.vt = VT_BSTR; vtTag.bstrVal = ::SysAllocString(bstrTag); hr = m_piMMCToolbar->put_Tag(vtTag); IfFailGo(hr); Error: ::VariantClear(&vtTag); FREESTRING(bstrTag); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarGeneralPage::OnCtlSelChange(int dlgItemID) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarGeneralPage::OnCtlSelChange(int dlgItemID) { HRESULT hr = S_OK; switch(dlgItemID) { case IDC_COMBO_TB_ILS: MakeDirty(); break; } RRETURN(hr); } //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// // // Toolbar Property Page Buttons // //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// struct ButtonStyles { TCHAR m_pszStyleName[kSIMaxBuffer + 1]; SnapInButtonStyleConstants m_iIdentifier; int m_iIndex; }; ButtonStyles g_buttonStyles[5] = { _T(""), siDefault, -1, _T(""), siCheck, -1, _T(""), siButtonGroup, -1, _T(""), siSeparator, -1, _T(""), siDropDown, -1 }; struct ButtonValues { TCHAR m_pszValueName[kSIMaxBuffer + 1]; SnapInButtonValueConstants m_iIdentifier; int m_iIndex; }; ButtonValues g_buttonValues[2] = { _T(""), siUnpressed, -1, _T(""), siPressed, -1, }; //=-------------------------------------------------------------------------------------- // IUnknown *CToolbarButtonsPage::Create(IUnknown *pUnkOuter) //=-------------------------------------------------------------------------------------- // // Notes // IUnknown *CToolbarButtonsPage::Create(IUnknown *pUnkOuter) { CToolbarButtonsPage *pNew = New CToolbarButtonsPage(pUnkOuter); return pNew->PrivateUnknown(); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::CToolbarButtonsPage(IUnknown *pUnkOuter) //=-------------------------------------------------------------------------------------- // // Notes // CToolbarButtonsPage::CToolbarButtonsPage ( IUnknown *pUnkOuter ) : CSIPropertyPage(pUnkOuter, OBJECT_TYPE_PPGTOOLBRBUTTONS), m_piMMCToolbar(0), m_lCurrentButtonIndex(0), m_lCurrentButtonMenuIndex(0), m_bSavedLastButton(true), m_bSavedLastButtonMenu(true) { } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::~CToolbarButtonsPage() //=-------------------------------------------------------------------------------------- // // Notes // CToolbarButtonsPage::~CToolbarButtonsPage() { RELEASE(m_piMMCToolbar); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::OnInitializeDialog() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::OnInitializeDialog() { HRESULT hr = S_OK; hr = RegisterTooltip(IDC_EDIT_TB_INDEX, IDS_TT_TB_BTN_INDEX); IfFailGo(hr); hr = RegisterTooltip(IDC_EDIT_TB_CAPTION, IDS_TT_TB_BTN_CAPTION); IfFailGo(hr); hr = RegisterTooltip(IDC_EDIT_TB_KEY, IDS_TT_TB_BTN_KEY); IfFailGo(hr); hr = RegisterTooltip(IDC_COMBO_TB_BUTTON_VALUE, IDS_TT_TB_BTN_VALUE); IfFailGo(hr); hr = RegisterTooltip(IDC_COMBO_TB_BUTTON_STYLE, IDS_TT_TB_BTN_STYLE); IfFailGo(hr); hr = RegisterTooltip(IDC_EDIT_TB_TOOLTIP_TEXT, IDS_TT_TB_BTN_TT_TEXT); IfFailGo(hr); hr = RegisterTooltip(IDC_EDIT_TB_IMAGE, IDS_TT_TB_BTN_IMAGE); IfFailGo(hr); hr = RegisterTooltip(IDC_EDIT_TB_BUTTON_TAG, IDS_TT_TB_BTN_TAG); IfFailGo(hr); hr = RegisterTooltip(IDC_CHECK_TB_VISIBLE, IDS_TT_TB_BTN_VISIBLE); IfFailGo(hr); hr = RegisterTooltip(IDC_CHECK_TB_ENABLED, IDS_TT_TB_BTN_ENABLED); IfFailGo(hr); hr = RegisterTooltip(IDC_CHECK_TB_MIXED_STATE, IDS_TT_TB_BTN_MIXED); IfFailGo(hr); hr = RegisterTooltip(IDC_EDIT_TB_MENU_INDEX, IDS_TT_TB_BTNM_INDEX); IfFailGo(hr); hr = RegisterTooltip(IDC_EDIT_TB_MENU_TEXT, IDS_TT_TB_BTNM_TEXT); IfFailGo(hr); hr = RegisterTooltip(IDC_EDIT_TB_MENU_KEY, IDS_TT_TB_BTNM_KEY); IfFailGo(hr); hr = RegisterTooltip(IDC_EDIT_TB_MENU_TAG, IDS_TT_TB_BTNM_TAG); IfFailGo(hr); hr = RegisterTooltip(IDC_CHECK_TB_MENU_ENABLED, IDS_TT_TB_BTNM_ENABLED); IfFailGo(hr); hr = RegisterTooltip(IDC_CHECK_TB_MENU_VISIBLE, IDS_TT_TB_BTNM_VISIBLE); IfFailGo(hr); hr = RegisterTooltip(IDC_CHECK_TB_MENU_CHECKED, IDS_TT_TB_BTN_CHECKED); IfFailGo(hr); hr = RegisterTooltip(IDC_CHECK_TB_MENU_GRAYED, IDS_TT_TB_BTN_GRAYED); IfFailGo(hr); hr = RegisterTooltip(IDC_CHECK_TB_MENU_SEPARATOR, IDS_TT_TB_BTN_SEPRTR); IfFailGo(hr); hr = RegisterTooltip(IDC_CHECK_TB_MENU_BREAK, IDS_TT_TB_BTN_MENUBR); IfFailGo(hr); hr = RegisterTooltip(IDC_CHECK_TB_MENU_BAR_BREAK, IDS_TT_TB_BTN_MENUBARB); IfFailGo(hr); hr = PopulateButtonStyles(); IfFailGo(hr); hr = PopulateButtonValues(); IfFailGo(hr); hr = EnableButtonEdits(false); IfFailGo(hr); hr = EnableButtonMenuEdits(false); IfFailGo(hr); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_REMOVE_BUTTON), FALSE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_INSERT_BUTTON_MENU), FALSE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_REMOVE_BUTTON_MENU), FALSE); hr = SetDlgText(IDC_EDIT_TB_INDEX, m_lCurrentButtonIndex); IfFailGo(hr); hr = SetDlgText(IDC_EDIT_TB_MENU_INDEX, m_lCurrentButtonMenuIndex); IfFailGo(hr); Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::InitializeButtonValues() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::InitializeButtonValues() { HRESULT hr = S_OK; int iResult = 0; char szBuffer[kSIMaxBuffer + 1]; if (-1 == g_buttonValues[0].m_iIndex) { iResult = ::LoadString(GetResourceHandle(), IDS_TB_BV_UNPRESSED, szBuffer, kSIMaxBuffer); if (0 == iResult) { hr = HRESULT_FROM_WIN32(::GetLastError()); EXCEPTION_CHECK_GO(hr); } _tcscpy(g_buttonValues[0].m_pszValueName, szBuffer); g_buttonValues[0].m_iIdentifier = siUnpressed; iResult = ::LoadString(GetResourceHandle(), IDS_TB_BV_PRESSED, szBuffer, kSIMaxBuffer); if (0 == iResult) { hr = HRESULT_FROM_WIN32(::GetLastError()); EXCEPTION_CHECK_GO(hr); } _tcscpy(g_buttonValues[1].m_pszValueName, szBuffer); g_buttonValues[1].m_iIdentifier = siPressed; } Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::PopulateButtonValues() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::PopulateButtonValues() { HRESULT hr = S_OK; BSTR bstr = NULL; int iIndex = 0; hr = InitializeButtonValues(); IfFailGo(hr); for (iIndex = 0; iIndex < 2; ++iIndex) { hr = BSTRFromANSI(g_buttonValues[iIndex].m_pszValueName, &bstr); IfFailGo(hr); hr = AddCBBstr(IDC_COMBO_TB_BUTTON_VALUE, bstr, g_buttonValues[iIndex].m_iIdentifier); IfFailGo(hr); FREESTRING(bstr); } Error: FREESTRING(bstr); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::InitializeButtonStyles() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::InitializeButtonStyles() { HRESULT hr = S_OK; int iResult = 0; char szBuffer[kSIMaxBuffer + 1]; if (-1 == g_buttonStyles[0].m_iIndex) { iResult = ::LoadString(GetResourceHandle(), IDS_TB_BS_DEFAULT, szBuffer, kSIMaxBuffer); if (0 == iResult) { hr = HRESULT_FROM_WIN32(::GetLastError()); EXCEPTION_CHECK_GO(hr); } _tcscpy(g_buttonStyles[0].m_pszStyleName, szBuffer); g_buttonStyles[0].m_iIdentifier = siDefault; iResult = ::LoadString(GetResourceHandle(), IDS_TB_BS_CHECK, szBuffer, kSIMaxBuffer); if (0 == iResult) { hr = HRESULT_FROM_WIN32(::GetLastError()); EXCEPTION_CHECK_GO(hr); } _tcscpy(g_buttonStyles[1].m_pszStyleName, szBuffer); g_buttonStyles[1].m_iIdentifier = siCheck; iResult = ::LoadString(GetResourceHandle(), IDS_TB_BS_GROUP, szBuffer, kSIMaxBuffer); if (0 == iResult) { hr = HRESULT_FROM_WIN32(::GetLastError()); EXCEPTION_CHECK_GO(hr); } _tcscpy(g_buttonStyles[2].m_pszStyleName, szBuffer); g_buttonStyles[2].m_iIdentifier = siButtonGroup; iResult = ::LoadString(GetResourceHandle(), IDS_TB_BS_SEPARATOR, szBuffer, kSIMaxBuffer); if (0 == iResult) { hr = HRESULT_FROM_WIN32(::GetLastError()); EXCEPTION_CHECK_GO(hr); } _tcscpy(g_buttonStyles[3].m_pszStyleName, szBuffer); g_buttonStyles[3].m_iIdentifier = siSeparator; iResult = ::LoadString(GetResourceHandle(), IDS_TB_BS_DROPDOWN, szBuffer, kSIMaxBuffer); if (0 == iResult) { hr = HRESULT_FROM_WIN32(::GetLastError()); EXCEPTION_CHECK_GO(hr); } _tcscpy(g_buttonStyles[4].m_pszStyleName, szBuffer); g_buttonStyles[4].m_iIdentifier = siDropDown; } Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::PopulateButtonStyles() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::PopulateButtonStyles() { HRESULT hr = S_OK; BSTR bstr = NULL; int iIndex = 0; hr = InitializeButtonStyles(); IfFailGo(hr); for (iIndex = 0; iIndex < 5; ++iIndex) { hr = BSTRFromANSI(g_buttonStyles[iIndex].m_pszStyleName, &bstr); IfFailGo(hr); hr = AddCBBstr(IDC_COMBO_TB_BUTTON_STYLE, bstr, g_buttonStyles[iIndex].m_iIdentifier); IfFailGo(hr); FREESTRING(bstr); } Error: FREESTRING(bstr); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::OnNewObjects() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::OnNewObjects() { HRESULT hr = S_OK; IUnknown *pUnk = NULL; DWORD dwDummy = 0; IMMCButtons *piMMCButtons = NULL; long lCount = 0; IMMCButton *piMMCButton = NULL; if (NULL != m_piMMCToolbar) goto Error; // Handle only one object pUnk = FirstControl(&dwDummy); if (pUnk == NULL) { hr = SID_E_INTERNAL; EXCEPTION_CHECK_GO(hr); } hr = pUnk->QueryInterface(IID_IMMCToolbar, reinterpret_cast<void **>(&m_piMMCToolbar)); if (FAILED(hr)) { hr = SID_E_INTERNAL; EXCEPTION_CHECK_GO(hr); } hr = m_piMMCToolbar->get_Buttons(reinterpret_cast<MMCButtons **>(&piMMCButtons)); IfFailGo(hr); hr = piMMCButtons->get_Count(&lCount); IfFailGo(hr); if (lCount > 0) { m_lCurrentButtonIndex = 1; hr = GetCurrentButton(&piMMCButton); IfFailGo(hr); hr = ShowButton(piMMCButton); IfFailGo(hr); hr = EnableButtonEdits(true); IfFailGo(hr); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_REMOVE_BUTTON), TRUE); } else { // There are no buttons so disable the button and button menu index // edit controls ::EnableWindow(::GetDlgItem(m_hwnd, IDC_EDIT_TB_INDEX), FALSE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_EDIT_TB_MENU_INDEX), FALSE); } m_bInitialized = true; Error: RELEASE(piMMCButton); RELEASE(piMMCButtons); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::OnApply() //=-------------------------------------------------------------------------------------- // // Notes // // Scenarios: // 1. The user is in the middle of creating a new Button // 2. The user is modifying an exising button HRESULT CToolbarButtonsPage::OnApply() { HRESULT hr = S_OK; IMMCButton *piMMCButton = NULL; long lCount = 0; int disposition = 0; IMMCButtonMenu *piMMCButtonMenu = NULL; SnapInButtonStyleConstants Style = siDefault; ASSERT(m_piMMCToolbar != NULL, "OnApply: m_piMMCToolbar is NULL"); if (0 == m_lCurrentButtonIndex) goto Error; if (!m_bSavedLastButton) { hr = CanCreateNewButton(); IfFailGo(hr); if (S_FALSE == hr) { hr = HandleCantCommit(_T("Can\'t create new Button"), _T("Would you like to discard your changes?"), &disposition); if (kSICancelOperation == disposition) { hr = E_INVALIDARG; goto Error; } else { // Discard changes hr = ExitDoingNewButtonState(NULL); IfFailGo(hr); hr = S_OK; goto Error; } } hr = CreateNewButton(&piMMCButton); IfFailGo(hr); hr = ExitDoingNewButtonState(piMMCButton); IfFailGo(hr); } else { hr = GetCurrentButton(&piMMCButton); IfFailGo(hr); } // Check the style. If it is dropdown and we haven't yet created a // button menu for it then do so now IfFailGo(piMMCButton->get_Style(&Style)); if ( (siDropDown == Style) && (!m_bSavedLastButtonMenu) ) { hr = CanCreateNewButtonMenu(); IfFailGo(hr); if (S_FALSE == hr) { hr = HandleCantCommit(_T("Can\'t create new ButtonMenu"), _T("Would you like to discard your changes?"), &disposition); if (kSICancelOperation == disposition) { hr = E_INVALIDARG; goto Error; } else { // Discard changes hr = ExitDoingNewButtonMenuState(NULL, NULL); IfFailGo(hr); hr = S_OK; goto Error; } } hr = CreateNewButtonMenu(piMMCButton, &piMMCButtonMenu); IfFailGo(hr); hr = ExitDoingNewButtonMenuState(piMMCButton, piMMCButtonMenu); IfFailGo(hr); } hr = ApplyCurrentButton(); IfFailGo(hr); Error: RELEASE(piMMCButtonMenu); RELEASE(piMMCButton); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyCurrentButton() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyCurrentButton() { HRESULT hr = S_OK; IMMCButton *piMMCButton = NULL; ASSERT(m_piMMCToolbar != NULL, "ApplyCurrentButton: m_piMMCToolbar is NULL"); hr = CanCreateNewButton(); IfFailGo(hr); if (S_FALSE == hr) { hr = E_INVALIDARG; goto Error; } hr = GetCurrentButton(&piMMCButton); IfFailGo(hr); hr = ApplyCaption(piMMCButton); IfFailGo(hr); hr = ApplyKey(piMMCButton); IfFailGo(hr); hr = ApplyStyle(piMMCButton); IfFailGo(hr); hr = ApplyImage(piMMCButton); IfFailGo(hr); hr = ApplyValue(piMMCButton); IfFailGo(hr); hr = ApplyTooltipText(piMMCButton); IfFailGo(hr); hr = ApplyTag(piMMCButton); IfFailGo(hr); hr = ApplyVisible(piMMCButton); IfFailGo(hr); hr = ApplyEnabled(piMMCButton); IfFailGo(hr); hr = ApplyMixedState(piMMCButton); IfFailGo(hr); hr = ApplyCurrentButtonMenu(piMMCButton); IfFailGo(hr); Error: RELEASE(piMMCButton); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyCurrentButtonMenu(IMMCButton *piMMCButton) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyCurrentButtonMenu(IMMCButton *piMMCButton) { HRESULT hr = S_OK; SnapInButtonStyleConstants bscStyle = siDefault; IMMCButtonMenu *piMMCButtonMenu = NULL; ASSERT(m_piMMCToolbar != NULL, "ApplyCurrentButtonMenu: m_piMMCToolbar is NULL"); ASSERT(piMMCButton != NULL, "ApplyCurrentButtonMenu: piMMCButton is NULL"); hr = piMMCButton->get_Style(&bscStyle); IfFailGo(hr); if (siDropDown == bscStyle) { hr = GetCurrentButtonMenu(piMMCButton, &piMMCButtonMenu); IfFailGo(hr); if (NULL != piMMCButtonMenu) { hr = ApplyButtonMenuText(piMMCButtonMenu); IfFailGo(hr); hr = ApplyButtonMenuKey(piMMCButtonMenu); IfFailGo(hr); hr = ApplyButtonMenuTag(piMMCButtonMenu); IfFailGo(hr); hr = ApplyButtonMenuEnabled(piMMCButtonMenu); IfFailGo(hr); hr = ApplyButtonMenuVisible(piMMCButtonMenu); IfFailGo(hr); hr = ApplyButtonMenuChecked(piMMCButtonMenu); IfFailGo(hr); hr = ApplyButtonMenuGrayed(piMMCButtonMenu); IfFailGo(hr); hr = ApplyButtonMenuSeparator(piMMCButtonMenu); IfFailGo(hr); hr = ApplyButtonMenuBreak(piMMCButtonMenu); IfFailGo(hr); hr = ApplyButtonMenuBarBreak(piMMCButtonMenu); IfFailGo(hr); } } Error: RELEASE(piMMCButtonMenu); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyCaption(IMMCButton *piMMCButton) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyCaption(IMMCButton *piMMCButton) { HRESULT hr = S_OK; BSTR bstrCaption = NULL; BSTR bstrSavedCaption = NULL; ASSERT(NULL != piMMCButton, "ApplyCaption: piMMCButton is NULL"); hr = GetDlgText(IDC_EDIT_TB_CAPTION, &bstrCaption); IfFailGo(hr); hr = piMMCButton->get_Caption(&bstrSavedCaption); IfFailGo(hr); if (NULL == bstrSavedCaption || 0 != ::wcscmp(bstrCaption, bstrSavedCaption)) { hr = piMMCButton->put_Caption(bstrCaption); IfFailGo(hr); } Error: FREESTRING(bstrSavedCaption); FREESTRING(bstrCaption); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyKey(IMMCButton *piMMCButton) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyKey(IMMCButton *piMMCButton) { HRESULT hr = S_OK; BSTR bstrKey = NULL; BSTR bstrSavedKey = NULL; ASSERT(NULL != piMMCButton, "ApplyKey: piMMCButton is NULL"); hr = GetDlgText(IDC_EDIT_TB_KEY, &bstrKey); IfFailGo(hr); if ( (NULL == bstrKey) || (0 == ::SysStringLen(bstrKey)) ) { hr = piMMCButton->put_Key(NULL); IfFailGo(hr); } else { hr = piMMCButton->get_Key(&bstrSavedKey); IfFailGo(hr); if ( (NULL == bstrSavedKey) || (0 != ::wcscmp(bstrKey, bstrSavedKey)) ) { hr = piMMCButton->put_Key(bstrKey); IfFailGo(hr); } } Error: FREESTRING(bstrSavedKey); FREESTRING(bstrKey); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyValue(IMMCButton *piMMCButton) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyValue(IMMCButton *piMMCButton) { HRESULT hr = S_OK; long lValue = 0; SnapInButtonValueConstants bvcValue = siUnpressed; SnapInButtonValueConstants bvcSavedValue = siUnpressed; ASSERT(NULL != m_piMMCToolbar, "ApplyValue: m_piMMCToolbar is NULL"); hr = GetCBSelectedItemData(IDC_COMBO_TB_BUTTON_VALUE, &lValue); IfFailGo(hr); bvcValue = static_cast<SnapInButtonValueConstants>(lValue); hr = piMMCButton->get_Value(&bvcSavedValue); IfFailGo(hr); if (bvcValue != bvcSavedValue) { hr = piMMCButton->put_Value(bvcValue); IfFailGo(hr); } Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyStyle(IMMCButton *piMMCButton) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyStyle(IMMCButton *piMMCButton) { HRESULT hr = S_OK; long lValue = 0; long cButtons = 0; SnapInButtonStyleConstants NewStyle = siDefault; SnapInButtonStyleConstants SavedStyle = siDefault; ASSERT(NULL != piMMCButton, "ApplyStyle: piMMCButton is NULL"); hr = GetCBSelectedItemData(IDC_COMBO_TB_BUTTON_STYLE, &lValue); IfFailGo(hr); NewStyle = static_cast<SnapInButtonStyleConstants>(lValue); hr = piMMCButton->get_Style(&SavedStyle); IfFailGo(hr); if (NewStyle != SavedStyle) { hr = piMMCButton->put_Style(NewStyle); IfFailGo(hr); } Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyTooltipText(IMMCButton *piMMCButton) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyTooltipText(IMMCButton *piMMCButton) { HRESULT hr = S_OK; BSTR bstrTooltipText = NULL; BSTR bstrSavedTooltipText = NULL; ASSERT(NULL != m_piMMCToolbar, "ApplyTooltipText: m_piMMCToolbar is NULL"); hr = GetDlgText(IDC_EDIT_TB_TOOLTIP_TEXT, &bstrTooltipText); IfFailGo(hr); hr = piMMCButton->get_ToolTipText(&bstrSavedTooltipText); IfFailGo(hr); if (NULL == bstrSavedTooltipText || 0 != ::wcscmp(bstrTooltipText, bstrSavedTooltipText)) { hr = piMMCButton->put_ToolTipText(bstrTooltipText); IfFailGo(hr); } Error: FREESTRING(bstrSavedTooltipText); FREESTRING(bstrTooltipText); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyImage(IMMCButton *piMMCButton) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyImage(IMMCButton *piMMCButton) { HRESULT hr = S_OK; VARIANT vtNewImage; ASSERT(NULL != piMMCButton, "ApplyImage: piMMCButton is NULL"); ::VariantInit(&vtNewImage); hr = GetDlgVariant(IDC_EDIT_TB_IMAGE, &vtNewImage); IfFailGo(hr); if (VT_EMPTY != vtNewImage.vt) { hr = piMMCButton->put_Image(vtNewImage); IfFailGo(hr); } Error: ::VariantClear(&vtNewImage); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyTag(IMMCButton *piMMCButton) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyTag(IMMCButton *piMMCButton) { HRESULT hr = S_OK; BSTR bstrTag = NULL; VARIANT vtNewTag; ASSERT(NULL != m_piMMCToolbar, "ApplyTag: m_piMMCToolbar is NULL"); ::VariantInit(&vtNewTag); hr = GetDlgText(IDC_EDIT_TB_BUTTON_TAG, &bstrTag); IfFailGo(hr); vtNewTag.vt = VT_BSTR; vtNewTag.bstrVal = ::SysAllocString(bstrTag); if (NULL == vtNewTag.bstrVal) { hr = SID_E_OUTOFMEMORY; EXCEPTION_CHECK_GO(hr); } hr = piMMCButton->put_Tag(vtNewTag); IfFailGo(hr); Error: ::VariantClear(&vtNewTag); FREESTRING(bstrTag); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyVisible(IMMCButton *piMMCButton) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyVisible(IMMCButton *piMMCButton) { HRESULT hr = S_OK; VARIANT_BOOL vtbVisible = VARIANT_FALSE; VARIANT_BOOL vtbSavedVisible = VARIANT_FALSE; ASSERT(NULL != m_piMMCToolbar, "ApplyVisible: m_piMMCToolbar is NULL"); hr = GetCheckbox(IDC_CHECK_TB_VISIBLE, &vtbVisible); IfFailGo(hr); hr = piMMCButton->get_Visible(&vtbSavedVisible); IfFailGo(hr); if (vtbVisible != vtbSavedVisible) { hr = piMMCButton->put_Visible(vtbVisible); IfFailGo(hr); } Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyEnabled(IMMCButton *piMMCButton) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyEnabled(IMMCButton *piMMCButton) { HRESULT hr = S_OK; VARIANT_BOOL vtbEnabled = VARIANT_FALSE; VARIANT_BOOL vtbSavedEnabled = VARIANT_FALSE; ASSERT(NULL != m_piMMCToolbar, "ApplyEnabled: m_piMMCToolbar is NULL"); hr = GetCheckbox(IDC_CHECK_TB_ENABLED, &vtbEnabled); IfFailGo(hr); hr = piMMCButton->get_Enabled(&vtbSavedEnabled); IfFailGo(hr); if (vtbEnabled != vtbSavedEnabled) { hr = piMMCButton->put_Enabled(vtbEnabled); IfFailGo(hr); } Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyMixedState(IMMCButton *piMMCButton) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyMixedState(IMMCButton *piMMCButton) { HRESULT hr = S_OK; VARIANT_BOOL vtbMixedState = VARIANT_FALSE; VARIANT_BOOL vtbSavedMixedState = VARIANT_FALSE; ASSERT(NULL != m_piMMCToolbar, "ApplyMixedState: m_piMMCToolbar is NULL"); hr = GetCheckbox(IDC_CHECK_TB_MIXED_STATE, &vtbMixedState); IfFailGo(hr); hr = piMMCButton->get_MixedState(&vtbSavedMixedState); IfFailGo(hr); if (vtbMixedState != vtbSavedMixedState) { hr = piMMCButton->put_MixedState(vtbMixedState); IfFailGo(hr); } Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyButtonMenuText(IMMCButtonMenu *piMMCButtonMenu) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyButtonMenuText(IMMCButtonMenu *piMMCButtonMenu) { HRESULT hr = S_OK; BSTR bstrButtonMenuText = NULL; BSTR bstrSavedButtonMenuText = NULL; ASSERT(NULL != piMMCButtonMenu, "ApplyButtonMenuText: piMMCButtonMenu is NULL"); hr = GetDlgText(IDC_EDIT_TB_MENU_TEXT, &bstrButtonMenuText); IfFailGo(hr); hr = piMMCButtonMenu->get_Text(&bstrSavedButtonMenuText); IfFailGo(hr); if (NULL == bstrSavedButtonMenuText || 0 != ::wcscmp(bstrButtonMenuText, bstrSavedButtonMenuText)) { hr = piMMCButtonMenu->put_Text(bstrButtonMenuText); IfFailGo(hr); } Error: FREESTRING(bstrSavedButtonMenuText); FREESTRING(bstrButtonMenuText); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyButtonMenuKey(IMMCButtonMenu *piMMCButtonMenu) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyButtonMenuKey(IMMCButtonMenu *piMMCButtonMenu) { HRESULT hr = S_OK; BSTR bstrButtonMenuKey = NULL; BSTR bstrSavedButtonMenuKey = NULL; ASSERT(NULL != piMMCButtonMenu, "ApplyButtonMenuKey: piMMCButtonMenu is NULL"); hr = GetDlgText(IDC_EDIT_TB_MENU_KEY, &bstrButtonMenuKey); IfFailGo(hr); hr = piMMCButtonMenu->get_Key(&bstrSavedButtonMenuKey); IfFailGo(hr); if (NULL == bstrSavedButtonMenuKey || 0 != ::wcscmp(bstrButtonMenuKey, bstrSavedButtonMenuKey)) { hr = piMMCButtonMenu->put_Key(bstrButtonMenuKey); IfFailGo(hr); } Error: FREESTRING(bstrSavedButtonMenuKey); FREESTRING(bstrButtonMenuKey); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyButtonMenuTag(IMMCButtonMenu *piMMCButtonMenu) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyButtonMenuTag(IMMCButtonMenu *piMMCButtonMenu) { HRESULT hr = S_OK; BSTR bstrTag = NULL; VARIANT vtNewTag; ASSERT(NULL != piMMCButtonMenu, "ApplyButtonMenuTag: piMMCButtonMenu is NULL"); ::VariantInit(&vtNewTag); hr = GetDlgText(IDC_EDIT_TB_MENU_TAG, &bstrTag); IfFailGo(hr); vtNewTag.vt = VT_BSTR; vtNewTag.bstrVal = ::SysAllocString(bstrTag); if (NULL == vtNewTag.bstrVal) { hr = SID_E_OUTOFMEMORY; EXCEPTION_CHECK_GO(hr); } hr = piMMCButtonMenu->put_Tag(vtNewTag); IfFailGo(hr); Error: ::VariantClear(&vtNewTag); FREESTRING(bstrTag); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyButtonMenuEnabled(IMMCButtonMenu *piMMCButtonMenu) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyButtonMenuEnabled(IMMCButtonMenu *piMMCButtonMenu) { HRESULT hr = S_OK; VARIANT_BOOL vtbEnabled = VARIANT_FALSE; VARIANT_BOOL vtbSavedEnabled = VARIANT_FALSE; ASSERT(NULL != piMMCButtonMenu, "ApplyButtonMenuEnabled: piMMCButtonMenu is NULL"); hr = GetCheckbox(IDC_CHECK_TB_MENU_ENABLED, &vtbEnabled); IfFailGo(hr); hr = piMMCButtonMenu->get_Enabled(&vtbSavedEnabled); IfFailGo(hr); if (vtbEnabled != vtbSavedEnabled) { hr = piMMCButtonMenu->put_Enabled(vtbEnabled); IfFailGo(hr); } Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyButtonMenuVisible(IMMCButtonMenu *piMMCButtonMenu) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyButtonMenuVisible(IMMCButtonMenu *piMMCButtonMenu) { HRESULT hr = S_OK; VARIANT_BOOL vtbVisible = VARIANT_FALSE; VARIANT_BOOL vtbSavedVisible = VARIANT_FALSE; ASSERT(NULL != piMMCButtonMenu, "ApplyButtonMenuVisible: piMMCButtonMenu is NULL"); hr = GetCheckbox(IDC_CHECK_TB_MENU_VISIBLE, &vtbVisible); IfFailGo(hr); hr = piMMCButtonMenu->get_Visible(&vtbSavedVisible); IfFailGo(hr); if (vtbVisible != vtbSavedVisible) { hr = piMMCButtonMenu->put_Visible(vtbVisible); IfFailGo(hr); } Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyButtonMenuChecked(IMMCButtonMenu *piMMCButtonMenu) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyButtonMenuChecked(IMMCButtonMenu *piMMCButtonMenu) { HRESULT hr = S_OK; VARIANT_BOOL vtbChecked = VARIANT_FALSE; VARIANT_BOOL vtbSavedChecked = VARIANT_FALSE; ASSERT(NULL != piMMCButtonMenu, "ApplyButtonMenuChecked: piMMCButtonMenu is NULL"); hr = GetCheckbox(IDC_CHECK_TB_MENU_CHECKED, &vtbChecked); IfFailGo(hr); hr = piMMCButtonMenu->get_Checked(&vtbSavedChecked); IfFailGo(hr); if (vtbChecked != vtbSavedChecked) { hr = piMMCButtonMenu->put_Checked(vtbChecked); IfFailGo(hr); } Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyButtonMenuGrayed(IMMCButtonMenu *piMMCButtonMenu) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyButtonMenuGrayed(IMMCButtonMenu *piMMCButtonMenu) { HRESULT hr = S_OK; VARIANT_BOOL vtbGrayed = VARIANT_FALSE; VARIANT_BOOL vtbSavedGrayed = VARIANT_FALSE; ASSERT(NULL != piMMCButtonMenu, "ApplyButtonMenuGrayed: piMMCButtonMenu is NULL"); hr = GetCheckbox(IDC_CHECK_TB_MENU_GRAYED, &vtbGrayed); IfFailGo(hr); hr = piMMCButtonMenu->get_Grayed(&vtbSavedGrayed); IfFailGo(hr); if (vtbGrayed != vtbSavedGrayed) { hr = piMMCButtonMenu->put_Grayed(vtbGrayed); IfFailGo(hr); } Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyButtonMenuSeparator(IMMCButtonMenu *piMMCButtonMenu) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyButtonMenuSeparator(IMMCButtonMenu *piMMCButtonMenu) { HRESULT hr = S_OK; VARIANT_BOOL vtbSeparator = VARIANT_FALSE; VARIANT_BOOL vtbSavedSeparator = VARIANT_FALSE; ASSERT(NULL != piMMCButtonMenu, "ApplyButtonMenuSeparator: piMMCButtonMenu is NULL"); hr = GetCheckbox(IDC_CHECK_TB_MENU_SEPARATOR, &vtbSeparator); IfFailGo(hr); hr = piMMCButtonMenu->get_Separator(&vtbSavedSeparator); IfFailGo(hr); if (vtbSeparator != vtbSavedSeparator) { hr = piMMCButtonMenu->put_Separator(vtbSeparator); IfFailGo(hr); } Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyButtonMenuBreak(IMMCButtonMenu *piMMCButtonMenu) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyButtonMenuBreak(IMMCButtonMenu *piMMCButtonMenu) { HRESULT hr = S_OK; VARIANT_BOOL vtbMenuBreak = VARIANT_FALSE; VARIANT_BOOL vtbSavedMenuBreak = VARIANT_FALSE; ASSERT(NULL != piMMCButtonMenu, "ApplyButtonMenuBreak: piMMCButtonMenu is NULL"); hr = GetCheckbox(IDC_CHECK_TB_MENU_BREAK, &vtbMenuBreak); IfFailGo(hr); hr = piMMCButtonMenu->get_MenuBreak(&vtbSavedMenuBreak); IfFailGo(hr); if (vtbMenuBreak != vtbSavedMenuBreak) { hr = piMMCButtonMenu->put_MenuBreak(vtbMenuBreak); IfFailGo(hr); } Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ApplyButtonMenuBarBreak(IMMCButtonMenu *piMMCButtonMenu) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ApplyButtonMenuBarBreak(IMMCButtonMenu *piMMCButtonMenu) { HRESULT hr = S_OK; VARIANT_BOOL vtbMenuBarBreak = VARIANT_FALSE; VARIANT_BOOL vtbSavedMenuBarBreak = VARIANT_FALSE; ASSERT(NULL != piMMCButtonMenu, "ApplyButtonMenuBarBreak: piMMCButtonMenu is NULL"); hr = GetCheckbox(IDC_CHECK_TB_MENU_BAR_BREAK, &vtbMenuBarBreak); IfFailGo(hr); hr = piMMCButtonMenu->get_MenuBarBreak(&vtbSavedMenuBarBreak); IfFailGo(hr); if (vtbMenuBarBreak != vtbSavedMenuBarBreak) { hr = piMMCButtonMenu->put_MenuBarBreak(vtbMenuBarBreak); IfFailGo(hr); } Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::OnButtonClicked(int dlgItemID) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::OnButtonClicked ( int dlgItemID ) { HRESULT hr = S_OK; IMMCButton *piMMCButton = NULL; switch(dlgItemID) { case IDC_BUTTON_INSERT_BUTTON: if (S_OK == IsPageDirty()) { hr = OnApply(); IfFailGo(hr); } hr = CanEnterDoingNewButtonState(); IfFailGo(hr); if (S_OK == hr) { hr = EnterDoingNewButtonState(); IfFailGo(hr); } break; case IDC_BUTTON_REMOVE_BUTTON: hr = OnRemoveButton(); IfFailGo(hr); break; case IDC_BUTTON_INSERT_BUTTON_MENU: if (S_OK == IsPageDirty()) { hr = OnApply(); IfFailGo(hr); } hr = CanEnterDoingNewButtonMenuState(); IfFailGo(hr); if (S_OK == hr) { hr = GetCurrentButton(&piMMCButton); IfFailGo(hr); hr = EnterDoingNewButtonMenuState(piMMCButton); IfFailGo(hr); } break; case IDC_BUTTON_REMOVE_BUTTON_MENU: hr = OnRemoveButtonMenu(); IfFailGo(hr); break; case IDC_CHECK_TB_VISIBLE: case IDC_CHECK_TB_ENABLED: case IDC_CHECK_TB_MIXED_STATE: case IDC_CHECK_TB_MENU_ENABLED: case IDC_CHECK_TB_MENU_VISIBLE: case IDC_CHECK_TB_MENU_CHECKED: case IDC_CHECK_TB_MENU_GRAYED: case IDC_CHECK_TB_MENU_SEPARATOR: case IDC_CHECK_TB_MENU_BREAK: case IDC_CHECK_TB_MENU_BAR_BREAK: MakeDirty(); break; } Error: RELEASE(piMMCButton); if (FAILED(hr)) HandleError(_T("Apply Error"), _T("There was an error applying values for this Toolbar.")); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::OnRemoveButton() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::OnRemoveButton() { HRESULT hr = S_OK; IMMCButtons *piMMCButtons = NULL; IMMCButton *piMMCButton = NULL; VARIANT varIndex; long lCount = 0; ASSERT(NULL != m_piMMCToolbar, "OnRemoveButton: m_piMMCToolbar is NULL"); ::VariantInit(&varIndex); hr = m_piMMCToolbar->get_Buttons(reinterpret_cast<MMCButtons **>(&piMMCButtons)); IfFailGo(hr); varIndex.vt = VT_I4; varIndex.lVal = m_lCurrentButtonIndex; hr = piMMCButtons->Remove(varIndex); IfFailGo(hr); hr = piMMCButtons->get_Count(&lCount); IfFailGo(hr); if (lCount > 0) { if (m_lCurrentButtonIndex > lCount) m_lCurrentButtonIndex = lCount; hr = GetCurrentButton(&piMMCButton); IfFailGo(hr); hr = ShowButton(piMMCButton); IfFailGo(hr); } else { m_lCurrentButtonIndex = 0; hr = ClearButton(); IfFailGo(hr); hr = EnableButtonEdits(false); IfFailGo(hr); hr = EnableButtonMenuEdits(false); IfFailGo(hr); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_REMOVE_BUTTON), FALSE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_INSERT_BUTTON_MENU), FALSE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_REMOVE_BUTTON_MENU), FALSE); } m_bSavedLastButton = TRUE; m_bSavedLastButtonMenu = TRUE; Error: ::VariantClear(&varIndex); RELEASE(piMMCButton); RELEASE(piMMCButtons); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::OnRemoveButtonMenu() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::OnRemoveButtonMenu() { HRESULT hr = S_OK; IMMCButton *piMMCButton = NULL; IMMCButtonMenu *piMMCButtonMenu = NULL; IMMCButtonMenus *piMMCButtonMenus = NULL; VARIANT varIndex; long lCount = 0; ASSERT(NULL != m_piMMCToolbar, "OnRemoveButtonMenu: m_piMMCToolbar is NULL"); ::VariantInit(&varIndex); hr = GetCurrentButton(&piMMCButton); IfFailGo(hr); hr = piMMCButton->get_ButtonMenus(reinterpret_cast<MMCButtonMenus **>(&piMMCButtonMenus)); IfFailGo(hr); varIndex.vt = VT_I4; varIndex.lVal = m_lCurrentButtonMenuIndex; hr = piMMCButtonMenus->Remove(varIndex); IfFailGo(hr); hr = piMMCButtonMenus->get_Count(&lCount); IfFailGo(hr); if (lCount > 0) { if (m_lCurrentButtonMenuIndex > lCount) m_lCurrentButtonMenuIndex = lCount; hr = GetCurrentButtonMenu(piMMCButton, &piMMCButtonMenu); IfFailGo(hr); hr = ShowButtonMenu(piMMCButtonMenu); IfFailGo(hr); } else { m_lCurrentButtonMenuIndex = 0; hr = ClearButtonMenu(); IfFailGo(hr); hr = EnableButtonMenuEdits(false); IfFailGo(hr); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_REMOVE_BUTTON_MENU), FALSE); } Error: ::VariantClear(&varIndex); RELEASE(piMMCButtonMenus); RELEASE(piMMCButtonMenu); RELEASE(piMMCButton); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ClearButton() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ClearButton() { HRESULT hr = S_OK; BSTR bstrNull = NULL; long lData = 0; hr = SetDlgText(IDC_EDIT_TB_INDEX, m_lCurrentButtonIndex); IfFailGo(hr); hr = SetDlgText(IDC_EDIT_TB_CAPTION, bstrNull); IfFailGo(hr); hr = SetDlgText(IDC_EDIT_TB_KEY, bstrNull); IfFailGo(hr); lData = 0; // siUnpressed; hr = SetCBItemSelection(IDC_COMBO_TB_BUTTON_VALUE, lData); IfFailGo(hr); lData = 0; // siDefault; hr = SetCBItemSelection(IDC_COMBO_TB_BUTTON_STYLE, lData); IfFailGo(hr); hr = SetDlgText(IDC_EDIT_TB_TOOLTIP_TEXT, bstrNull); IfFailGo(hr); // Initialize the image index to the button index. hr = SetDlgText(IDC_EDIT_TB_IMAGE, m_lCurrentButtonIndex); IfFailGo(hr); hr = SetDlgText(IDC_EDIT_TB_BUTTON_TAG, bstrNull); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_VISIBLE, VARIANT_TRUE); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_ENABLED, VARIANT_TRUE); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_MIXED_STATE, VARIANT_FALSE); IfFailGo(hr); Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ClearButtonMenu() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ClearButtonMenu() { HRESULT hr = S_OK; BSTR bstrNull = NULL; hr = SetDlgText(IDC_EDIT_TB_MENU_INDEX, m_lCurrentButtonMenuIndex); IfFailGo(hr); hr = SetDlgText(IDC_EDIT_TB_MENU_TEXT, bstrNull); IfFailGo(hr); hr = SetDlgText(IDC_EDIT_TB_MENU_KEY, bstrNull); IfFailGo(hr); hr = SetDlgText(IDC_EDIT_TB_MENU_TAG, bstrNull); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_MENU_ENABLED, VARIANT_TRUE); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_MENU_VISIBLE, VARIANT_TRUE); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_MENU_CHECKED, VARIANT_FALSE); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_MENU_GRAYED, VARIANT_FALSE); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_MENU_SEPARATOR, VARIANT_FALSE); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_MENU_BREAK, VARIANT_FALSE); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_MENU_BAR_BREAK, VARIANT_FALSE); IfFailGo(hr); Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::OnCtlSelChange(int dlgItemID) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::OnCtlSelChange(int dlgItemID) { HRESULT hr = S_OK; switch(dlgItemID) { case IDC_COMBO_TB_BUTTON_VALUE: MakeDirty(); break; case IDC_COMBO_TB_BUTTON_STYLE: hr = OnButtonStyle(); IfFailGo(hr); MakeDirty(); break; } Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::OnButtonStyle() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::OnButtonStyle() { HRESULT hr = S_OK; long lData = 0; SnapInButtonStyleConstants bscStyle = siDefault; IMMCButton *piMMCButton = NULL; IMMCButtonMenus *piMMCButtonMenus = NULL; long lCount = 0; ASSERT(NULL != m_piMMCToolbar, "ApplyEnabled: OnButtonStyle is NULL"); IfFailGo(GetCBSelectedItemData(IDC_COMBO_TB_BUTTON_STYLE, &lData)); bscStyle = static_cast<SnapInButtonStyleConstants>(lData); IfFailGo(GetCurrentButton(&piMMCButton)); if (NULL != piMMCButton) { IfFailGo(piMMCButton->get_ButtonMenus(reinterpret_cast<MMCButtonMenus **>(&piMMCButtonMenus))); } switch (bscStyle) { case siDropDown: ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_INSERT_BUTTON_MENU), TRUE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_EDIT_TB_CAPTION), TRUE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_EDIT_TB_IMAGE), FALSE); IfFailGo(SetDlgText(IDC_EDIT_TB_IMAGE, (BSTR)NULL)); break; default: ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_INSERT_BUTTON_MENU), FALSE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_REMOVE_BUTTON_MENU), FALSE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_EDIT_TB_IMAGE), TRUE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_EDIT_TB_CAPTION), FALSE); IfFailGo(SetDlgText(IDC_EDIT_TB_CAPTION, (BSTR)NULL)); IfFailGo(EnableButtonMenuEdits(FALSE)); // Revert the button to a state where it has no button menus m_lCurrentButtonMenuIndex = 0; IfFailGo(ClearButtonMenu()); if (NULL != piMMCButton) { IfFailGo(piMMCButton->put_Caption(NULL)); } if (NULL != piMMCButtonMenus) { IfFailGo(piMMCButtonMenus->Clear()); } m_bSavedLastButtonMenu = TRUE; break; } Error: RELEASE(piMMCButtonMenus); RELEASE(piMMCButton); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::OnDeltaPos(NMUPDOWN *pNMUpDown) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::OnDeltaPos(NMUPDOWN *pNMUpDown) { HRESULT hr = S_OK; switch (pNMUpDown->hdr.idFrom) { case IDC_SPIN_TB_INDEX: hr = OnButtonDeltaPos(pNMUpDown); IfFailGo(hr); break; case IDC_SPIN_TB_MENU_INDEX: hr = OnButtonMenuDeltaPos(pNMUpDown); IfFailGo(hr); break; } Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::OnButtonDeltaPos(NMUPDOWN *pNMUpDown) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::OnButtonDeltaPos(NMUPDOWN *pNMUpDown) { HRESULT hr = S_OK; IMMCButtons *piMMCButtons = NULL; long lCount = 0; IMMCButton *piMMCButton = NULL; ASSERT(NULL != m_piMMCToolbar, "OnButtonDeltaPos: m_piMMCToolbar is NULL"); if (false == m_bSavedLastButton || S_OK == IsPageDirty()) { hr = OnApply(); IfFailGo(hr); } hr = m_piMMCToolbar->get_Buttons(reinterpret_cast<MMCButtons **>(&piMMCButtons)); IfFailGo(hr); hr = piMMCButtons->get_Count(&lCount); IfFailGo(hr); if (pNMUpDown->iDelta < 0) { if (m_lCurrentButtonIndex < lCount) { ++m_lCurrentButtonIndex; hr = GetCurrentButton(&piMMCButton); IfFailGo(hr); hr = ShowButton(piMMCButton); IfFailGo(hr); } } else { if (m_lCurrentButtonIndex > 1 && m_lCurrentButtonIndex <= lCount) { --m_lCurrentButtonIndex; hr = GetCurrentButton(&piMMCButton); IfFailGo(hr); hr = ShowButton(piMMCButton); IfFailGo(hr); } } Error: RELEASE(piMMCButton); RELEASE(piMMCButtons); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::OnButtonMenuDeltaPos(NMUPDOWN *pNMUpDown) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::OnButtonMenuDeltaPos(NMUPDOWN *pNMUpDown) { HRESULT hr = S_OK; long lCount = 0; IMMCButton *piMMCButton = NULL; IMMCButtonMenus *piMMCButtonMenus = NULL; IMMCButtonMenu *piMMCButtonMenu = NULL; ASSERT(NULL != m_piMMCToolbar, "OnButtonMenuDeltaPos: m_piMMCToolbar is NULL"); if (false == m_bSavedLastButtonMenu || S_OK == IsPageDirty()) { hr = OnApply(); IfFailGo(hr); } hr = GetCurrentButton(&piMMCButton); IfFailGo(hr); hr = piMMCButton->get_ButtonMenus(reinterpret_cast<MMCButtonMenus **>(&piMMCButtonMenus)); IfFailGo(hr); hr = piMMCButtonMenus->get_Count(&lCount); IfFailGo(hr); if (pNMUpDown->iDelta < 0) { if (m_lCurrentButtonMenuIndex < lCount) { ++m_lCurrentButtonMenuIndex; hr = GetCurrentButtonMenu(piMMCButton, &piMMCButtonMenu); IfFailGo(hr); hr = ShowButtonMenu(piMMCButtonMenu); IfFailGo(hr); } } else { if (m_lCurrentButtonMenuIndex > 1 && m_lCurrentButtonMenuIndex <= lCount) { --m_lCurrentButtonMenuIndex; hr = GetCurrentButtonMenu(piMMCButton, &piMMCButtonMenu); IfFailGo(hr); hr = ShowButtonMenu(piMMCButtonMenu); IfFailGo(hr); } } Error: RELEASE(piMMCButtonMenu); RELEASE(piMMCButtonMenus); RELEASE(piMMCButton); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::OnKillFocus(int dlgItemID) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::OnKillFocus(int dlgItemID) { HRESULT hr = S_OK; int lIndex = 0; IMMCButtons *piMMCButtons = NULL; long lCount = 0; IMMCButton *piMMCButton = NULL; IMMCButtonMenus *piMMCButtonMenus = NULL; IMMCButtonMenu *piMMCButtonMenu = NULL; if (false == m_bSavedLastButton) { goto Error; } switch (dlgItemID) { case IDC_EDIT_TB_INDEX: // Get the contents of the index field. If the user entered something // other than a number then set the index to 1. hr = GetDlgInt(IDC_EDIT_TB_INDEX, &lIndex); if (E_INVALIDARG == hr) { hr = S_OK; lIndex = 1L; // Set this to zero so code below will detect a change and // refresh dialog which will replace junk in index field with "1" m_lCurrentButtonIndex = 0; } IfFailGo(hr); hr = m_piMMCToolbar->get_Buttons(reinterpret_cast<MMCButtons **>(&piMMCButtons)); IfFailGo(hr); hr = piMMCButtons->get_Count(&lCount); IfFailGo(hr); // If the user entered an index of zero then switch it to 1 because the // collection is one-based if (0 == lIndex) { lIndex = 1L; // Set this to zero so code below will detect a change and // refresh dialog which will replace junk in index field with "1" m_lCurrentButtonIndex = 0; } // If the user entered an index that is beyond the end of the list then // switch to the last valid index if (lIndex > lCount) { lIndex = lCount; // Set this to zero so code below will detect a change and // refresh dialog which will replace junk in index field with "1" m_lCurrentButtonIndex = 0; } if (lIndex != m_lCurrentButtonIndex) { m_lCurrentButtonIndex = lIndex; hr = GetCurrentButton(&piMMCButton); IfFailGo(hr); hr = ShowButton(piMMCButton); IfFailGo(hr); } break; case IDC_EDIT_TB_MENU_INDEX: // Get the contents of the index field. If the user entered something // other than a number then set the index to 1. hr = GetDlgInt(IDC_EDIT_TB_MENU_INDEX, &lIndex); if (E_INVALIDARG == hr) { hr = S_OK; lIndex = 1L; // Set this to zero so code below will detect a change and // refresh dialog which will replace junk in index field with "1" m_lCurrentButtonMenuIndex = 0; } IfFailGo(hr); hr = GetCurrentButton(&piMMCButton); IfFailGo(hr); hr = piMMCButton->get_ButtonMenus(reinterpret_cast<MMCButtonMenus **>(&piMMCButtonMenus)); IfFailGo(hr); hr = piMMCButtonMenus->get_Count(&lCount); IfFailGo(hr); // If the user entered an index of zero then switch it to 1 because the // collection is one-based if (0 == lIndex) { lIndex = 1L; // Set this to zero so code below will detect a change and // refresh dialog which will replace junk in index field with "1" m_lCurrentButtonMenuIndex = 0; } // If the user entered an index that is beyond the end of the list then // switch to the last valid index if (lIndex > lCount) { lIndex = lCount; // Set this to zero so code below will detect a change and // refresh dialog which will replace junk in index field with "1" m_lCurrentButtonMenuIndex = 0; } if (lIndex != m_lCurrentButtonMenuIndex) { m_lCurrentButtonMenuIndex = lIndex; hr = GetCurrentButtonMenu(piMMCButton, &piMMCButtonMenu); IfFailGo(hr); hr = ShowButtonMenu(piMMCButtonMenu); IfFailGo(hr); } break; } Error: RELEASE(piMMCButtonMenu); RELEASE(piMMCButtonMenus); RELEASE(piMMCButtons); RELEASE(piMMCButton); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ShowButton(IMMCButton *piMMCButton) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ShowButton ( IMMCButton *piMMCButton ) { HRESULT hr = S_OK; BSTR bstrCaption = NULL; BSTR bstrKey = NULL; SnapInButtonValueConstants bvcValue = siUnpressed; SnapInButtonStyleConstants bscStyle = siDefault; BSTR bstrTooltipText = NULL; VARIANT vtImage; VARIANT vtTag; VARIANT_BOOL vtbVisible = VARIANT_FALSE; VARIANT_BOOL vtbEnabled = VARIANT_FALSE; VARIANT_BOOL vtbMixedState = VARIANT_FALSE; IMMCButtonMenus *piMMCButtonMenus = NULL; long lCount = 0; IMMCButtonMenu *piMMCButtonMenu = NULL; ASSERT(NULL != piMMCButton, "ShowButton: piMMCButton is NULL"); ::VariantInit(&vtImage); ::VariantInit(&vtTag); m_lCurrentButtonMenuIndex = 0; m_bSilentUpdate = true; hr = SetDlgText(IDC_EDIT_TB_INDEX, m_lCurrentButtonIndex); IfFailGo(hr); hr = piMMCButton->get_Caption(&bstrCaption); IfFailGo(hr); hr = SetDlgText(IDC_EDIT_TB_CAPTION, bstrCaption); IfFailGo(hr); hr = piMMCButton->get_Key(&bstrKey); IfFailGo(hr); hr = SetDlgText(IDC_EDIT_TB_KEY, bstrKey); IfFailGo(hr); hr = piMMCButton->get_Value(&bvcValue); IfFailGo(hr); hr = SetCBItemSelection(IDC_COMBO_TB_BUTTON_VALUE, static_cast<long>(bvcValue)); IfFailGo(hr); hr = piMMCButton->get_Style(&bscStyle); IfFailGo(hr); hr = SetCBItemSelection(IDC_COMBO_TB_BUTTON_STYLE, static_cast<long>(bscStyle)); IfFailGo(hr); hr = piMMCButton->get_ToolTipText(&bstrTooltipText); IfFailGo(hr); hr = SetDlgText(IDC_EDIT_TB_TOOLTIP_TEXT, bstrTooltipText); IfFailGo(hr); hr = piMMCButton->get_Image(&vtImage); IfFailGo(hr); hr = SetDlgText(vtImage, IDC_EDIT_TB_IMAGE); IfFailGo(hr); hr = piMMCButton->get_Tag(&vtTag); IfFailGo(hr); hr = SetDlgText(vtTag, IDC_EDIT_TB_BUTTON_TAG); IfFailGo(hr); hr = piMMCButton->get_Visible(&vtbVisible); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_VISIBLE, vtbVisible); IfFailGo(hr); hr = piMMCButton->get_Enabled(&vtbEnabled); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_ENABLED, vtbEnabled); IfFailGo(hr); hr = piMMCButton->get_MixedState(&vtbMixedState); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_MIXED_STATE, vtbMixedState); IfFailGo(hr); hr = EnableButtonEdits(TRUE); IfFailGo(hr); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_EDIT_TB_INDEX), TRUE); if (siDropDown == bscStyle) { ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_INSERT_BUTTON_MENU), TRUE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_EDIT_TB_CAPTION), TRUE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_EDIT_TB_IMAGE), FALSE); hr = SetDlgText(IDC_EDIT_TB_IMAGE, (BSTR)NULL); IfFailGo(hr); hr = piMMCButton->get_ButtonMenus(reinterpret_cast<MMCButtonMenus **>(&piMMCButtonMenus)); IfFailGo(hr); hr = piMMCButtonMenus->get_Count(&lCount); IfFailGo(hr); if (lCount > 0) { m_lCurrentButtonMenuIndex = 1; hr = GetCurrentButtonMenu(piMMCButton, &piMMCButtonMenu); IfFailGo(hr); hr = ShowButtonMenu(piMMCButtonMenu); IfFailGo(hr); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_REMOVE_BUTTON_MENU), TRUE); hr = EnableButtonMenuEdits(true); IfFailGo(hr); } } else { ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_INSERT_BUTTON_MENU), FALSE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_REMOVE_BUTTON_MENU), FALSE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_EDIT_TB_CAPTION), FALSE); hr = SetDlgText(IDC_EDIT_TB_CAPTION, (BSTR)NULL); IfFailGo(hr); m_lCurrentButtonMenuIndex = 0; hr = ClearButtonMenu(); IfFailGo(hr); hr = EnableButtonMenuEdits(false); IfFailGo(hr); } Error: RELEASE(piMMCButtonMenu); RELEASE(piMMCButtonMenus); ::VariantClear(&vtTag); ::VariantClear(&vtImage); FREESTRING(bstrTooltipText); FREESTRING(bstrKey); FREESTRING(bstrCaption); m_bSilentUpdate = false; RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ShowButtonMenu(IMMCButtonMenu *piMMCButtonMenu) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ShowButtonMenu(IMMCButtonMenu *piMMCButtonMenu) { HRESULT hr = S_OK; BSTR bstrText = NULL; BSTR bstrKey = NULL; VARIANT vtTag; VARIANT_BOOL vtbEnabled = VARIANT_FALSE; VARIANT_BOOL vtbVisible = VARIANT_FALSE; ASSERT(NULL != piMMCButtonMenu, "ShowButtonMenu: piMMCButtonMenu is NULL"); ::VariantInit(&vtTag); hr = SetDlgText(IDC_EDIT_TB_MENU_INDEX, m_lCurrentButtonMenuIndex); IfFailGo(hr); hr = piMMCButtonMenu->get_Text(&bstrText); IfFailGo(hr); hr = SetDlgText(IDC_EDIT_TB_MENU_TEXT, bstrText); IfFailGo(hr); hr = piMMCButtonMenu->get_Key(&bstrKey); IfFailGo(hr); hr = SetDlgText(IDC_EDIT_TB_MENU_KEY, bstrKey); IfFailGo(hr); hr = piMMCButtonMenu->get_Tag(&vtTag); IfFailGo(hr); hr = SetDlgText(vtTag, IDC_EDIT_TB_MENU_TAG); IfFailGo(hr); hr = piMMCButtonMenu->get_Enabled(&vtbEnabled); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_MENU_ENABLED, vtbEnabled); IfFailGo(hr); hr = piMMCButtonMenu->get_Visible(&vtbVisible); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_MENU_VISIBLE, vtbVisible); IfFailGo(hr); hr = piMMCButtonMenu->get_Checked(&vtbVisible); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_MENU_CHECKED, vtbVisible); IfFailGo(hr); hr = piMMCButtonMenu->get_Grayed(&vtbVisible); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_MENU_GRAYED, vtbVisible); IfFailGo(hr); hr = piMMCButtonMenu->get_Separator(&vtbVisible); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_MENU_SEPARATOR, vtbVisible); IfFailGo(hr); hr = piMMCButtonMenu->get_MenuBreak(&vtbVisible); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_MENU_BREAK, vtbVisible); IfFailGo(hr); hr = piMMCButtonMenu->get_MenuBarBreak(&vtbVisible); IfFailGo(hr); hr = SetCheckbox(IDC_CHECK_TB_MENU_BAR_BREAK, vtbVisible); IfFailGo(hr); Error: ::VariantClear(&vtTag); FREESTRING(bstrKey); FREESTRING(bstrText); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::EnableButtonEdits(bool bEnable) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::EnableButtonEdits ( bool bEnable ) { BOOL fEnableEdit = ((false == bEnable) ? TRUE : FALSE); BOOL fEnableWindow = ((true == bEnable) ? TRUE : FALSE); // ::SendMessage(::GetDlgItem(m_hwnd, IDC_EDIT_TB_INDEX), EM_SETREADONLY, static_cast<WPARAM>(TRUE), 0); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_SPIN_TB_INDEX), fEnableWindow); ::SendMessage(::GetDlgItem(m_hwnd, IDC_EDIT_TB_CAPTION), EM_SETREADONLY, static_cast<WPARAM>(fEnableEdit), 0); ::SendMessage(::GetDlgItem(m_hwnd, IDC_EDIT_TB_KEY), EM_SETREADONLY, static_cast<WPARAM>(fEnableEdit), 0); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_COMBO_TB_BUTTON_VALUE), fEnableWindow); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_COMBO_TB_BUTTON_STYLE), fEnableWindow); ::SendMessage(::GetDlgItem(m_hwnd, IDC_EDIT_TB_TOOLTIP_TEXT), EM_SETREADONLY, static_cast<WPARAM>(fEnableEdit), 0); ::SendMessage(::GetDlgItem(m_hwnd, IDC_EDIT_TB_IMAGE), EM_SETREADONLY, static_cast<WPARAM>(fEnableEdit), 0); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_EDIT_TB_IMAGE), fEnableWindow); ::SendMessage(::GetDlgItem(m_hwnd, IDC_EDIT_TB_BUTTON_TAG), EM_SETREADONLY, static_cast<WPARAM>(fEnableEdit), 0); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_CHECK_TB_VISIBLE), fEnableWindow); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_CHECK_TB_ENABLED), fEnableWindow); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_CHECK_TB_MIXED_STATE), fEnableWindow); return S_OK; } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::EnableButtonMenuEdits(bool bEnable) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::EnableButtonMenuEdits ( bool bEnable ) { BOOL fEnableEdit = ((false == bEnable) ? TRUE : FALSE); BOOL fEnableWindow = ((true == bEnable) ? TRUE : FALSE); int iRetValue = 0; ::SendMessage(::GetDlgItem(m_hwnd, IDC_EDIT_TB_MENU_INDEX), EM_SETREADONLY, static_cast<WPARAM>(fEnableEdit), 0); iRetValue = ::EnableWindow(::GetDlgItem(m_hwnd, IDC_SPIN_TB_MENU_INDEX), fEnableWindow); iRetValue = ::SendMessage(::GetDlgItem(m_hwnd, IDC_EDIT_TB_MENU_TEXT), EM_SETREADONLY, static_cast<WPARAM>(fEnableEdit), 0); iRetValue = ::SendMessage(::GetDlgItem(m_hwnd, IDC_EDIT_TB_MENU_KEY), EM_SETREADONLY, static_cast<WPARAM>(fEnableEdit), 0); iRetValue = ::SendMessage(::GetDlgItem(m_hwnd, IDC_EDIT_TB_MENU_TAG), EM_SETREADONLY, static_cast<WPARAM>(fEnableEdit), 0); iRetValue = ::EnableWindow(::GetDlgItem(m_hwnd, IDC_CHECK_TB_MENU_ENABLED), fEnableWindow); iRetValue = ::EnableWindow(::GetDlgItem(m_hwnd, IDC_CHECK_TB_MENU_VISIBLE), fEnableWindow); iRetValue = ::EnableWindow(::GetDlgItem(m_hwnd, IDC_CHECK_TB_MENU_CHECKED), fEnableWindow); iRetValue = ::EnableWindow(::GetDlgItem(m_hwnd, IDC_CHECK_TB_MENU_GRAYED), fEnableWindow); iRetValue = ::EnableWindow(::GetDlgItem(m_hwnd, IDC_CHECK_TB_MENU_SEPARATOR), fEnableWindow); iRetValue = ::EnableWindow(::GetDlgItem(m_hwnd, IDC_CHECK_TB_MENU_BREAK), fEnableWindow); iRetValue = ::EnableWindow(::GetDlgItem(m_hwnd, IDC_CHECK_TB_MENU_BAR_BREAK), fEnableWindow); return S_OK; } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::CanEnterDoingNewButtonState() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::CanEnterDoingNewButtonState() { HRESULT hr = S_FALSE; if (m_bSavedLastButton && m_bSavedLastButtonMenu) { hr = S_OK; } RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::EnterDoingNewButtonState() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::EnterDoingNewButtonState() { HRESULT hr = S_OK; ASSERT(NULL != m_piMMCToolbar, "EnterDoingNewButtonState: m_piMMCToolbar is NULL"); // Bump up the current button index to keep matters in sync. ++m_lCurrentButtonIndex; hr = SetDlgText(IDC_EDIT_TB_INDEX, m_lCurrentButtonIndex); IfFailGo(hr); // Don't let the user change index on a new button ::EnableWindow(::GetDlgItem(m_hwnd, IDC_EDIT_TB_INDEX), FALSE); // We disable the RemoveButton, InsertButtonMenu and RemoveButtonMenu buttons. // The InsertButton button remains enabled and acts like an "Apply and New" button ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_REMOVE_BUTTON), FALSE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_INSERT_BUTTON_MENU), FALSE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_REMOVE_BUTTON_MENU), FALSE); // Enable edits in this area of the dialog and clear all the entries hr = EnableButtonEdits(TRUE); IfFailGo(hr); // Disable and clear the Caption field as the default style is siDefault and // Caption is only used for a menu button (siDropDown) ::EnableWindow(::GetDlgItem(m_hwnd, IDC_EDIT_TB_CAPTION), FALSE); hr = ClearButton(); IfFailGo(hr); // Reinitialize button menu stuff for this button m_lCurrentButtonMenuIndex = 0; hr = ClearButtonMenu(); IfFailGo(hr); hr = EnableButtonMenuEdits(FALSE); IfFailGo(hr); // Visible and Enabled should be on by default m_bSavedLastButton = FALSE; Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::CanCreateNewButton() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::CanCreateNewButton() { HRESULT hr = S_OK; long lData = 0; VARIANT vtImageIndex; ::VariantInit(&vtImageIndex); // Got to have an image which is a string or an index > 0, unless it's a drop-down, // in which case we ignore this value. hr = GetCBSelectedItemData(IDC_COMBO_TB_BUTTON_STYLE, &lData); IfFailGo(hr); if (siDropDown != static_cast<SnapInButtonStyleConstants>(lData)) { hr = GetDlgVariant(IDC_EDIT_TB_IMAGE, &vtImageIndex); IfFailGo(hr); if (VT_I4 == vtImageIndex.vt) { if (vtImageIndex.lVal <= 0) { HandleError(_T("Cannot Create New Button"), _T("ImageIndex has to be greater than zero")); hr = S_FALSE; goto Error; } } else if (VT_BSTR == vtImageIndex.vt) { if (0 == ::SysStringLen(vtImageIndex.bstrVal)) { HandleError(_T("Cannot Create New Button"), _T("ImageIndex cannot be an empty string")); hr = S_FALSE; goto Error; } } else { HandleError(_T("Cannot Create New Button"), _T("Cannot determine type of ImageIndex")); hr = S_FALSE; goto Error; } } Error: ::VariantClear(&vtImageIndex); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::CreateNewButton() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::CreateNewButton(IMMCButton **ppiMMCButton) { HRESULT hr = S_OK; IMMCButtons *piMMCButtons = NULL; VARIANT varIndex; BSTR bstrKey = NULL; VARIANT vtKey; BSTR bstrCaption = NULL; VARIANT vtCaption; BSTR bstrTooltipText = NULL; VARIANT vtTooltipText; VARIANT vtStyle; long lData = 0; BSTR bstrImage = NULL; VARIANT vtImage; ::VariantInit(&varIndex); ::VariantInit(&vtKey); ::VariantInit(&vtCaption); ::VariantInit(&vtTooltipText); ::VariantInit(&vtStyle); ::VariantInit(&vtImage); varIndex.vt = VT_I4; varIndex.lVal = m_lCurrentButtonIndex; hr = GetDlgText(IDC_EDIT_TB_KEY, &bstrKey); IfFailGo(hr); if (NULL == bstrKey || 0 == ::SysStringLen(bstrKey)) { vtKey.vt = VT_ERROR; vtKey.scode = DISP_E_PARAMNOTFOUND; } else { vtKey.vt = VT_BSTR; vtKey.bstrVal = ::SysAllocString(bstrKey); if (NULL == vtKey.bstrVal) { hr = SID_E_OUTOFMEMORY; EXCEPTION_CHECK_GO(hr); } } hr = GetDlgText(IDC_EDIT_TB_CAPTION, &bstrCaption); IfFailGo(hr); vtCaption.vt = VT_BSTR; vtCaption.bstrVal = ::SysAllocString(bstrCaption); if (NULL == vtCaption.bstrVal) { hr = SID_E_OUTOFMEMORY; EXCEPTION_CHECK_GO(hr); } hr = GetDlgText(IDC_EDIT_TB_TOOLTIP_TEXT, &bstrTooltipText); IfFailGo(hr); vtTooltipText.vt = VT_BSTR; vtTooltipText.bstrVal = ::SysAllocString(bstrTooltipText); if (NULL == vtTooltipText.bstrVal) { hr = SID_E_OUTOFMEMORY; EXCEPTION_CHECK_GO(hr); } hr = GetCBSelectedItemData(IDC_COMBO_TB_BUTTON_STYLE, &lData); IfFailGo(hr); vtStyle.vt = VT_I4; vtStyle.lVal = lData; hr = GetDlgText(IDC_EDIT_TB_IMAGE, &bstrImage); IfFailGo(hr); vtImage.vt = VT_BSTR; vtImage.bstrVal = ::SysAllocString(bstrImage); if (NULL == vtImage.bstrVal) { hr = SID_E_OUTOFMEMORY; EXCEPTION_CHECK_GO(hr); } hr = m_piMMCToolbar->get_Buttons(reinterpret_cast<MMCButtons **>(&piMMCButtons)); IfFailGo(hr); hr = piMMCButtons->Add(varIndex, vtKey, vtCaption, vtStyle, vtImage, vtTooltipText, reinterpret_cast<MMCButton **>(ppiMMCButton)); IfFailGo(hr); Error: ::VariantClear(&vtImage); FREESTRING(bstrImage); ::VariantClear(&vtStyle); ::VariantClear(&vtCaption); FREESTRING(bstrCaption); ::VariantClear(&vtTooltipText); FREESTRING(bstrTooltipText); ::VariantClear(&vtKey); FREESTRING(bstrKey); ::VariantClear(&varIndex); RELEASE(piMMCButtons); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ExitDoingNewButtonState() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ExitDoingNewButtonState(IMMCButton *piMMCButton) { HRESULT hr = S_OK; SnapInButtonStyleConstants sibsc = siDefault; ASSERT(m_piMMCToolbar != NULL, "ExitDoingNewButtonState: m_piMMCToolbar is NULL"); if (NULL != piMMCButton) { ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_REMOVE_BUTTON), TRUE); hr = piMMCButton->get_Style(&sibsc); IfFailGo(hr); if (siDropDown == sibsc) { ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_INSERT_BUTTON_MENU), TRUE); } } else // Operation was cancelled { --m_lCurrentButtonIndex; if (m_lCurrentButtonIndex > 0) { hr = GetCurrentButton(&piMMCButton); IfFailGo(hr); hr = ShowButton(piMMCButton); IfFailGo(hr); RELEASE(piMMCButton); } else { hr = EnableButtonEdits(false); IfFailGo(hr); hr = ClearButton(); IfFailGo(hr); } } m_bSavedLastButton = true; m_bSavedLastButtonMenu = true; Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::CanEnterDoingNewButtonMenuState() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::CanEnterDoingNewButtonMenuState() { HRESULT hr = S_FALSE; if (m_bSavedLastButton && m_bSavedLastButtonMenu) { hr = S_OK; } RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::EnterDoingNewButtonMenuState(IMMCButton *piMMCButton) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::EnterDoingNewButtonMenuState(IMMCButton *piMMCButton) { HRESULT hr = S_OK; long lCount = 0; ASSERT(NULL != piMMCButton, "EnterDoingNewButtonMenuState: piMMCButton is NULL"); // Bump up the current button index to keep matters in sync. ++m_lCurrentButtonMenuIndex; hr = SetDlgText(IDC_EDIT_TB_MENU_INDEX, m_lCurrentButtonMenuIndex); IfFailGo(hr); // We disable the InsertButton, RemoveButton, and RemoveButtonMenu buttons. // The InsertButton button remains enabled and acts like an "Apply and New" button //::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_INSERT_BUTTON), FALSE); //::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_REMOVE_BUTTON), FALSE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_REMOVE_BUTTON_MENU), FALSE); hr = EnableButtonMenuEdits(true); IfFailGo(hr); hr = ClearButtonMenu(); IfFailGo(hr); m_bSavedLastButtonMenu = FALSE; Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::CanCreateNewButtonMenu() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::CanCreateNewButtonMenu() { return S_OK; } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::CreateNewButtonMenu(IMMCButton *piMMCButton) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::CreateNewButtonMenu(IMMCButton *piMMCButton, IMMCButtonMenu **ppiMMCButtonMenu) { HRESULT hr = S_OK; IMMCButtonMenus *piMMCButtonMenus = NULL; VARIANT varIndex; BSTR bstrKey = NULL; VARIANT vtKey; BSTR bstrText = NULL; VARIANT vtText; ::VariantInit(&varIndex); ::VariantInit(&vtKey); ::VariantInit(&vtText); hr = piMMCButton->get_ButtonMenus(reinterpret_cast<MMCButtonMenus **>(&piMMCButtonMenus)); IfFailGo(hr); varIndex.vt = VT_I4; varIndex.lVal = m_lCurrentButtonMenuIndex; hr = GetDlgText(IDC_EDIT_TB_MENU_KEY, &bstrKey); IfFailGo(hr); if (NULL != bstrKey && ::SysStringLen(bstrKey) > 0) { vtKey.vt = VT_BSTR; vtKey.bstrVal = ::SysAllocString(bstrKey); if (NULL == vtKey.bstrVal) { hr = SID_E_OUTOFMEMORY; EXCEPTION_CHECK_GO(hr); } } else { vtKey.vt = VT_ERROR; vtKey.scode = DISP_E_PARAMNOTFOUND; } hr = GetDlgText(IDC_EDIT_TB_MENU_TEXT, &bstrText); IfFailGo(hr); vtText.vt = VT_BSTR; vtText.bstrVal = ::SysAllocString(bstrText); if (NULL == vtText.bstrVal) { hr = SID_E_OUTOFMEMORY; EXCEPTION_CHECK_GO(hr); } hr = piMMCButtonMenus->Add(varIndex, vtKey, vtText, reinterpret_cast<MMCButtonMenu **>(ppiMMCButtonMenu)); IfFailGo(hr); Error: ::VariantClear(&vtText); FREESTRING(bstrText); ::VariantClear(&vtKey); FREESTRING(bstrKey); ::VariantClear(&varIndex); RELEASE(piMMCButtonMenus); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::ExitDoingNewButtonMenuState(IMMCButton *piMMCButton, IMMCButtonMenu *piMMCButtonMenu) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::ExitDoingNewButtonMenuState(IMMCButton *piMMCButton, IMMCButtonMenu *piMMCButtonMenu) { HRESULT hr = S_OK; ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_INSERT_BUTTON), TRUE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_REMOVE_BUTTON), TRUE); ::EnableWindow(::GetDlgItem(m_hwnd, IDC_BUTTON_REMOVE_BUTTON_MENU), TRUE); m_bSavedLastButtonMenu = true; //Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::GetCurrentButton(IMMCButton **ppiMMCButton) //=-------------------------------------------------------------------------------------- // // Notes // // Returns: S_OK - button found and returned in *ppiMMCButton // S_FALSE - button not found, *ppiMMCButton=NULL // HRESULT CToolbarButtonsPage::GetCurrentButton(IMMCButton **ppiMMCButton) { HRESULT hr = S_OK; IMMCButtons *piMMCButtons = NULL; VARIANT varIndex; ::VariantInit(&varIndex); *ppiMMCButton = NULL; ASSERT(NULL != m_piMMCToolbar, "GetCurrentButton: m_piMMCToolbar is NULL"); if (m_lCurrentButtonIndex > 0) { hr = m_piMMCToolbar->get_Buttons(reinterpret_cast<MMCButtons **>(&piMMCButtons)); IfFailGo(hr); varIndex.vt = VT_I4; varIndex.lVal = m_lCurrentButtonIndex; hr = piMMCButtons->get_Item(varIndex, reinterpret_cast<MMCButton **>(ppiMMCButton)); if (SID_E_INDEX_OUT_OF_RANGE == hr) { // User did Insert Button but has not yet applied so it it not // in the collection. hr = S_FALSE; } IfFailGo(hr); } else { hr = S_FALSE; } Error: RELEASE(piMMCButtons); ::VariantClear(&varIndex); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::GetCurrentButtonMenu(IMMCButton *piMMCButton, IMMCButtonMenu **ppiMMCButtonMenu) //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::GetCurrentButtonMenu(IMMCButton *piMMCButton, IMMCButtonMenu **ppiMMCButtonMenu) { HRESULT hr = S_OK; IMMCButtonMenus *piMMCButtonMenus = NULL; VARIANT varIndex; ASSERT(NULL != piMMCButton, "GetCurrentButton: piMMCButton is NULL"); ::VariantInit(&varIndex); if (m_lCurrentButtonMenuIndex > 0) { hr = piMMCButton->get_ButtonMenus(reinterpret_cast<MMCButtonMenus **>(&piMMCButtonMenus)); IfFailGo(hr); varIndex.vt = VT_I4; varIndex.lVal = m_lCurrentButtonMenuIndex; hr = piMMCButtonMenus->get_Item(varIndex, reinterpret_cast<MMCButtonMenu **>(ppiMMCButtonMenu)); IfFailGo(hr); } Error: RELEASE(piMMCButtonMenus); ::VariantClear(&varIndex); RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::OnDestroy() //=-------------------------------------------------------------------------------------- // // Notes // HRESULT CToolbarButtonsPage::OnDestroy() { HRESULT hr = S_OK; IfFailGo(CheckButtonStyles()); Error: RRETURN(hr); } //=-------------------------------------------------------------------------------------- // CToolbarButtonsPage::CheckButtonStyles() //=-------------------------------------------------------------------------------------- // // Notes // // Checks that all buttons are either dropdown or something else as MMC does not // allow mixing toolbar buttons and menu buttons. If styles are not consistent // displays message telling user to fix it up before running the snap-in or a // runtime error will occur. // HRESULT CToolbarButtonsPage::CheckButtonStyles() { HRESULT hr = S_OK; long cButtons = 0; SnapInButtonStyleConstants Style = siDefault; SnapInButtonStyleConstants LastStyle = siDefault; IMMCButtons *piMMCButtons = NULL; IMMCButton *piMMCButton = NULL; VARIANT varIndex; ::VariantInit(&varIndex); IfFailGo(m_piMMCToolbar->get_Buttons(reinterpret_cast<MMCButtons **>(&piMMCButtons))); IfFailGo(piMMCButtons->get_Count(&cButtons)); varIndex.vt = VT_I4; for (varIndex.lVal = 1L; varIndex.lVal <= cButtons; varIndex.lVal++) { IfFailGo(piMMCButtons->get_Item(varIndex, reinterpret_cast<MMCButton **>(&piMMCButton))); IfFailGo(piMMCButton->get_Style(&Style)); if (varIndex.lVal != 1L) { if (siDropDown == Style) { if (siDropDown != LastStyle) { hr = SID_E_TOOLBAR_INCONSISTENT; goto Error; } } else // This button is not drop-down { if (siDropDown == LastStyle) { hr = SID_E_TOOLBAR_INCONSISTENT; goto Error; } } } LastStyle = Style; RELEASE(piMMCButton); } Error: if (SID_E_TOOLBAR_INCONSISTENT == hr) { HandleError("Toolbar Definition Inconsistent", "A toolbar's buttons must all be drop-down style or all must be something else. MMC does not allow mixing toolbar buttons and menu buttons within a toolbar. If you do not make the styles consistent before running your snap-in the toolbar will not appear."); } QUICK_RELEASE(piMMCButtons); QUICK_RELEASE(piMMCButton); RRETURN(hr); }
29.026184
313
0.524184
npocmaka
023db6b22b9a28d346cbb2f1953bc3307b8e2a74
624
hpp
C++
raisim/win32/mt_release/include/raisim/constraints/StiffLengthConstraint.hpp
simRepoRelease/raisimLib
00724ac2abb0b4c11aadb4ddd3455fc42c57a34e
[ "Apache-2.0" ]
142
2020-10-21T18:18:13.000Z
2022-03-29T11:49:25.000Z
raisim/win32/mt_release/include/raisim/constraints/StiffLengthConstraint.hpp
simRepoRelease/raisimLib
00724ac2abb0b4c11aadb4ddd3455fc42c57a34e
[ "Apache-2.0" ]
192
2020-10-21T15:51:15.000Z
2022-03-28T12:56:01.000Z
raisim/win32/mt_release/include/raisim/constraints/StiffLengthConstraint.hpp
simRepoRelease/raisimLib
00724ac2abb0b4c11aadb4ddd3455fc42c57a34e
[ "Apache-2.0" ]
51
2020-10-26T08:29:54.000Z
2022-03-23T12:00:23.000Z
//----------------------------// // This file is part of RaiSim// // Copyright 2020, RaiSim Tech// //----------------------------// #ifndef RAISIM_STIFFWIRE_HPP #define RAISIM_STIFFWIRE_HPP #include "LengthConstraint.hpp" namespace raisim { class StiffLengthConstraint : public LengthConstraint { public: StiffLengthConstraint(Object* obj1, size_t localIdx1, Vec<3> pos1_b, Object* obj2, size_t localIdx2, Vec<3> pos2_b, double length); virtual ~StiffLengthConstraint() = default; protected: void applyTension(contact::ContactProblems& contact_problems) final; private: }; } #endif //RAISIM_STIFFWIRE_HPP
21.517241
133
0.689103
simRepoRelease
023f04b5d143edd11c52d56b5ab6e1297a7fe7ba
6,666
cpp
C++
src/transaction/transactors/SetREL.cpp
hawx1993/truechain-testnet-core
a75edfe83562b3764fb3140144bc41943ebb995a
[ "MIT" ]
null
null
null
src/transaction/transactors/SetREL.cpp
hawx1993/truechain-testnet-core
a75edfe83562b3764fb3140144bc41943ebb995a
[ "MIT" ]
null
null
null
src/transaction/transactors/SetREL.cpp
hawx1993/truechain-testnet-core
a75edfe83562b3764fb3140144bc41943ebb995a
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------ /* Copyright (c) 2012, 2013 Skywell Labs Inc. Copyright (c) 2017-2018 TrueChain Foundation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <BeastConfig.h> #include <transaction/book/Quality.h> #include <transaction/transactors/Transactor.h> #include <common/base/Log.h> #include <protocol/Indexes.h> #include <protocol/TxFlags.h> namespace truechain { class SetREL : public Transactor { public: SetREL ( STTx const& txn, TransactionEngineParams params, TransactionEngine* engine) : Transactor ( txn, params, engine, deprecatedLogs().journal("SetREL")) { } TER preCheck () override { std::uint32_t const uTxFlags = mTxn.getFlags (); if (uTxFlags & tfRelationSetMask) { m_journal.trace << "Malformed transaction: Invalid flags set."; return temINVALID_FLAG; } STAmount const saLimitAmount (mTxn.getFieldAmount (sfLimitAmount)); if (!isLegalNet (saLimitAmount)) return temBAD_AMOUNT; if (saLimitAmount.isNative ()) { if (m_journal.trace) m_journal.trace << "Malformed transaction: specifies native limit " << saLimitAmount.getFullText (); return temBAD_LIMIT; } if (badCurrency() == saLimitAmount.getCurrency ()) { if (m_journal.trace) m_journal.trace << "Malformed transaction: specifies SWT as IOU"; return temBAD_CURRENCY; } if (saLimitAmount < zero) { if (m_journal.trace) m_journal.trace << "Malformed transaction: Negative credit limit."; return temBAD_LIMIT; } // Check if destination makes sense. auto const& issuer = saLimitAmount.getIssuer (); if (!issuer || issuer == noAccount()) { if (m_journal.trace) m_journal.trace << "Malformed transaction: no destination account."; return temDST_NEEDED; } return Transactor::preCheck (); } TER doApply () override { TER terResult = tesSUCCESS; std::uint32_t const uRelationType = mTxn.getFieldU32 (sfRelationType); STAmount const saLimitAmount (mTxn.getFieldAmount (sfLimitAmount)); bool const bQualityIn (mTxn.isFieldPresent (sfQualityIn)); bool const bQualityOut (mTxn.isFieldPresent (sfQualityOut)); Currency const currency (saLimitAmount.getCurrency ()); Account uIssuerID (saLimitAmount.getIssuer ()); Account uDstAccountID (mTxn.getFieldAccount160 (sfTarget)); // true, iff current is high account. bool const bHigh = mTxnAccountID > uDstAccountID; std::uint32_t uQualityIn (bQualityIn ? mTxn.getFieldU32 (sfQualityIn) : 0); std::uint32_t uQualityOut (bQualityOut ? mTxn.getFieldU32 (sfQualityOut) : 0); if (bQualityOut && QUALITY_ONE == uQualityOut) uQualityOut = 0; SLE::pointer sleDst (mEngine->view().entryCache ( ltACCOUNT_ROOT, getAccountRootIndex (uDstAccountID))); if (!sleDst) { m_journal.trace << "Delay transaction: Destination account does not exist."; return tecNO_DST; } STAmount saLimitAllow = saLimitAmount; saLimitAllow.setIssuer (mTxnAccountID); SLE::pointer sleSkywellState (mEngine->view().entryCache (ltTrust_STATE, getTrustStateIndex (mTxnAccountID, uDstAccountID,uRelationType,uIssuerID, currency))); if (mTxn.getTxnType () == ttREL_DEL && sleSkywellState) { return mEngine->view ().trustDelete ( sleSkywellState, mTxnAccountID, uDstAccountID); } if (!sleSkywellState && mTxn.getTxnType () == ttREL_SET) { // Zero balance in currency. // STAmount saBalance ({currency, noAccount()}); STAmount saBalance ({currency, uIssuerID}); uint256 index (getTrustStateIndex ( mTxnAccountID, uDstAccountID,uRelationType,uIssuerID, currency)); m_journal.trace << "doRelationSet: Creating rep line: " << to_string (index); // Create a new skywell line. terResult = mEngine->view ().relationCreate ( bHigh, mTxnAccountID, uDstAccountID, index, mTxnAccount, saBalance, saLimitAllow, // Limit for who is being charged. uQualityIn, uQualityOut); if(terResult == tesSUCCESS) { SLE::pointer sleSkywellState (mEngine->view().entryCache (ltTrust_STATE, getTrustStateIndex (mTxnAccountID, uDstAccountID,uRelationType,uIssuerID, currency))); sleSkywellState->setFieldU32 (sfRelationType, uRelationType); mEngine->view().entryModify (sleSkywellState); } } else if(sleSkywellState && mTxn.getTxnType () == ttREL_SET) { // // Limits // sleSkywellState->setFieldAmount (!bHigh ? sfLowLimit : sfHighLimit, saLimitAllow); mEngine->view().entryModify (sleSkywellState); m_journal.trace << "Modify trust line"; } return terResult; } }; TER transact_SetREL ( STTx const& txn, TransactionEngineParams params, TransactionEngine* engine) { return SetREL (txn, params, engine).apply (); } }
33.33
100
0.581458
hawx1993
02453a9c5f55e1e5df7a191a9c251533ef2e9fb6
6,259
cpp
C++
KRender/Internal/KConstantDefinition.cpp
King19931229/KApp
f7f855b209348f835de9e5f57844d4fb6491b0a1
[ "MIT" ]
13
2019-10-19T17:41:19.000Z
2021-11-04T18:50:03.000Z
KRender/Internal/KConstantDefinition.cpp
King19931229/KApp
f7f855b209348f835de9e5f57844d4fb6491b0a1
[ "MIT" ]
3
2019-12-09T06:22:43.000Z
2020-05-28T09:33:44.000Z
KRender/Internal/KConstantDefinition.cpp
King19931229/KApp
f7f855b209348f835de9e5f57844d4fb6491b0a1
[ "MIT" ]
null
null
null
#include "KConstantDefinition.h" namespace KConstantDefinition { static ConstantBufferDetail CAMERA_DETAILS; static ConstantBufferDetail SHADOW_DETAILS; static ConstantBufferDetail CASCADED_SHADOW_DETAILS; static ConstantBufferDetail GLOBAL_DETAILS; static ConstantBufferDetail VOXEL_DETAILS; static ConstantBufferDetail EMPYT_DETAILS; void SafeInit() { static bool CONSTANT_DETAIL_INIT = false; if(!CONSTANT_DETAIL_INIT) { // CAMERA { // VIEW { ConstantSemanticDetail DETAIL = { CS_VIEW, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(CAMERA, VIEW), MEMBER_OFFSET(CAMERA, VIEW) }; CAMERA_DETAILS.semanticDetails.push_back(DETAIL); } // PROJ { ConstantSemanticDetail DETAIL = { CS_PROJ, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(CAMERA, PROJ), MEMBER_OFFSET(CAMERA, PROJ) }; CAMERA_DETAILS.semanticDetails.push_back(DETAIL); } // VIEW_INV { ConstantSemanticDetail DETAIL = { CS_VIEW_INV, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(CAMERA, VIEW_INV), MEMBER_OFFSET(CAMERA, VIEW_INV) }; CAMERA_DETAILS.semanticDetails.push_back(DETAIL); } // PROJ_INV { ConstantSemanticDetail DETAIL = { CS_PROJ_INV, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(CAMERA, PROJ_INV), MEMBER_OFFSET(CAMERA, PROJ_INV) }; CAMERA_DETAILS.semanticDetails.push_back(DETAIL); } // VIEW_PROJ { ConstantSemanticDetail DETAIL = { CS_VIEW_PROJ, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(CAMERA, VIEW_PROJ), MEMBER_OFFSET(CAMERA, VIEW_PROJ) }; CAMERA_DETAILS.semanticDetails.push_back(DETAIL); } // PREV_VIEW_PROJ { ConstantSemanticDetail DETAIL = { CS_PREV_VIEW_PROJ, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(CAMERA, PREV_VIEW_PROJ), MEMBER_OFFSET(CAMERA, PREV_VIEW_PROJ) }; CAMERA_DETAILS.semanticDetails.push_back(DETAIL); } // PARAMETERS { ConstantSemanticDetail DETAIL = { CS_CAMERA_PARAMETERS, EF_R32G32B32A32_FLOAT, 1, MEMBER_SIZE(CAMERA, PARAMETERS), MEMBER_OFFSET(CAMERA, PARAMETERS) }; CAMERA_DETAILS.semanticDetails.push_back(DETAIL); } CAMERA_DETAILS.bufferSize = sizeof(CAMERA); } // SHADOW { // LIGHT_VIEW { ConstantSemanticDetail DETAIL = { CS_SHADOW_VIEW, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(SHADOW, LIGHT_VIEW), MEMBER_OFFSET(SHADOW, LIGHT_VIEW) }; SHADOW_DETAILS.semanticDetails.push_back(DETAIL); } // LIGHT_PROJ { ConstantSemanticDetail DETAIL = { CS_SHADOW_PROJ, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(SHADOW, LIGHT_PROJ), MEMBER_OFFSET(SHADOW, LIGHT_PROJ) }; SHADOW_DETAILS.semanticDetails.push_back(DETAIL); } // CAM_NEAR_FAR { ConstantSemanticDetail DETAIL = { CS_SHADOW_CAMERA_PARAMETERS, EF_R32G32B32A32_FLOAT, 1, MEMBER_SIZE(SHADOW, PARAMETERS), MEMBER_OFFSET(SHADOW, PARAMETERS) }; SHADOW_DETAILS.semanticDetails.push_back(DETAIL); } SHADOW_DETAILS.bufferSize = sizeof(SHADOW); } // CASCADED_SHADOW_DETAILS { // LIGHT_VIEW { ConstantSemanticDetail DETAIL = { CS_CASCADED_SHADOW_VIEW, EF_R32G32B32A32_FLOAT, 4 * 4, MEMBER_SIZE(CASCADED_SHADOW, LIGHT_VIEW), MEMBER_OFFSET(CASCADED_SHADOW, LIGHT_VIEW) }; CASCADED_SHADOW_DETAILS.semanticDetails.push_back(DETAIL); } // LIGHT_VIEW_PROJ { ConstantSemanticDetail DETAIL = { CS_CASCADED_SHADOW_VIEW_PROJ, EF_R32G32B32A32_FLOAT, 4 * 4, MEMBER_SIZE(CASCADED_SHADOW, LIGHT_VIEW_PROJ), MEMBER_OFFSET(CASCADED_SHADOW, LIGHT_VIEW_PROJ) }; CASCADED_SHADOW_DETAILS.semanticDetails.push_back(DETAIL); } // LIGHT_INFO { ConstantSemanticDetail DETAIL = { CS_CASCADED_SHADOW_LIGHT_INFO, EF_R32G32B32A32_FLOAT, 4, MEMBER_SIZE(CASCADED_SHADOW, LIGHT_INFO), MEMBER_OFFSET(CASCADED_SHADOW, LIGHT_INFO) }; CASCADED_SHADOW_DETAILS.semanticDetails.push_back(DETAIL); } // FRUSTUM { ConstantSemanticDetail DETAIL = { CS_CASCADED_SHADOW_FRUSTUM, EF_R32_FLOAT, 4, MEMBER_SIZE(CASCADED_SHADOW, FRUSTUM), MEMBER_OFFSET(CASCADED_SHADOW, FRUSTUM) }; CASCADED_SHADOW_DETAILS.semanticDetails.push_back(DETAIL); } // NUM_CASCADED { ConstantSemanticDetail DETAIL = { CS_CASCADED_SHADOW_NUM_CASCADED, EF_R32_UINT, 1, MEMBER_SIZE(CASCADED_SHADOW, NUM_CASCADED), MEMBER_OFFSET(CASCADED_SHADOW, NUM_CASCADED) }; CASCADED_SHADOW_DETAILS.semanticDetails.push_back(DETAIL); } CASCADED_SHADOW_DETAILS.bufferSize = sizeof(CASCADED_SHADOW); } // VOXEL_DETAILS { // VIEW_PROJ { ConstantSemanticDetail DETAIL = { CS_VOXEL_VIEW_PROJ, EF_R32G32B32A32_FLOAT, 4 * 3, MEMBER_SIZE(VOXEL, VIEW_PROJ), MEMBER_OFFSET(VOXEL, VIEW_PROJ) }; VOXEL_DETAILS.semanticDetails.push_back(DETAIL); } // VIEW_PROJ_INV { ConstantSemanticDetail DETAIL = { CS_VOXEL_VIEW_PROJ_INV, EF_R32G32B32A32_FLOAT, 4 * 3, MEMBER_SIZE(VOXEL, VIEW_PROJ_INV), MEMBER_OFFSET(VOXEL, VIEW_PROJ_INV) }; VOXEL_DETAILS.semanticDetails.push_back(DETAIL); } // MIDPOINT_SCALE { ConstantSemanticDetail DETAIL = { CS_VOXEL_MIDPOINT_SCALE, EF_R32G32B32A32_FLOAT, 1, MEMBER_SIZE(VOXEL, MIDPOINT_SCALE), MEMBER_OFFSET(VOXEL, MIDPOINT_SCALE) }; VOXEL_DETAILS.semanticDetails.push_back(DETAIL); } // MISCS { ConstantSemanticDetail DETAIL = { CS_VOXEL_MISCS, EF_R32_UINT, 4, MEMBER_SIZE(VOXEL, MISCS), MEMBER_OFFSET(VOXEL, MISCS) }; VOXEL_DETAILS.semanticDetails.push_back(DETAIL); } VOXEL_DETAILS.bufferSize = sizeof(VOXEL); } // GLOBAL { // SUN_LIGHT_DIR { ConstantSemanticDetail DETAIL = { CS_SUN_LIGHT_DIRECTION, EF_R32G32B32A32_FLOAT, 1, MEMBER_SIZE(GLOBAL, SUN_LIGHT_DIR), MEMBER_OFFSET(GLOBAL, SUN_LIGHT_DIR) }; GLOBAL_DETAILS.semanticDetails.push_back(DETAIL); } GLOBAL_DETAILS.bufferSize = sizeof(GLOBAL); } CONSTANT_DETAIL_INIT = true; } } const ConstantBufferDetail& GetConstantBufferDetail(ConstantBufferType bufferType) { SafeInit(); switch (bufferType) { case CBT_CAMERA: return CAMERA_DETAILS; case CBT_SHADOW: return SHADOW_DETAILS; case CBT_CASCADED_SHADOW: return CASCADED_SHADOW_DETAILS; case CBT_VOXEL: return VOXEL_DETAILS; case CBT_GLOBAL: return GLOBAL_DETAILS; default: assert(false && "Unknown ConstantBufferType"); return EMPYT_DETAILS; } } }
37.479042
196
0.743569
King19931229
02463ee3cc7e4690157dbd368464b97456f7ada8
5,987
hpp
C++
src/QDMEwald/src/kokkos_linalg.hpp
fossabot/xtp
e82cc53f23e213d09da15da80ada6e32ac031a07
[ "Apache-2.0" ]
null
null
null
src/QDMEwald/src/kokkos_linalg.hpp
fossabot/xtp
e82cc53f23e213d09da15da80ada6e32ac031a07
[ "Apache-2.0" ]
null
null
null
src/QDMEwald/src/kokkos_linalg.hpp
fossabot/xtp
e82cc53f23e213d09da15da80ada6e32ac031a07
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Forschungszentrum Juelich GmbH * Copyright 2020 The VOTCA Development Team * (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License") * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #pragma once #ifndef VOTCA_XTP_KOKKOS_LINALG_PRIVATE_H #define VOTCA_XTP_KOKKOS_LINALG_PRIVATE_H // Standard includes #include <cmath> // Third party includes #include <Kokkos_Core.hpp> namespace kokkos_linalg_3d { template <class T> int size(const T& vector) { return int(vector.size()); } template <class T> int size(const Kokkos::View<T>& vector) { return int(vector.extent(0)); } template <class Vector1, class Vector2> std::array<typename Vector1::value_type, 3> cross(const Vector1& x, const Vector2& y) { std::array<typename Vector1::value_type, 3> result; assert(size(x) == size(y) && "Dimensions of vectors do not match!"); assert(size(x) == 3 && "Only three dimensions allowed"); result[0] = x[1] * y[2] - x[2] * y[1]; result[1] = x[2] * y[0] - x[0] * y[2]; result[2] = x[0] * y[1] - x[1] * y[0]; return result; } template <class Vector1, class Vector2> typename Vector1::value_type dot(const Vector1& x, const Vector2& y) { assert(size(x) == size(y) && "Dimensions of arrays do not match!"); typename Vector1::value_type result = 0.0; for (auto i = 0; i < size(x); i++) { result += x[i] * y[i]; } return result; } template <class Vector> typename Vector::value_type norm(const Vector& x) { return std::sqrt(dot(x, x)); } template <class Matrix, class Vector> std::array<typename Matrix::value_type, 3> gemv(const Matrix& A, const Vector& x) { assert(size(x) == 3 && "Only three dimensions allowed"); assert(size(A) == 9 && "Only 3x3 dimensions allowed"); std::array<typename Matrix::value_type, 3> result; result[0] = A[0] * x[0] + A[1] * x[1] + A[2] * x[2]; result[1] = A[3] * x[0] + A[4] * x[1] + A[5] * x[2]; result[2] = A[6] * x[0] + A[7] * x[1] + A[8] * x[2]; return result; } // eqn 21 in Smith Point Multipoles in Ewald Summation(Revisited) // generalized cross product template <class Matrix1, class Matrix2> std::array<typename Matrix1::value_type, 3> cross_matrix_product( const Matrix1& A, const Matrix2& B) { assert(size(A) == size(B) && "Dimensions of vectors do not match!"); assert(size(A) == 9 && "Only 3x3 dimensions allowed"); std::array<typename Matrix1::value_type, 3> result; result[0] = A[3] * B[6] + A[4] * B[7] + A[5] * B[8] - A[6] * B[3] - A[7] * B[4] - A[8] * B[5]; result[1] = A[6] * B[0] + A[7] * B[1] + A[8] * B[2] - A[0] * B[6] - A[1] * B[7] - A[2] * B[8]; result[2] = A[0] * B[3] + A[1] * B[4] + A[2] * B[5] - A[3] * B[0] - A[4] * B[1] - A[5] * B[2]; return result; } template <class Matrix> typename Matrix::value_type trace(const Matrix& A) { assert(size(A) == 9 && "Only 3x3 dimensions allowed"); return A[0] + A[4] + A[8]; } template <class Vector> typename std::array<typename Vector::value_type, 3> scale_3d( const typename Vector::value_type s, const Vector& v) { assert(size(v) == 3 && "Dimension must be 3"); std::array<typename Vector::value_type, 3> result; for (int i = 0; i < 3; ++i) result[i] = s * v[i]; return result; } template <class Vector> typename std::array<std::array<typename Vector::value_type, 3>, 3> dualbase_3d( const Vector& a, const Vector& b, const Vector& c) { assert(size(a) == size(b) && "Dimensions of vector a and b do not match"); assert(size(b) == size(c) && "Dimensions of vector b and c do not match"); assert(size(a) == 3 && "Dimension must be 3"); std::array<std::array<typename Vector::value_type, 3>, 3> result; typename Vector::value_type V = dot(a, cross(b, c)); typename Vector::value_type V_inv = 1.0 / V; result[0] = scale_3d(V_inv, cross(b, c)); result[1] = scale_3d(V_inv, cross(c, a)); result[2] = scale_3d(V_inv, cross(a, b)); return result; } template <class Vector1, class Vector2> void add_to(Vector1& a, const Vector2& b) { assert(size(a) == size(b) && "Dimensions of vector a and b do not match"); for (int i = 0; i < size(a); i++) { a[i] += b[i]; } return; } template <class Vector1, class Vector2> void subtract_from(Vector1& a, const Vector2& b) { assert(size(a) == size(b) && "Dimensions of vector a and b do not match"); for (int i = 0; i < size(a); i++) { a[i] -= b[i]; } return; } template <class Vector1, class Vector2> typename std::array<typename Vector1::value_type, 3> add(const Vector1& a, const Vector2& b) { assert(size(a) == size(b) && "Dimensions of vector a and b do not match"); assert(size(a) == 3 && "Dimension must be 3"); std::array<typename Vector1::value_type, 3> result; for (int i = 0; i < size(a); i++) { result[i] = a[i] + b[i]; } return result; } template <class Vector1, class Vector2> typename std::array<typename Vector1::value_type, 3> subtract( const Vector1& a, const Vector2& b) { assert(size(a) == size(b) && "Dimensions of vector a and b do not match"); assert(size(a) == 3 && "Dimension must be 3"); std::array<typename Vector1::value_type, 3> result; for (int i = 0; i < size(a); i++) { result[i] = a[i] - b[i]; } return result; } } // namespace kokkos_linalg_3d #endif // VOTCA_XTP_KOKKOS_LINALG_PRIVATE_H
33.261111
79
0.614665
fossabot
0246f016c86ddd1b481370923aba444454513ec4
1,671
cpp
C++
TAO/tao/DiffServPolicy/DiffServ_Service_Context_Handler.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tao/DiffServPolicy/DiffServ_Service_Context_Handler.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tao/DiffServPolicy/DiffServ_Service_Context_Handler.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: DiffServ_Service_Context_Handler.cpp 95623 2012-03-20 11:46:15Z sma $ #include "tao/DiffServPolicy/DiffServ_Service_Context_Handler.h" #include "tao/DiffServPolicy/Client_Network_Priority_Policy.h" #include "tao/CDR.h" #include "tao/TAO_Server_Request.h" #include "tao/Transport.h" #include "tao/ORB_Core.h" #include "tao/GIOP_Message_Base.h" #include "tao/operation_details.h" #include "tao/Transport_Mux_Strategy.h" #include "tao/Stub.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL int TAO_DiffServ_Service_Context_Handler::process_service_context ( TAO_Transport&, const IOP::ServiceContext&, TAO_ServerRequest *) { return 0; } int TAO_DiffServ_Service_Context_Handler::generate_service_context ( TAO_Stub *stub, TAO_Transport&, TAO_Operation_Details &opdetails, TAO_Target_Specification &, TAO_OutputCDR &) { if (stub) { CORBA::Policy_var cnpp = stub->get_cached_policy (TAO_CACHED_POLICY_CLIENT_NETWORK_PRIORITY); TAO::NetworkPriorityPolicy_var cnp = TAO::NetworkPriorityPolicy::_narrow (cnpp.in ()); if (!CORBA::is_nil (cnp.in ())) { TAO::DiffservCodepoint const reply_diffserv_codepoint = cnp->reply_diffserv_codepoint (); CORBA::Long const rep_dscp_codepoint = reply_diffserv_codepoint; TAO_OutputCDR cdr; if (!(cdr << ACE_OutputCDR::from_boolean (TAO_ENCAP_BYTE_ORDER)) || !(cdr << rep_dscp_codepoint)) { throw CORBA::MARSHAL (); } opdetails.request_service_context ().set_context (IOP::REP_NWPRIORITY, cdr); } } return 0; } TAO_END_VERSIONED_NAMESPACE_DECL
26.109375
86
0.705566
cflowe
02496a9d11e2f2c402f399026afa68502c18c5b9
598
hpp
C++
irohad/model/query_response.hpp
artyom-yurin/iroha-archive
1ad3a149d21d30e99c650a9a4bad88b2792d751d
[ "Apache-2.0" ]
31
2019-04-17T19:32:05.000Z
2022-02-05T01:35:02.000Z
irohad/model/query_response.hpp
artyom-yurin/iroha-archive
1ad3a149d21d30e99c650a9a4bad88b2792d751d
[ "Apache-2.0" ]
11
2016-10-13T10:09:55.000Z
2019-06-13T08:49:11.000Z
irohad/model/query_response.hpp
artyom-yurin/iroha-archive
1ad3a149d21d30e99c650a9a4bad88b2792d751d
[ "Apache-2.0" ]
12
2019-06-03T10:31:31.000Z
2021-12-13T12:17:15.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_QUERY_RESPONSE_HPP #define IROHA_QUERY_RESPONSE_HPP #include <memory> #include "crypto/hash_types.hpp" #include "model/client.hpp" #include "model/query.hpp" namespace iroha { namespace model { /** * Interface of query response for user */ struct QueryResponse { /** * Client query */ hash256_t query_hash{}; virtual ~QueryResponse() {} }; } // namespace model } // namespace iroha #endif // IROHA_QUERY_RESPONSE_HPP
19.290323
53
0.658863
artyom-yurin
024a4d8d95c5a6b2a0db4e4836429606715b30b5
3,576
hpp
C++
Source/AllProjects/Tests2/TestCIDMData/TestCIDMData_AttrData.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
null
null
null
Source/AllProjects/Tests2/TestCIDMData/TestCIDMData_AttrData.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
null
null
null
Source/AllProjects/Tests2/TestCIDMData/TestCIDMData_AttrData.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
null
null
null
// // FILE NAME: TestCIDMData_AttrData.hpp // // AUTHOR: Dean Roddey // // CREATED: 08/07/2018 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // The header for the attribute data tests. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // // --------------------------------------------------------------------------- // CLASS: TTest_AttrDataBasic // PREFIX: tfwt // --------------------------------------------------------------------------- class TTest_AttrDataBasic : public TTestFWTest { public : // ------------------------------------------------------------------- // Constructor and Destructor // ------------------------------------------------------------------- TTest_AttrDataBasic(); ~TTest_AttrDataBasic(); // ------------------------------------------------------------------- // Public, inherited methods // ------------------------------------------------------------------- tTestFWLib::ETestRes eRunTest ( TTextStringOutStream& strmOutput , tCIDLib::TBoolean& bWarning ) final; private : // ------------------------------------------------------------------- // Private, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TBoolean bTestState ( TTextOutStream& strmOut , const TString& strTestName , const tCIDLib::TCard4 c4Line , const TAttrData& adatTest , const TString& strLimits , const tCIDMData::EAttrTypes eType , const TString& strFmtValue ); tCIDLib::TBoolean bTestState2 ( TTextOutStream& strmOut , const TString& strTestName , const tCIDLib::TCard4 c4Line , const TAttrData& adatTest , const TString& strAttrId , const TString& strSpecType , const TString& strLimits , const tCIDMData::EAttrTypes eType , const tCIDMData::EAttrEdTypes eEditType , const TString& strFmtValue ); tCIDLib::TBoolean bTestState3 ( TTextOutStream& strmOut , const TString& strTestName , const tCIDLib::TCard4 c4Line , const TAttrData& adatTest , const TString& strAttrId , const TString& strSpecType , const TString& strLimits , const tCIDMData::EAttrTypes eType , const tCIDMData::EAttrEdTypes eEditType , const TString& strFmtValue , const tCIDLib::TCard8 c8UserData , const TString& strUserData ); // ------------------------------------------------------------------- // Do any needed magic macros // ------------------------------------------------------------------- RTTIDefs(TTest_AttrDataBasic, TTestFWTest) };
34.384615
78
0.39877
MarkStega
024e35c748f5e1bf6e23fd964c2a970f67ea639d
8,227
cpp
C++
3rdparty/GPSTk/ext/lib/Rxio/AshtechMBEN.cpp
mfkiwl/ICE
e660d031bb1bcea664db1de4946fd8781be5b627
[ "MIT" ]
50
2019-10-12T01:22:20.000Z
2022-02-15T23:28:26.000Z
3rdparty/GPSTk/ext/lib/Rxio/AshtechMBEN.cpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
null
null
null
3rdparty/GPSTk/ext/lib/Rxio/AshtechMBEN.cpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
14
2019-11-05T01:50:29.000Z
2021-08-06T06:23:44.000Z
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 3.0 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= #include "AshtechMBEN.hpp" #include "AshtechStream.hpp" #include "GNSSconstants.hpp" using namespace std; namespace gpstk { const char* AshtechMBEN::mpcId = "MPC"; const char* AshtechMBEN::mcaId = "MCA"; //--------------------------------------------------------------------------- void AshtechMBEN::reallyGetRecord(FFStream& ffs) throw(std::exception, FFStreamError, EndOfFile) { AshtechStream& stream=dynamic_cast<AshtechStream&>(ffs); // make sure the object is reset before starting the search clear(fmtbit | lenbit | crcbit); string& rawData = stream.rawData; // If this object doesn't have an id set yet, assume that the streams // most recent read id is what we need to be if (id == "" && rawData.size()>=11 && rawData.substr(0,7) == preamble && rawData[10]==',') id = rawData.substr(7,3); // If that didn't work, or this is object is not of the right type, // then give up. if (id == "" || !checkId(id)) return; readBody(stream); } //--------------------------------------------------------------------------- void AshtechMBEN::decode(const std::string& data) throw(std::exception, FFStreamError) { using gpstk::BinUtils::decodeVar; string str(data); uint8_t csum=0; if (str.length() == 108 || str.length()==52) { ascii=false; header = str.substr(0,11); str.erase(0,11); seq = decodeVar<uint16_t>(str); left = decodeVar<uint8_t>(str); svprn = decodeVar<uint8_t>(str); el = decodeVar<uint8_t>(str); az = decodeVar<uint8_t>(str); chid = decodeVar<uint8_t>(str); ca.decodeBIN(str); if (id == mpcId) { p1.decodeBIN(str); p2.decodeBIN(str); } checksum = decodeVar<uint8_t>(str); clear(); int end = data.size() - 3; for (int i=11; i<end; i++) csum ^= data[i]; } else { ascii=true; header = str.substr(0,11); str.erase(0,11); stringstream iss(str); char c; iss >> seq >> c >> left >> c >> svprn >> c >> el >> c >> az >> c >> chid >> c; ca.decodeASCII(iss); if (id == mpcId) { p1.decodeASCII(iss); p2.decodeASCII(iss); } iss >> checksum; if (iss) clear(); int end=data.rfind(','); for (int i=11; i<=end; i++) csum ^= data[i]; } if (csum != checksum) { setstate(crcbit); if (debugLevel) cout << "checksum error, computed:" << hex << (uint16_t) csum << " received:" << checksum << dec << endl; } if (seq>36000) setstate(fmtbit); } //--------------------------------------------------------------------------- void AshtechMBEN::code_block::decodeASCII(stringstream& str) throw(std::exception, FFStreamError) { char c; str >> warning >> c >> goodbad >> c >> polarity_known>> c >> ireg >> c >> qa_phase >> c >> full_phase >> c >> raw_range >> c >> doppler >> c >> smoothing >> c >> smooth_cnt >> c; // The ashtech docs say this field should be in 1e-4 Hz // The data sure doesn't look like it, however //doppler *= 1e-4; raw_range *= 1e-3; //convert ms to sec } //--------------------------------------------------------------------------- void AshtechMBEN::code_block::decodeBIN(string& str) throw(std::exception, FFStreamError) { using gpstk::BinUtils::decodeVar; uint32_t smo; warning = decodeVar<uint8_t>(str); goodbad = decodeVar<uint8_t>(str); polarity_known = decodeVar<uint8_t>(str); ireg = decodeVar<uint8_t>(str); qa_phase = decodeVar<uint8_t>(str); full_phase = decodeVar<double>(str); raw_range = decodeVar<double>(str); doppler = decodeVar<int32_t>(str); smo = decodeVar<uint32_t>(str); doppler *= 1e-4; smoothing = (smo & 0x800000 ? -1e-3 : 1e-3) * (smo & 0x7fffff); smooth_cnt = (smo >> 24) & 0xff; } //--------------------------------------------------------------------------- void AshtechMBEN::code_block::dump(ostream& out) const { using gpstk::StringUtils::asString; out << hex << "warn:" << (int)warning << " gb:" << (int)goodbad << " pol:" << (int)polarity_known << dec << " ireg:" << (int)ireg << " qa:" << (int)qa_phase << " phase:" << asString(full_phase, 1) << " range:" << asString(raw_range*1e3, 3) << " doppler:" << doppler << " smo:" << smoothing << " smo_cnt:" << smooth_cnt; } //--------------------------------------------------------------------------- float AshtechMBEN::code_block::snr(float chipRate, float m) const throw() { const float n = 20000; // number of samples in 1 ms const float bw = 0.9 * chipRate; // equivalent noise bandwidth (Hz) const float d = PI/(n*n*m*m*4.0); float snr=0; // Note that ireg is as output from the MBEN which is 0-255, not the 0-99 // as displayed on the front panel. if (ireg) { snr = exp(((float)ireg)/25.0); snr = snr*snr*bw*d; snr = 10 * log10(snr); } return snr; } //--------------------------------------------------------------------------- void AshtechMBEN::dump(ostream& out) const throw() { ostringstream oss; using gpstk::StringUtils::asString; AshtechData::dump(oss); oss << getName() << "1:" << " seq:" << 0.05 * seq << " left:" << (int)left << " prn:" << (int)svprn << " el:" << (int)el << " az:" << (int)az << " chid:" << (int)chid << " " << (ascii?"ascii":"bin") << endl; oss << getName() << "2: ca "; ca.dump(oss); oss << endl; if (id == mpcId) { oss << getName() << "3: p1 "; p1.dump(oss); oss << endl; oss << getName() << "4: p2 "; p2.dump(oss); oss << endl; } out << oss.str() << flush; } } // namespace gpstk
30.025547
80
0.476601
mfkiwl
024e57bdb0089575ac829640706113b6c2366713
970
cpp
C++
source/RegistRTTR.cpp
xzrunner/visiongraph
476ea49bbf56d6a2caa062d05677e768575d7ea1
[ "MIT" ]
null
null
null
source/RegistRTTR.cpp
xzrunner/visiongraph
476ea49bbf56d6a2caa062d05677e768575d7ea1
[ "MIT" ]
null
null
null
source/RegistRTTR.cpp
xzrunner/visiongraph
476ea49bbf56d6a2caa062d05677e768575d7ea1
[ "MIT" ]
null
null
null
#define EXE_FILEPATH "visiongraph/comp_include_gen.h" #include "visiongraph/comp_regist_cfg.h" #undef EXE_FILEPATH #include <rttr/registration> #define REGIST_COMP_TYPE(type, name) \ rttr::registration::class_<visiongraph::comp::type>("vg::"#name) \ .constructor<>() \ ; #define REGIST_ENUM_ITEM(type, name, label) \ rttr::value(name, type), \ rttr::metadata(type, label) \ RTTR_REGISTRATION { rttr::registration::class_<dag::Node<vg::CompVarType>::Port>("vg::Node::Port") .property("var", &dag::Node<vg::CompVarType>::Port::var) ; rttr::registration::class_<vg::Component>("vg::Comp") .method("GetImports", &vg::Component::GetImports) .method("GetExports", &vg::Component::GetExports) ; #define EXE_FILEPATH "visiongraph/comp_rttr_gen.h" #include "visiongraph/comp_regist_cfg.h" #undef EXE_FILEPATH } namespace vg { void regist_rttr() { } }
23.658537
78
0.64433
xzrunner
0250cf74aa64e31b658e46e6a43e7457387ae8ae
1,846
cc
C++
content/renderer/render_view_fuchsia.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/render_view_fuchsia.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/render_view_fuchsia.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright (c) 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/render_view_impl.h" #include "third_party/blink/public/platform/web_font_render_style.h" namespace content { namespace { SkFontHinting RendererPreferencesToSkiaHinting( const blink::mojom::RendererPreferences& prefs) { switch (prefs.hinting) { case gfx::FontRenderParams::HINTING_NONE: return SkFontHinting::kNone; case gfx::FontRenderParams::HINTING_SLIGHT: return SkFontHinting::kSlight; case gfx::FontRenderParams::HINTING_MEDIUM: return SkFontHinting::kNormal; case gfx::FontRenderParams::HINTING_FULL: return SkFontHinting::kFull; default: NOTREACHED(); return SkFontHinting::kNormal; } } } // namespace void RenderViewImpl::UpdateFontRenderingFromRendererPrefs() { const blink::mojom::RendererPreferences& prefs = renderer_preferences_; blink::WebFontRenderStyle::SetHinting( RendererPreferencesToSkiaHinting(prefs)); blink::WebFontRenderStyle::SetAutoHint(prefs.use_autohinter); blink::WebFontRenderStyle::SetUseBitmaps(prefs.use_bitmaps); SkFontLCDConfig::SetSubpixelOrder( gfx::FontRenderParams::SubpixelRenderingToSkiaLCDOrder( prefs.subpixel_rendering)); SkFontLCDConfig::SetSubpixelOrientation( gfx::FontRenderParams::SubpixelRenderingToSkiaLCDOrientation( prefs.subpixel_rendering)); blink::WebFontRenderStyle::SetAntiAlias(prefs.should_antialias_text); blink::WebFontRenderStyle::SetSubpixelRendering( prefs.subpixel_rendering != gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE); blink::WebFontRenderStyle::SetSubpixelPositioning( prefs.use_subpixel_positioning); } } // namespace content
34.830189
73
0.766522
sarang-apps
0250d212edfdbdd165811d908620272c8b6add10
2,149
hpp
C++
src/utility/Timer.hpp
jabra98/chip8EMU
b0b4c6d78fc8d30087c06468ef037ffd17bfea46
[ "MIT" ]
6
2020-06-02T12:03:48.000Z
2021-07-05T20:52:03.000Z
src/utility/Timer.hpp
jabra98/chip8EMU
b0b4c6d78fc8d30087c06468ef037ffd17bfea46
[ "MIT" ]
null
null
null
src/utility/Timer.hpp
jabra98/chip8EMU
b0b4c6d78fc8d30087c06468ef037ffd17bfea46
[ "MIT" ]
1
2020-04-10T15:31:01.000Z
2020-04-10T15:31:01.000Z
#ifndef TIMER_HPP #define TIMER_HPP #include <chrono> #include <stdexcept> class Timer { public: enum class Type { cpu, framerate, seconds, milliseconds }; bool is_ready(Type t, long long required_rate) { if (required_rate == 0) return false; if (t == Type::cpu) { if (std::chrono::duration_cast<std::chrono::microseconds>(timer.now() - cpu_interval).count() > (1'000'000 / required_rate)) { cpu_interval = timer.now(); return true; } else return false; } else if (t==Type::framerate) { if (std::chrono::duration_cast<std::chrono::microseconds>(timer.now() - frame_interval).count() > (1'000'000 / required_rate)) { frame_interval = timer.now(); return true; } else return false; } else if (t==Type::seconds) { if (std::chrono::duration_cast<std::chrono::microseconds>(timer.now() - seconds).count() > (1'000'000 / required_rate)) { seconds = timer.now(); return true; } else return false; } else if (t==Type::milliseconds) { if (std::chrono::duration_cast<std::chrono::milliseconds>(timer.now() - milliseconds).count() > (required_rate)) { milliseconds = timer.now(); return true; } else return false; } throw std::runtime_error{"unsupported timertype"}; } private: std::chrono::time_point<std::chrono::steady_clock> milliseconds{}; std::chrono::time_point<std::chrono::steady_clock> seconds{}; std::chrono::time_point<std::chrono::steady_clock> frame_interval{}; std::chrono::time_point<std::chrono::steady_clock> cpu_interval{}; std::chrono::steady_clock timer; }; #endif // TIMER_HPP
27.202532
84
0.500233
jabra98
025334e2d5c165cb66a31173789ab578b259f7be
1,692
hpp
C++
rococo-dst/rrr/misc/dball.hpp
SJTU-IPADS/dst
897b929a692642cbf295c105d9d6e64090abb673
[ "Apache-2.0" ]
9
2020-12-17T01:59:13.000Z
2022-03-30T16:25:08.000Z
rococo-dst/rrr/misc/dball.hpp
SJTU-IPADS/dst
897b929a692642cbf295c105d9d6e64090abb673
[ "Apache-2.0" ]
1
2021-07-30T12:06:33.000Z
2021-07-31T10:16:09.000Z
rococo-dst/rrr/misc/dball.hpp
SJTU-IPADS/dst
897b929a692642cbf295c105d9d6e64090abb673
[ "Apache-2.0" ]
1
2021-08-01T13:47:07.000Z
2021-08-01T13:47:07.000Z
/** * DragonBall is an interesting abstraction of event driven * programming. Typically after you collect all dragon balls you can * call for the holy dragon and he will make your wish become true. * * DragonBall is not thread-safe for now. */ #pragma once #include <mutex> #include <functional> namespace rrr { class DragonBall { public: int64_t n_wait_ = -1; int64_t n_ready_ = 0; bool called_ = false; std::function<void(void)> wish_; // this is your wish! bool th_safe_ = false; bool auto_trigger = true; // std::mutex mtx_; DragonBall(bool th_safe = false) :th_safe_(th_safe) {} DragonBall(const int32_t n_wait, const std::function<void(void)> &wish, bool th_safe = false) : n_wait_(n_wait), wish_(wish), th_safe_(th_safe) {}; void set_wait(int64_t n_wait) { //std::lock_guard<std::mutex> guard(mtx_); n_wait_ = n_wait; } //oid collect(int64_t n) { // std::lock_guard<std::mutex> guard(mtx_); // n_ready_ += n; // if (auto_trigger) { // trigger(); // } //} // /** * delete myself after triggered. */ bool trigger() { //mtx_.lock(); n_ready_ ++; verify(n_ready_ <= n_wait_); bool ready = (n_ready_ == n_wait_); //mtx_.unlock(); if (ready) { verify(!called_); called_ = true; wish_(); delete this; } return ready; } //only allows deconstructor called by itself. private: ~DragonBall() {} }; typedef DragonBall ConcurrentDragonBall; } // namespace deptran
20.385542
68
0.567376
SJTU-IPADS
0256646db1940ee49d099786ccb4fa7b8ec9d819
3,652
cpp
C++
src/smt/smt_lookahead.cpp
vmishenev/misynth
5bd977cb32144a6d61670c874efad49982f75932
[ "MIT" ]
55
2015-08-15T22:37:02.000Z
2022-03-27T03:08:02.000Z
src/smt/smt_lookahead.cpp
ekpyron/z3
28cb13fb96c15714eb244bf05d1d7f56e84cda5e
[ "MIT" ]
16
2016-04-13T23:48:33.000Z
2020-02-02T12:38:52.000Z
src/smt/smt_lookahead.cpp
ekpyron/z3
28cb13fb96c15714eb244bf05d1d7f56e84cda5e
[ "MIT" ]
18
2015-08-11T08:37:41.000Z
2021-09-16T14:24:04.000Z
/*++ Copyright (c) 2006 Microsoft Corporation Module Name: smt_lookahead.cpp Abstract: Lookahead cuber for SMT Author: nbjorner 2019-05-27. Revision History: --*/ #include <cmath> #include "ast/ast_smt2_pp.h" #include "smt/smt_lookahead.h" #include "smt/smt_context.h" namespace smt { lookahead::lookahead(context& ctx): ctx(ctx), m(ctx.get_manager()) {} double lookahead::get_score() { double score = 0; for (clause* cp : ctx.m_aux_clauses) { unsigned nf = 0, nu = 0; bool is_taut = false; for (literal lit : *cp) { switch (ctx.get_assignment(lit)) { case l_false: if (ctx.get_assign_level(lit) > 0) { ++nf; } break; case l_true: is_taut = true; break; default: ++nu; break; } } if (!is_taut && nf > 0) { score += pow(0.5, nu); } } return score; } struct lookahead::compare { context& ctx; compare(context& ctx): ctx(ctx) {} bool operator()(bool_var v1, bool_var v2) const { return ctx.get_activity(v1) > ctx.get_activity(v2); } }; expr_ref lookahead::choose() { ctx.pop_to_base_lvl(); unsigned sz = ctx.m_bool_var2expr.size(); bool_var best_v = null_bool_var; double best_score = -1; svector<bool_var> vars; for (bool_var v = 0; v < static_cast<bool_var>(sz); ++v) { expr* b = ctx.bool_var2expr(v); if (b && ctx.get_assignment(v) == l_undef) { vars.push_back(v); } } compare comp(ctx); std::sort(vars.begin(), vars.end(), comp); unsigned nf = 0, nc = 0, ns = 0, bound = 2000; for (bool_var v : vars) { if (!ctx.bool_var2expr(v)) continue; literal lit(v, false); ctx.push_scope(); ctx.assign(lit, b_justification::mk_axiom(), true); ctx.propagate(); bool inconsistent = ctx.inconsistent(); double score1 = get_score(); ctx.pop_scope(1); if (inconsistent) { ctx.assign(~lit, b_justification::mk_axiom(), false); ctx.propagate(); ++nf; continue; } ctx.push_scope(); ctx.assign(~lit, b_justification::mk_axiom(), true); ctx.propagate(); inconsistent = ctx.inconsistent(); double score2 = get_score(); ctx.pop_scope(1); if (inconsistent) { ctx.assign(lit, b_justification::mk_axiom(), false); ctx.propagate(); ++nf; continue; } double score = score1 + score2 + 1024*score1*score2; if (score > best_score) { best_score = score; best_v = v; bound += ns; ns = 0; } ++nc; ++ns; if (ns > bound) { break; } } expr_ref result(m); if (ctx.inconsistent()) { result = m.mk_false(); } else if (best_v != null_bool_var) { result = ctx.bool_var2expr(best_v); } else { result = m.mk_true(); } return result; } }
26.852941
69
0.452903
vmishenev
025eb732d987b4fc72682018667827dc98edc763
3,199
cc
C++
chrome/renderer/renderer_histogram_snapshots.cc
zachlatta/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
1
2021-09-24T22:49:10.000Z
2021-09-24T22:49:10.000Z
chrome/renderer/renderer_histogram_snapshots.cc
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
null
null
null
chrome/renderer/renderer_histogram_snapshots.cc
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/renderer_histogram_snapshots.h" #include <ctype.h> #include "base/histogram.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/pickle.h" #include "chrome/common/render_messages.h" #include "chrome/renderer/render_process.h" #include "chrome/renderer/render_thread.h" // TODO(raman): Before renderer shuts down send final snapshot lists. RendererHistogramSnapshots::RendererHistogramSnapshots() : ALLOW_THIS_IN_INITIALIZER_LIST( renderer_histogram_snapshots_factory_(this)) { } // Send data quickly! void RendererHistogramSnapshots::SendHistograms(int sequence_number) { RenderThread::current()->message_loop()->PostTask(FROM_HERE, renderer_histogram_snapshots_factory_.NewRunnableMethod( &RendererHistogramSnapshots::UploadAllHistrograms, sequence_number)); } void RendererHistogramSnapshots::UploadAllHistrograms(int sequence_number) { StatisticsRecorder::Histograms histograms; StatisticsRecorder::GetHistograms(&histograms); HistogramPickledList pickled_histograms; for (StatisticsRecorder::Histograms::iterator it = histograms.begin(); histograms.end() != it; it++) { UploadHistrogram(**it, &pickled_histograms); } // Send the sequence number and list of pickled histograms over synchronous // IPC. RenderThread::current()->Send( new ViewHostMsg_RendererHistograms( sequence_number, pickled_histograms)); } // Extract snapshot data and then send it off the the Browser process // to save it. void RendererHistogramSnapshots::UploadHistrogram( const Histogram& histogram, HistogramPickledList* pickled_histograms) { // Get up-to-date snapshot of sample stats. Histogram::SampleSet snapshot; histogram.SnapshotSample(&snapshot); const std::string& histogram_name = histogram.histogram_name(); // Find the already sent stats, or create an empty set. LoggedSampleMap::iterator it = logged_samples_.find(histogram_name); Histogram::SampleSet* already_logged; if (logged_samples_.end() == it) { // Add new entry. already_logged = &logged_samples_[histogram.histogram_name()]; already_logged->Resize(histogram); // Complete initialization. } else { already_logged = &(it->second); // Deduct any stats we've already logged from our snapshot. snapshot.Subtract(*already_logged); } // Snapshot now contains only a delta to what we've already_logged. if (snapshot.TotalCount() > 0) { UploadHistogramDelta(histogram, snapshot, pickled_histograms); // Add new data into our running total. already_logged->Add(snapshot); } } void RendererHistogramSnapshots::UploadHistogramDelta( const Histogram& histogram, const Histogram::SampleSet& snapshot, HistogramPickledList* pickled_histograms) { DCHECK(0 != snapshot.TotalCount()); snapshot.CheckSize(histogram); std::string histogram_info = Histogram::SerializeHistogramInfo(histogram, snapshot); pickled_histograms->push_back(histogram_info); }
34.031915
79
0.754298
zachlatta
02623bf040c4c0dcbcd4295874d50adcfb8adedc
4,292
cc
C++
libartbase/base/bit_memory_region_test.cc
Paschalis/android-llvm
317f7fd4b736a0511a2273a2487915c34cf8933e
[ "Apache-2.0" ]
20
2021-06-24T16:38:42.000Z
2022-01-20T16:15:57.000Z
libartbase/base/bit_memory_region_test.cc
Paschalis/android-llvm
317f7fd4b736a0511a2273a2487915c34cf8933e
[ "Apache-2.0" ]
null
null
null
libartbase/base/bit_memory_region_test.cc
Paschalis/android-llvm
317f7fd4b736a0511a2273a2487915c34cf8933e
[ "Apache-2.0" ]
4
2021-11-03T06:01:12.000Z
2022-02-24T02:57:31.000Z
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "bit_memory_region.h" #include "gtest/gtest.h" namespace art { static void CheckBits(uint8_t* data, size_t size, uint32_t init, size_t offset, size_t length, uint32_t value) { for (size_t i = 0; i < size * kBitsPerByte; i++) { uint8_t expected = (offset <= i && i < offset + length) ? value >> (i - offset) : init; uint8_t actual = data[i / kBitsPerByte] >> (i % kBitsPerByte); EXPECT_EQ(expected & 1, actual & 1); } } TEST(BitMemoryRegion, TestVarint) { for (size_t start_bit_offset = 0; start_bit_offset <= 32; start_bit_offset++) { uint32_t values[] = { 0, 1, 11, 12, 15, 16, 255, 256, 1u << 16, 1u << 24, ~1u, ~0u }; for (uint32_t value : values) { std::vector<uint8_t> buffer; BitMemoryWriter<std::vector<uint8_t>> writer(&buffer, start_bit_offset); writer.WriteVarint(value); BitMemoryReader reader(buffer.data(), start_bit_offset); uint32_t result = reader.ReadVarint(); uint32_t upper_bound = RoundUp(MinimumBitsToStore(value), kBitsPerByte) + kVarintHeaderBits; EXPECT_EQ(writer.NumberOfWrittenBits(), reader.NumberOfReadBits()); EXPECT_EQ(value, result); EXPECT_GE(upper_bound, writer.NumberOfWrittenBits()); } } } TEST(BitMemoryRegion, TestBit) { uint8_t data[sizeof(uint32_t) * 2]; for (size_t bit_offset = 0; bit_offset < 2 * sizeof(uint32_t) * kBitsPerByte; ++bit_offset) { for (uint32_t initial_value = 0; initial_value <= 1; initial_value++) { for (uint32_t value = 0; value <= 1; value++) { // Check Store and Load with bit_offset set on the region. std::fill_n(data, sizeof(data), initial_value * 0xFF); BitMemoryRegion bmr1(MemoryRegion(&data, sizeof(data)), bit_offset, 1); bmr1.StoreBit(0, value); EXPECT_EQ(bmr1.LoadBit(0), value); CheckBits(data, sizeof(data), initial_value, bit_offset, 1, value); // Check Store and Load with bit_offset set on the methods. std::fill_n(data, sizeof(data), initial_value * 0xFF); BitMemoryRegion bmr2(MemoryRegion(&data, sizeof(data))); bmr2.StoreBit(bit_offset, value); EXPECT_EQ(bmr2.LoadBit(bit_offset), value); CheckBits(data, sizeof(data), initial_value, bit_offset, 1, value); } } } } TEST(BitMemoryRegion, TestBits) { uint8_t data[sizeof(uint32_t) * 4]; for (size_t bit_offset = 0; bit_offset < 3 * sizeof(uint32_t) * kBitsPerByte; ++bit_offset) { uint32_t mask = 0; for (size_t bit_length = 0; bit_length < sizeof(uint32_t) * kBitsPerByte; ++bit_length) { const uint32_t value = 0xDEADBEEF & mask; for (uint32_t initial_value = 0; initial_value <= 1; initial_value++) { // Check Store and Load with bit_offset set on the region. std::fill_n(data, sizeof(data), initial_value * 0xFF); BitMemoryRegion bmr1(MemoryRegion(&data, sizeof(data)), bit_offset, bit_length); bmr1.StoreBits(0, value, bit_length); EXPECT_EQ(bmr1.LoadBits(0, bit_length), value); CheckBits(data, sizeof(data), initial_value, bit_offset, bit_length, value); // Check Store and Load with bit_offset set on the methods. std::fill_n(data, sizeof(data), initial_value * 0xFF); BitMemoryRegion bmr2(MemoryRegion(&data, sizeof(data))); bmr2.StoreBits(bit_offset, value, bit_length); EXPECT_EQ(bmr2.LoadBits(bit_offset, bit_length), value); CheckBits(data, sizeof(data), initial_value, bit_offset, bit_length, value); } mask = (mask << 1) | 1; } } } } // namespace art
42.078431
98
0.657036
Paschalis
026b4f500cd2619f0f7fc036d74b2cb3c8f5edbc
6,372
cpp
C++
Engine/Threading/QueuedTask.cpp
Higami69/Leviathan
90f68f9f6e5506d6133bcefcf35c8e84f158483b
[ "BSL-1.0" ]
16
2018-12-22T02:09:05.000Z
2022-03-09T20:38:59.000Z
Engine/Threading/QueuedTask.cpp
Higami69/Leviathan
90f68f9f6e5506d6133bcefcf35c8e84f158483b
[ "BSL-1.0" ]
46
2018-04-02T11:06:01.000Z
2019-12-14T11:16:04.000Z
Engine/Threading/QueuedTask.cpp
Higami69/Leviathan
90f68f9f6e5506d6133bcefcf35c8e84f158483b
[ "BSL-1.0" ]
14
2018-04-09T02:26:15.000Z
2021-09-11T03:12:15.000Z
// ------------------------------------ // #include "QueuedTask.h" using namespace Leviathan; // ------------------------------------ // DLLEXPORT Leviathan::QueuedTask::QueuedTask(std::function<void ()> functorun) : FunctionToRun(functorun) { } DLLEXPORT Leviathan::QueuedTask::~QueuedTask(){ } // ------------------------------------ // DLLEXPORT void Leviathan::QueuedTask::RunTask(){ // Run the function // _PreFunctionRun(); FunctionToRun(); _PostFunctionRun(); } // ------------------------------------ // void Leviathan::QueuedTask::_PreFunctionRun(){ } void Leviathan::QueuedTask::_PostFunctionRun(){ } // ------------------------------------ // DLLEXPORT bool Leviathan::QueuedTask::CanBeRan(const QueuedTaskCheckValues* const checkvalues){ return true; } DLLEXPORT bool Leviathan::QueuedTask::MustBeRanBefore(int eventtypeidentifier){ return eventtypeidentifier == TASK_MUSTBERAN_BEFORE_EXIT; } DLLEXPORT bool Leviathan::QueuedTask::IsRepeating(){ return false; } // ------------------ QueuedTaskCheckValues ------------------ // Leviathan::QueuedTaskCheckValues::QueuedTaskCheckValues() : CurrentTime(Time::GetThreadSafeSteadyTimePoint()) { } // ------------------ ConditionalTask ------------------ // DLLEXPORT Leviathan::ConditionalTask::ConditionalTask( std::function<void ()> functorun, std::function<bool ()> canberuncheck) : QueuedTask(functorun), TaskCheckingFunc(canberuncheck) { } DLLEXPORT Leviathan::ConditionalTask::~ConditionalTask(){ } DLLEXPORT bool Leviathan::ConditionalTask::CanBeRan( const QueuedTaskCheckValues* const checkvalues) { return TaskCheckingFunc(); } // ------------------ ConditionalDelayedTask ------------------ // DLLEXPORT Leviathan::ConditionalDelayedTask::ConditionalDelayedTask( std::function<void ()> functorun, std::function<bool ()> canberuncheck, const MicrosecondDuration &delaytime) : QueuedTask(functorun), TaskCheckingFunc(canberuncheck), CheckingTime(Time::GetThreadSafeSteadyTimePoint()+delaytime), DelayBetweenChecks(delaytime) { } DLLEXPORT Leviathan::ConditionalDelayedTask::~ConditionalDelayedTask(){ } DLLEXPORT bool Leviathan::ConditionalDelayedTask::CanBeRan( const QueuedTaskCheckValues* const checkvalues) { // Check is it too early // if(checkvalues->CurrentTime < CheckingTime) return false; // Adjust the next check time // CheckingTime = Time::GetThreadSafeSteadyTimePoint()+DelayBetweenChecks; // Run the checking function // return TaskCheckingFunc(); } // ------------------ DelayedTask ------------------ // DLLEXPORT Leviathan::DelayedTask::DelayedTask(std::function<void ()> functorun, const MicrosecondDuration &delaytime) : QueuedTask(functorun), ExecutionTime(Time::GetThreadSafeSteadyTimePoint()+delaytime) { } DLLEXPORT Leviathan::DelayedTask::DelayedTask(std::function<void ()> functorun, const WantedClockType::time_point &executetime) : QueuedTask(functorun), ExecutionTime(executetime) { } DLLEXPORT Leviathan::DelayedTask::~DelayedTask(){ } DLLEXPORT bool Leviathan::DelayedTask::CanBeRan( const QueuedTaskCheckValues* const checkvalues) { // Check is the current time past our timestamp // return checkvalues->CurrentTime >= ExecutionTime; } // ------------------ RepeatingDelayedTask ------------------ // DLLEXPORT Leviathan::RepeatingDelayedTask::RepeatingDelayedTask( std::function<void ()> functorun, const MicrosecondDuration &bothdelays) : DelayedTask(functorun, bothdelays), TimeBetweenExecutions(bothdelays), ShouldRunAgain(true) { } DLLEXPORT Leviathan::RepeatingDelayedTask::RepeatingDelayedTask( std::function<void ()> functorun, const MicrosecondDuration &initialdelay, const MicrosecondDuration &followingduration) : DelayedTask(functorun, initialdelay), TimeBetweenExecutions(followingduration), ShouldRunAgain(true) { } DLLEXPORT Leviathan::RepeatingDelayedTask::~RepeatingDelayedTask(){ } DLLEXPORT bool Leviathan::RepeatingDelayedTask::IsRepeating(){ return ShouldRunAgain; } DLLEXPORT void Leviathan::RepeatingDelayedTask::SetRepeatStatus(bool newvalue){ ShouldRunAgain = newvalue; } void Leviathan::RepeatingDelayedTask::_PostFunctionRun(){ // Set new execution point in time // ExecutionTime = Time::GetThreadSafeSteadyTimePoint()+TimeBetweenExecutions; } // ------------------ RepeatCountedTask ------------------ // DLLEXPORT Leviathan::RepeatCountedTask::RepeatCountedTask(std::function<void ()> functorun, size_t repeatcount) : QueuedTask(functorun), MaxRepeats(repeatcount), RepeatedCount(0) { } DLLEXPORT Leviathan::RepeatCountedTask::~RepeatCountedTask(){ } DLLEXPORT bool Leviathan::RepeatCountedTask::IsRepeating(){ // Increment count and see if there are still repeats left // return ++RepeatedCount < MaxRepeats; } DLLEXPORT void Leviathan::RepeatCountedTask::StopRepeating(){ // This should do the trick // MaxRepeats = 0; } DLLEXPORT size_t Leviathan::RepeatCountedTask::GetRepeatCount() const { return RepeatedCount; } DLLEXPORT bool Leviathan::RepeatCountedTask::IsThisLastRepeat() const{ return RepeatedCount + 1 >= MaxRepeats; } // ------------------ RepeatCountedDelayedTask ------------------ // DLLEXPORT Leviathan::RepeatCountedDelayedTask::RepeatCountedDelayedTask( std::function<void ()> functorun, const MicrosecondDuration &bothdelays, int repeatcount) : RepeatCountedTask(functorun, repeatcount), TimeBetweenExecutions(bothdelays), ExecutionTime(Time::GetThreadSafeSteadyTimePoint() + bothdelays) { } DLLEXPORT Leviathan::RepeatCountedDelayedTask::RepeatCountedDelayedTask( std::function<void ()> functorun, const MicrosecondDuration &initialdelay, const MicrosecondDuration &followingduration, int repeatcount) : RepeatCountedTask(functorun, repeatcount), TimeBetweenExecutions(followingduration), ExecutionTime(Time::GetThreadSafeSteadyTimePoint()+initialdelay) { } DLLEXPORT Leviathan::RepeatCountedDelayedTask::~RepeatCountedDelayedTask(){ } DLLEXPORT bool Leviathan::RepeatCountedDelayedTask::CanBeRan( const QueuedTaskCheckValues* const checkvalues) { // Check is the current time past our timestamp // return checkvalues->CurrentTime >= ExecutionTime; } void Leviathan::RepeatCountedDelayedTask::_PostFunctionRun(){ // Set new execution point in time // ExecutionTime = Time::GetThreadSafeSteadyTimePoint()+TimeBetweenExecutions; }
28.963636
95
0.724105
Higami69
02708b7439eb12b269ed15441d947c783cb9f908
1,944
cpp
C++
fennel/calculator/CalcInit.cpp
alexavila150/luciddb
e3125564eb18238677e6efb384b630cab17bb472
[ "Apache-2.0" ]
14
2015-07-21T06:31:22.000Z
2020-05-13T14:18:33.000Z
fennel/calculator/CalcInit.cpp
alexavila150/luciddb
e3125564eb18238677e6efb384b630cab17bb472
[ "Apache-2.0" ]
1
2020-05-04T23:08:51.000Z
2020-05-04T23:08:51.000Z
fennel/calculator/CalcInit.cpp
alexavila150/luciddb
e3125564eb18238677e6efb384b630cab17bb472
[ "Apache-2.0" ]
22
2015-01-03T14:27:36.000Z
2021-09-14T02:09:13.000Z
/* // Licensed to DynamoBI Corporation (DynamoBI) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. DynamoBI licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. */ #include "fennel/common/CommonPreamble.h" #include "fennel/calculator/CalcInit.h" // to allow calls to InstructionFactory::registerInstructions() #include "fennel/calculator/CalcAssembler.h" #include "fennel/calculator/InstructionFactory.h" FENNEL_BEGIN_NAMESPACE CalcInit* CalcInit::_instance = NULL; CalcInit* CalcInit::instance() { // Warning: Not thread safe if (_instance) { return _instance; } _instance = new CalcInit; InstructionFactory::registerInstructions(); ExtStringRegister(InstructionFactory::getExtendedInstructionTable()); ExtMathRegister(InstructionFactory::getExtendedInstructionTable()); ExtDateTimeRegister(InstructionFactory::getExtendedInstructionTable()); ExtRegExpRegister(InstructionFactory::getExtendedInstructionTable()); ExtCastRegister(InstructionFactory::getExtendedInstructionTable()); ExtDynamicVariableRegister( InstructionFactory::getExtendedInstructionTable()); ExtWinAggFuncRegister(InstructionFactory::getExtendedInstructionTable()); // Add new init calls here return _instance; } FENNEL_END_NAMESPACE // End CalcInit.cpp
31.868852
77
0.769033
alexavila150
027373011eeebb62442bcd1bfa260027f24b3989
8,371
hpp
C++
ThirdParty-mod/java2cpp/java/util/concurrent/ExecutorCompletionService.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/java/util/concurrent/ExecutorCompletionService.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/java/util/concurrent/ExecutorCompletionService.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: java.util.concurrent.ExecutorCompletionService ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_UTIL_CONCURRENT_EXECUTORCOMPLETIONSERVICE_HPP_DECL #define J2CPP_JAVA_UTIL_CONCURRENT_EXECUTORCOMPLETIONSERVICE_HPP_DECL namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace java { namespace lang { class Runnable; } } } namespace j2cpp { namespace java { namespace util { namespace concurrent { class Executor; } } } } namespace j2cpp { namespace java { namespace util { namespace concurrent { class BlockingQueue; } } } } namespace j2cpp { namespace java { namespace util { namespace concurrent { class Callable; } } } } namespace j2cpp { namespace java { namespace util { namespace concurrent { class Future; } } } } namespace j2cpp { namespace java { namespace util { namespace concurrent { class CompletionService; } } } } namespace j2cpp { namespace java { namespace util { namespace concurrent { class TimeUnit; } } } } #include <java/lang/Object.hpp> #include <java/lang/Runnable.hpp> #include <java/util/concurrent/BlockingQueue.hpp> #include <java/util/concurrent/Callable.hpp> #include <java/util/concurrent/CompletionService.hpp> #include <java/util/concurrent/Executor.hpp> #include <java/util/concurrent/Future.hpp> #include <java/util/concurrent/TimeUnit.hpp> namespace j2cpp { namespace java { namespace util { namespace concurrent { class ExecutorCompletionService; class ExecutorCompletionService : public object<ExecutorCompletionService> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) explicit ExecutorCompletionService(jobject jobj) : object<ExecutorCompletionService>(jobj) { } operator local_ref<java::lang::Object>() const; operator local_ref<java::util::concurrent::CompletionService>() const; ExecutorCompletionService(local_ref< java::util::concurrent::Executor > const&); ExecutorCompletionService(local_ref< java::util::concurrent::Executor > const&, local_ref< java::util::concurrent::BlockingQueue > const&); local_ref< java::util::concurrent::Future > submit(local_ref< java::util::concurrent::Callable > const&); local_ref< java::util::concurrent::Future > submit(local_ref< java::lang::Runnable > const&, local_ref< java::lang::Object > const&); local_ref< java::util::concurrent::Future > take(); local_ref< java::util::concurrent::Future > poll(); local_ref< java::util::concurrent::Future > poll(jlong, local_ref< java::util::concurrent::TimeUnit > const&); }; //class ExecutorCompletionService } //namespace concurrent } //namespace util } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_UTIL_CONCURRENT_EXECUTORCOMPLETIONSERVICE_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_UTIL_CONCURRENT_EXECUTORCOMPLETIONSERVICE_HPP_IMPL #define J2CPP_JAVA_UTIL_CONCURRENT_EXECUTORCOMPLETIONSERVICE_HPP_IMPL namespace j2cpp { java::util::concurrent::ExecutorCompletionService::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } java::util::concurrent::ExecutorCompletionService::operator local_ref<java::util::concurrent::CompletionService>() const { return local_ref<java::util::concurrent::CompletionService>(get_jobject()); } java::util::concurrent::ExecutorCompletionService::ExecutorCompletionService(local_ref< java::util::concurrent::Executor > const &a0) : object<java::util::concurrent::ExecutorCompletionService>( call_new_object< java::util::concurrent::ExecutorCompletionService::J2CPP_CLASS_NAME, java::util::concurrent::ExecutorCompletionService::J2CPP_METHOD_NAME(0), java::util::concurrent::ExecutorCompletionService::J2CPP_METHOD_SIGNATURE(0) >(a0) ) { } java::util::concurrent::ExecutorCompletionService::ExecutorCompletionService(local_ref< java::util::concurrent::Executor > const &a0, local_ref< java::util::concurrent::BlockingQueue > const &a1) : object<java::util::concurrent::ExecutorCompletionService>( call_new_object< java::util::concurrent::ExecutorCompletionService::J2CPP_CLASS_NAME, java::util::concurrent::ExecutorCompletionService::J2CPP_METHOD_NAME(1), java::util::concurrent::ExecutorCompletionService::J2CPP_METHOD_SIGNATURE(1) >(a0, a1) ) { } local_ref< java::util::concurrent::Future > java::util::concurrent::ExecutorCompletionService::submit(local_ref< java::util::concurrent::Callable > const &a0) { return call_method< java::util::concurrent::ExecutorCompletionService::J2CPP_CLASS_NAME, java::util::concurrent::ExecutorCompletionService::J2CPP_METHOD_NAME(2), java::util::concurrent::ExecutorCompletionService::J2CPP_METHOD_SIGNATURE(2), local_ref< java::util::concurrent::Future > >(get_jobject(), a0); } local_ref< java::util::concurrent::Future > java::util::concurrent::ExecutorCompletionService::submit(local_ref< java::lang::Runnable > const &a0, local_ref< java::lang::Object > const &a1) { return call_method< java::util::concurrent::ExecutorCompletionService::J2CPP_CLASS_NAME, java::util::concurrent::ExecutorCompletionService::J2CPP_METHOD_NAME(3), java::util::concurrent::ExecutorCompletionService::J2CPP_METHOD_SIGNATURE(3), local_ref< java::util::concurrent::Future > >(get_jobject(), a0, a1); } local_ref< java::util::concurrent::Future > java::util::concurrent::ExecutorCompletionService::take() { return call_method< java::util::concurrent::ExecutorCompletionService::J2CPP_CLASS_NAME, java::util::concurrent::ExecutorCompletionService::J2CPP_METHOD_NAME(4), java::util::concurrent::ExecutorCompletionService::J2CPP_METHOD_SIGNATURE(4), local_ref< java::util::concurrent::Future > >(get_jobject()); } local_ref< java::util::concurrent::Future > java::util::concurrent::ExecutorCompletionService::poll() { return call_method< java::util::concurrent::ExecutorCompletionService::J2CPP_CLASS_NAME, java::util::concurrent::ExecutorCompletionService::J2CPP_METHOD_NAME(5), java::util::concurrent::ExecutorCompletionService::J2CPP_METHOD_SIGNATURE(5), local_ref< java::util::concurrent::Future > >(get_jobject()); } local_ref< java::util::concurrent::Future > java::util::concurrent::ExecutorCompletionService::poll(jlong a0, local_ref< java::util::concurrent::TimeUnit > const &a1) { return call_method< java::util::concurrent::ExecutorCompletionService::J2CPP_CLASS_NAME, java::util::concurrent::ExecutorCompletionService::J2CPP_METHOD_NAME(6), java::util::concurrent::ExecutorCompletionService::J2CPP_METHOD_SIGNATURE(6), local_ref< java::util::concurrent::Future > >(get_jobject(), a0, a1); } J2CPP_DEFINE_CLASS(java::util::concurrent::ExecutorCompletionService,"java/util/concurrent/ExecutorCompletionService") J2CPP_DEFINE_METHOD(java::util::concurrent::ExecutorCompletionService,0,"<init>","(Ljava/util/concurrent/Executor;)V") J2CPP_DEFINE_METHOD(java::util::concurrent::ExecutorCompletionService,1,"<init>","(Ljava/util/concurrent/Executor;Ljava/util/concurrent/BlockingQueue;)V") J2CPP_DEFINE_METHOD(java::util::concurrent::ExecutorCompletionService,2,"submit","(Ljava/util/concurrent/Callable;)Ljava/util/concurrent/Future;") J2CPP_DEFINE_METHOD(java::util::concurrent::ExecutorCompletionService,3,"submit","(Ljava/lang/Runnable;Ljava/lang/Object;)Ljava/util/concurrent/Future;") J2CPP_DEFINE_METHOD(java::util::concurrent::ExecutorCompletionService,4,"take","()Ljava/util/concurrent/Future;") J2CPP_DEFINE_METHOD(java::util::concurrent::ExecutorCompletionService,5,"poll","()Ljava/util/concurrent/Future;") J2CPP_DEFINE_METHOD(java::util::concurrent::ExecutorCompletionService,6,"poll","(JLjava/util/concurrent/TimeUnit;)Ljava/util/concurrent/Future;") } //namespace j2cpp #endif //J2CPP_JAVA_UTIL_CONCURRENT_EXECUTORCOMPLETIONSERVICE_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
44.057895
196
0.751523
kakashidinho
02744dba2b60bc5b64e6547a3ceb7ea98c3c761f
4,907
cpp
C++
interfaces/kits/napi/aafwk/wantConstant/want_constant.cpp
chaoyangcui/aafwk_standard
6a1ba0b0aa175c709e7a0d684f89ebd41a006061
[ "Apache-2.0" ]
null
null
null
interfaces/kits/napi/aafwk/wantConstant/want_constant.cpp
chaoyangcui/aafwk_standard
6a1ba0b0aa175c709e7a0d684f89ebd41a006061
[ "Apache-2.0" ]
null
null
null
interfaces/kits/napi/aafwk/wantConstant/want_constant.cpp
chaoyangcui/aafwk_standard
6a1ba0b0aa175c709e7a0d684f89ebd41a006061
[ "Apache-2.0" ]
1
2021-09-13T12:07:39.000Z
2021-09-13T12:07:39.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 "want_constant.h" #include <cstring> #include <vector> #include <uv.h> #include "securec.h" #include "hilog_wrapper.h" namespace OHOS { namespace AppExecFwk { /** * @brief WantConstantInit NAPI module registration. * * @param env The environment that the Node-API call is invoked under. * @param exports An empty object via the exports parameter as a convenience. * * @return The return value from Init is treated as the exports object for the module. */ napi_value WantConstantInit(napi_env env, napi_value exports) { HILOG_INFO("%{public}s,called1", __func__); napi_value action = nullptr; napi_value entity = nullptr; napi_create_object(env, &action); napi_create_object(env, &entity); SetNamedProperty(env, action, "action.system.home", "ACTION_HOME"); SetNamedProperty(env, action, "action.system.play", "ACTION_PLAY"); SetNamedProperty(env, action, "action.bundle.add", "ACTION_BUNDLE_ADD"); SetNamedProperty(env, action, "action.bundle.remove", "ACTION_BUNDLE_REMOVE"); SetNamedProperty(env, action, "action.bundle.update", "ACTION_BUNDLE_UPDATE"); SetNamedProperty(env, action, "ability.intent.ORDER_TAXI", "ACTION_ORDER_TAXI"); SetNamedProperty(env, action, "ability.intent.QUERY_TRAFFIC_RESTRICTION", "ACTION_QUERY_TRAFFIC_RESTRICTION"); SetNamedProperty(env, action, "ability.intent.PLAN_ROUTE", "ACTION_PLAN_ROUTE"); SetNamedProperty(env, action, "ability.intent.BOOK_FLIGHT", "ACTION_BOOK_FLIGHT"); SetNamedProperty(env, action, "ability.intent.BOOK_TRAIN_TICKET", "ACTION_BOOK_TRAIN_TICKET"); SetNamedProperty(env, action, "ability.intent.BOOK_HOTEL", "ACTION_BOOK_HOTEL"); SetNamedProperty(env, action, "ability.intent.QUERY_TRAVELLING_GUIDELINE", "ACTION_QUERY_TRAVELLING_GUIDELINE"); SetNamedProperty(env, action, "ability.intent.QUERY_POI_INFO", "ACTION_QUERY_POI_INFO"); SetNamedProperty(env, action, "ability.intent.QUERY_CONSTELLATION_FORTUNE", "ACTION_QUERY_CONSTELLATION_FORTUNE"); SetNamedProperty(env, action, "ability.intent.QUERY_ALMANC", "ACTION_QUERY_ALMANC"); SetNamedProperty(env, action, "ability.intent.QUERY_WEATHER", "ACTION_QUERY_WEATHER"); SetNamedProperty(env, action, "ability.intent.QUERY_ENCYCLOPEDIA", "ACTION_QUERY_ENCYCLOPEDIA"); SetNamedProperty(env, action, "ability.intent.QUERY_RECIPE", "ACTION_QUERY_RECIPE"); SetNamedProperty(env, action, "ability.intent.BUY_TAKEOUT", "ACTION_BUY_TAKEOUT"); SetNamedProperty(env, action, "ability.intent.TRANSLATE_TEXT", "ACTION_TRANSLATE_TEXT"); SetNamedProperty(env, action, "ability.intent.BUY", "ACTION_BUY"); SetNamedProperty(env, action, "ability.intent.QUERY_LOGISTICS_INFO", "ACTION_QUERY_LOGISTICS_INFO"); SetNamedProperty(env, action, "ability.intent.SEND_LOGISTICS", "ACTION_SEND_LOGISTICS"); SetNamedProperty(env, action, "ability.intent.QUERY_SPORTS_INFO", "ACTION_QUERY_SPORTS_INFO"); SetNamedProperty(env, action, "ability.intent.QUERY_NEWS", "ACTION_QUERY_NEWS"); SetNamedProperty(env, action, "ability.intent.QUERY_JOKE", "ACTION_QUERY_JOKE"); SetNamedProperty(env, action, "ability.intent.WATCH_VIDEO_CLIPS", "ACTION_WATCH_VIDEO_CLIPS"); SetNamedProperty(env, action, "ability.intent.QUERY_STOCK_INFO", "ACTION_QUERY_STOCK_INFO"); SetNamedProperty(env, action, "ability.intent.LOCALE_CHANGED", "ACTION_LOCALE_CHANGED"); SetNamedProperty(env, entity, "entity.system.home", "ENTITY_HOME"); SetNamedProperty(env, entity, "entity.system.video", "ENTITY_VIDEO"); napi_property_descriptor exportFuncs[] = { DECLARE_NAPI_PROPERTY("Action", action), DECLARE_NAPI_PROPERTY("Entity", entity), }; napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); return exports; } void SetNamedProperty(napi_env env, napi_value dstObj, const char *objName, const char *propName) { napi_value prop = nullptr; napi_create_string_utf8(env, objName, NAPI_AUTO_LENGTH, &prop); napi_set_named_property(env, dstObj, propName, prop); } napi_value ActionConstructor(napi_env env, napi_callback_info info) { napi_value jsthis = nullptr; napi_get_cb_info(env, info, nullptr, nullptr, &jsthis, nullptr); return jsthis; } } // namespace AppExecFwk } // namespace OHOS
51.114583
118
0.75912
chaoyangcui
0275f4fa5198d87b64f0fe69c9de5e91eb58b7ea
323
cpp
C++
src/main/cpp/pistis/logging/Log.cpp
tomault/pistis-logging
26f1411d161dc08c5684f0df4a95d929e3bbef35
[ "Apache-2.0" ]
null
null
null
src/main/cpp/pistis/logging/Log.cpp
tomault/pistis-logging
26f1411d161dc08c5684f0df4a95d929e3bbef35
[ "Apache-2.0" ]
null
null
null
src/main/cpp/pistis/logging/Log.cpp
tomault/pistis-logging
26f1411d161dc08c5684f0df4a95d929e3bbef35
[ "Apache-2.0" ]
null
null
null
#include "Log.hpp" using namespace pistis::logging; Log::Log(LogMessageFactory* msgFactory, LogMessageReceiver* msgReceiver, const std::string& destination, LogLevel logLevel): msgFactory_(msgFactory), msgReceiver_(msgReceiver), destination_(destination), logLevel_(logLevel) { // Intentionally left blank }
26.916667
72
0.770898
tomault
027659d075d26f6856fc5298629383779d8ee66f
1,268
cpp
C++
src/chat/test/ElizaTest.cpp
OznOg/xania
4effa29e1c88c7290400a8cf8a67e03ad71c851a
[ "BSD-2-Clause" ]
null
null
null
src/chat/test/ElizaTest.cpp
OznOg/xania
4effa29e1c88c7290400a8cf8a67e03ad71c851a
[ "BSD-2-Clause" ]
null
null
null
src/chat/test/ElizaTest.cpp
OznOg/xania
4effa29e1c88c7290400a8cf8a67e03ad71c851a
[ "BSD-2-Clause" ]
null
null
null
/*************************************************************************/ /* Xania (M)ulti(U)ser(D)ungeon server source code */ /* (C) 1995-2020 Xania Development Team */ /* See the header to file: merc.h for original code copyrights */ /* Chat bot originally written by Chris Busch in 1993-5, this file is a */ /* reimplementation of that work. */ /*************************************************************************/ #include "chat/Eliza.hpp" #include "chat/Database.hpp" #include "chat/KeywordResponses.hpp" #include <unistd.h> #include <catch2/catch.hpp> using namespace chat; TEST_CASE("production database sanity") { std::string chatdata_file = TEST_RESOURCE_DIR "/chat.data"; Eliza eliza; SECTION("validate production chat database loads and responds to a basic lookup") { CHECK(eliza.load_databases(chatdata_file) == true); CHECK(eliza.handle_player_message("player", "what is your name?", "Heimdall") == "My name is \"Heimdall\""); CHECK(eliza.handle_player_message("player", "you remind me of a big yellow submarine", "Heimdall") == "In what way am I like a big yellow submarine?"); } }
45.285714
116
0.554416
OznOg
027886a0999a02c0467b08869548bf4f8ce7c909
6,310
cpp
C++
src/py/wrapper_1826ae426a86563c999d176eb03c6750.cpp
nikhilkalige/ClangLite
dcb6d7385cca25c0a888bb56ae3ec1eb951cd752
[ "Apache-2.0" ]
5
2017-11-13T18:34:24.000Z
2021-08-10T02:22:22.000Z
src/py/wrapper_1826ae426a86563c999d176eb03c6750.cpp
nikhilkalige/ClangLite
dcb6d7385cca25c0a888bb56ae3ec1eb951cd752
[ "Apache-2.0" ]
4
2017-11-15T13:13:36.000Z
2019-02-26T00:21:14.000Z
src/py/wrapper_1826ae426a86563c999d176eb03c6750.cpp
nikhilkalige/ClangLite
dcb6d7385cca25c0a888bb56ae3ec1eb951cd752
[ "Apache-2.0" ]
7
2017-11-15T11:58:33.000Z
2021-03-15T18:16:16.000Z
#include "_clanglite.h" class ::clang::ConstructorUsingShadowDecl * (*method_pointer_c4b918ac39155b0a900dcfa85e003fbb)(class ::clang::ASTContext &, class ::clang::DeclContext *, class ::clang::SourceLocation , class ::clang::UsingDecl *, class ::clang::NamedDecl *, bool )= ::clang::ConstructorUsingShadowDecl::Create; class ::clang::ConstructorUsingShadowDecl * (*method_pointer_945b3ec2717450468b643a3946c8a988)(class ::clang::ASTContext &, unsigned int )= ::clang::ConstructorUsingShadowDecl::CreateDeserialized; class ::clang::CXXRecordDecl const * (::clang::ConstructorUsingShadowDecl::*method_pointer_7d8fe187704659bfbc68f3cb6eab2d86)()const= &::clang::ConstructorUsingShadowDecl::getParent; class ::clang::CXXRecordDecl * (::clang::ConstructorUsingShadowDecl::*method_pointer_bcd2883cdd7250bf8f30de7b6ced4b98)()= &::clang::ConstructorUsingShadowDecl::getParent; class ::clang::ConstructorUsingShadowDecl * (::clang::ConstructorUsingShadowDecl::*method_pointer_7478c6ce0ca65da18d9567c7013e9a06)()const= &::clang::ConstructorUsingShadowDecl::getNominatedBaseClassShadowDecl; class ::clang::ConstructorUsingShadowDecl * (::clang::ConstructorUsingShadowDecl::*method_pointer_4e1ee143b6335c02bd0367e52103afda)()const= &::clang::ConstructorUsingShadowDecl::getConstructedBaseClassShadowDecl; class ::clang::CXXRecordDecl * (::clang::ConstructorUsingShadowDecl::*method_pointer_8fef68184f2c588497447f16d34d765c)()const= &::clang::ConstructorUsingShadowDecl::getNominatedBaseClass; class ::clang::CXXRecordDecl * (::clang::ConstructorUsingShadowDecl::*method_pointer_f8b32b454cbd5e3baf27e2ddc1f9b1f1)()const= &::clang::ConstructorUsingShadowDecl::getConstructedBaseClass; bool (::clang::ConstructorUsingShadowDecl::*method_pointer_09d6ab552a86507f97e3f12c80b9eec6)()const= &::clang::ConstructorUsingShadowDecl::constructsVirtualBase; // class ::clang::CXXConstructorDecl * (::clang::ConstructorUsingShadowDecl::*method_pointer_e9ef33993a8057d49e9f2c89634b4f54)()const= &::clang::ConstructorUsingShadowDecl::getConstructor; // void (::clang::ConstructorUsingShadowDecl::*method_pointer_f75d716b070c54d79b7e1d919edfb0c5)(class ::clang::NamedDecl *)= &::clang::ConstructorUsingShadowDecl::setConstructor; bool (*method_pointer_fe76d27284825a60ba2aa933194150a9)(class ::clang::Decl const *)= ::clang::ConstructorUsingShadowDecl::classof; bool (*method_pointer_28c10fe860ff54d49cd2f9581f46232c)(enum ::clang::Decl::Kind )= ::clang::ConstructorUsingShadowDecl::classofKind; namespace autowig { } void wrapper_1826ae426a86563c999d176eb03c6750(pybind11::module& module) { pybind11::class_<class ::clang::ConstructorUsingShadowDecl, autowig::HolderType< class ::clang::ConstructorUsingShadowDecl >::Type, class ::clang::UsingShadowDecl > class_1826ae426a86563c999d176eb03c6750(module, "ConstructorUsingShadowDecl", "Represents a shadow constructor declaration introduced into a class by a\nC++11 using-declaration that names a constructor.\n\nFor example:\n\n"); class_1826ae426a86563c999d176eb03c6750.def_static("create", method_pointer_c4b918ac39155b0a900dcfa85e003fbb, pybind11::return_value_policy::reference_internal, ""); class_1826ae426a86563c999d176eb03c6750.def_static("create_deserialized", method_pointer_945b3ec2717450468b643a3946c8a988, pybind11::return_value_policy::reference_internal, ""); class_1826ae426a86563c999d176eb03c6750.def("get_parent", method_pointer_7d8fe187704659bfbc68f3cb6eab2d86, pybind11::return_value_policy::reference_internal, ""); class_1826ae426a86563c999d176eb03c6750.def("get_parent", method_pointer_bcd2883cdd7250bf8f30de7b6ced4b98, pybind11::return_value_policy::reference_internal, ""); class_1826ae426a86563c999d176eb03c6750.def("get_nominated_base_class_shadow_decl", method_pointer_7478c6ce0ca65da18d9567c7013e9a06, pybind11::return_value_policy::reference_internal, "Get the inheriting constructor declaration for the direct base class\nfrom which this using shadow declaration was inherited, if there is one.\nThis can be different for each redeclaration of the same shadow decl.\n\n:Return Type:\n :cpp:class:`::clang::ConstructorUsingShadowDecl`\n\n"); class_1826ae426a86563c999d176eb03c6750.def("get_constructed_base_class_shadow_decl", method_pointer_4e1ee143b6335c02bd0367e52103afda, pybind11::return_value_policy::reference_internal, "Get the inheriting constructor declaration for the base class for which\nwe don’t have an explicit initializer, if there is one.\n\n:Return Type:\n :cpp:class:`::clang::ConstructorUsingShadowDecl`\n\n"); class_1826ae426a86563c999d176eb03c6750.def("get_nominated_base_class", method_pointer_8fef68184f2c588497447f16d34d765c, pybind11::return_value_policy::reference_internal, "Get the base class that was named in the using declaration. This can be\ndifferent for each redeclaration of this same shadow decl.\n\n:Return Type:\n :cpp:class:`::clang::CXXRecordDecl`\n\n"); class_1826ae426a86563c999d176eb03c6750.def("get_constructed_base_class", method_pointer_f8b32b454cbd5e3baf27e2ddc1f9b1f1, pybind11::return_value_policy::reference_internal, "Get the base class whose constructor or constructor shadow declaration\nis passed the constructor arguments.\n\n:Return Type:\n :cpp:class:`::clang::CXXRecordDecl`\n\n"); class_1826ae426a86563c999d176eb03c6750.def("constructs_virtual_base", method_pointer_09d6ab552a86507f97e3f12c80b9eec6, "Returns\n:raw-latex:`\\c true if the constructed base class is a virtual base\nclass subobject of this declaration's class.`\n\n:Return Type:\n :cpp:any:`bool`\n\n"); // class_1826ae426a86563c999d176eb03c6750.def("get_constructor", method_pointer_e9ef33993a8057d49e9f2c89634b4f54, pybind11::return_value_policy::reference_internal, "Get the constructor or constructor template in the derived class\ncorrespnding to this using shadow declaration, if it has been implicitly\ndeclared already.\n\n:Return Type:\n :cpp:class:`::clang::CXXConstructorDecl`\n\n"); // class_1826ae426a86563c999d176eb03c6750.def("set_constructor", method_pointer_f75d716b070c54d79b7e1d919edfb0c5, ""); class_1826ae426a86563c999d176eb03c6750.def_static("classof", method_pointer_fe76d27284825a60ba2aa933194150a9, ""); class_1826ae426a86563c999d176eb03c6750.def_static("classof_kind", method_pointer_28c10fe860ff54d49cd2f9581f46232c, ""); }
166.052632
479
0.82916
nikhilkalige
027a3d5f2e034521e419ceb3bdf9cb0ea025e3f5
2,528
cpp
C++
library/cpp/threading/mux_event/mux_event_ut.cpp
jochenater/catboost
de2786fbc633b0d6ea6a23b3862496c6151b95c2
[ "Apache-2.0" ]
6,989
2017-07-18T06:23:18.000Z
2022-03-31T15:58:36.000Z
library/cpp/threading/mux_event/mux_event_ut.cpp
birichie/catboost
de75c6af12cf490700e76c22072fbdc15b35d679
[ "Apache-2.0" ]
1,978
2017-07-18T09:17:58.000Z
2022-03-31T14:28:43.000Z
library/cpp/threading/mux_event/mux_event_ut.cpp
birichie/catboost
de75c6af12cf490700e76c22072fbdc15b35d679
[ "Apache-2.0" ]
1,228
2017-07-18T09:03:13.000Z
2022-03-29T05:57:40.000Z
#include <library/cpp/testing/unittest/registar.h> #include <library/cpp/threading/mux_event/mux_event.h> #include <util/system/thread.h> struct TMuxEventText: public TTestBase { UNIT_TEST_SUITE(TMuxEventText); UNIT_TEST(CheckOneWait); UNIT_TEST(CheckTwoWait); UNIT_TEST(CheckSignalAfterWait); UNIT_TEST_SUITE_END(); void CheckOneWait() { TMuxEvent e0; UNIT_ASSERT_VALUES_EQUAL(WaitForAnyEvent(e0, TDuration::MicroSeconds(0)), -1); UNIT_ASSERT_VALUES_EQUAL(WaitForAnyEvent(e0, TDuration::MilliSeconds(50)), -1); e0.Signal(); UNIT_ASSERT_VALUES_EQUAL(WaitForAnyEvent(e0, TDuration::MicroSeconds(0)), 0); UNIT_ASSERT_VALUES_EQUAL(WaitForAnyEvent(e0), 0); e0.Reset(); UNIT_ASSERT_VALUES_EQUAL(WaitForAnyEvent(e0, TDuration::MicroSeconds(0)), -1); } void CheckTwoWait() { TMuxEvent e0, e1; UNIT_ASSERT_VALUES_EQUAL(WaitForAnyEvent(e0, e1, TDuration::MicroSeconds(0)), -1); UNIT_ASSERT_VALUES_EQUAL(WaitForAnyEvent(e0, e1, TDuration::MilliSeconds(50)), -1); e0.Signal(); UNIT_ASSERT_VALUES_EQUAL(WaitForAnyEvent(e0, e1, TDuration::MicroSeconds(0)), 0); e1.Signal(); UNIT_ASSERT_VALUES_EQUAL(WaitForAnyEvent(e0, e1, TDuration::MicroSeconds(0)), 0); e0.Reset(); UNIT_ASSERT_VALUES_EQUAL(WaitForAnyEvent(e0, e1), 1); e1.Reset(); UNIT_ASSERT_VALUES_EQUAL(WaitForAnyEvent(e0, e1, TDuration::MicroSeconds(0)), -1); } struct TTestFuncParams { TSystemEvent SyncEvent; TMuxEvent TestEvent; }; static void* TestFunc(void* params) { static_cast<TTestFuncParams*>(params)->SyncEvent.Signal(); Sleep(TDuration::MilliSeconds(100)); // ensure that WaitForAnyEvent is called static_cast<TTestFuncParams*>(params)->TestEvent.Signal(); return nullptr; } void CheckSignalAfterWait() { TTestFuncParams params; TThread test(&TMuxEventText::TestFunc, &params); test.Start(); params.SyncEvent.Wait(); TMuxEvent e0, e2; UNIT_ASSERT_VALUES_EQUAL(WaitForAnyEvent(e0, params.TestEvent, e2, TDuration::Seconds(1)), 1); UNIT_ASSERT_VALUES_EQUAL(WaitForAnyEvent(e0, params.TestEvent, e2), 1); } }; UNIT_TEST_SUITE_REGISTRATION(TMuxEventText); // TMuxEvent implements Event semantics too #include <util/system/event.h> // for pragma once in util/system/event_ut.cpp #define TSystemEvent TMuxEvent #include <util/system/event_ut.cpp>
34.630137
102
0.689873
jochenater
027a6ebc2ac3a25e7bc902f573cb157e364f0d05
1,188
hpp
C++
Value/ValueVisitorPrinter.hpp
Sevenrip/value-container
a2c586a134f10c2a1802ee5947e0c4b8a4b046dc
[ "MIT" ]
null
null
null
Value/ValueVisitorPrinter.hpp
Sevenrip/value-container
a2c586a134f10c2a1802ee5947e0c4b8a4b046dc
[ "MIT" ]
null
null
null
Value/ValueVisitorPrinter.hpp
Sevenrip/value-container
a2c586a134f10c2a1802ee5947e0c4b8a4b046dc
[ "MIT" ]
null
null
null
#pragma once #include <ostream> #include <memory> #include <type_traits> #include <unordered_map> #include <string> #include <sstream> #include "../Utils/Utils.hpp" class ValueVisitorPrinter { public: explicit ValueVisitorPrinter(std::stringstream & stream) : _stream(stream) {} ValueVisitorPrinter& operator=(ValueVisitorPrinter const&) = delete; template <typename T> void operator()(const T & t ) const { _stream << t; } void operator()(const std::shared_ptr<const std::string> & s ) const { _stream << *s; } template <typename T> void operator()(const std::shared_ptr<std::vector<T>> & t) const { _stream << "[ " ; for(const auto & el : *t) { this->operator()(el); } _stream << " ]" ; } template <typename T> void operator()(const std::shared_ptr<StringMap<T>> & map) { _stream << "{ " ; for(const auto & pair : *map) { _stream << "{" ; this->operator()(pair.first); this->operator()(pair.second); _stream << "}" ; } _stream << " }" ; } private: int _depth; std::stringstream & _stream; };
19.47541
73
0.564815
Sevenrip
027dbd873a120220b9c64c2d82a5a7f0e8a07408
7,996
cpp
C++
code/wxWidgets/utils/configtool/src/configitemselector.cpp
Bloodknight/NeuTorsion
a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea
[ "MIT" ]
38
2016-02-20T02:46:28.000Z
2021-11-17T11:39:57.000Z
code/wxWidgets/utils/configtool/src/configitemselector.cpp
Bloodknight/NeuTorsion
a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea
[ "MIT" ]
17
2016-02-20T02:19:55.000Z
2021-02-08T15:15:17.000Z
code/wxWidgets/utils/configtool/src/configitemselector.cpp
Bloodknight/NeuTorsion
a5890e9ca145a8c1b6bec7b70047a43d9b1c29ea
[ "MIT" ]
46
2016-02-20T02:47:33.000Z
2021-01-31T15:46:05.000Z
///////////////////////////////////////////////////////////////////////////// // Name: configitemselector.cpp // Purpose: Selector for one or more config items // Author: Julian Smart // Modified by: // Created: 2003-06-04 // RCS-ID: $Id: configitemselector.cpp,v 1.11 2005/02/01 20:44:05 ABX Exp $ // Copyright: (c) Julian Smart // Licence: ///////////////////////////////////////////////////////////////////////////// #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA) #pragma implementation "configitemselector.h" #endif // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/statline.h" #include "wx/splitter.h" #include "wx/scrolwin.h" #include "wx/spinctrl.h" #include "wx/spinbutt.h" #endif #include "wx/cshelp.h" #include "wx/notebook.h" #include "wx/valgen.h" #include "configitemselector.h" #include "configtooldoc.h" #include "configtoolview.h" #include "configitem.h" #include "mainframe.h" #include "wxconfigtool.h" ////@begin XPM images ////@end XPM images /*! * ctConfigItemsSelector type definition */ IMPLEMENT_CLASS( ctConfigItemsSelector, wxDialog ) /*! * ctConfigItemsSelector event table definition */ BEGIN_EVENT_TABLE( ctConfigItemsSelector, wxDialog ) ////@begin ctConfigItemsSelector event table entries EVT_BUTTON( ID_CONFIG_ADD, ctConfigItemsSelector::OnConfigAdd ) EVT_UPDATE_UI( ID_CONFIG_ADD, ctConfigItemsSelector::OnUpdateConfigAdd ) EVT_BUTTON( ID_CONFIG_REMOVE, ctConfigItemsSelector::OnConfigRemove ) EVT_UPDATE_UI( ID_CONFIG_REMOVE, ctConfigItemsSelector::OnUpdateConfigRemove ) EVT_BUTTON( wxID_OK, ctConfigItemsSelector::OnOk ) ////@end ctConfigItemsSelector event table entries END_EVENT_TABLE() /*! * ctConfigItemsSelector constructor */ ctConfigItemsSelector::ctConfigItemsSelector( wxWindow* parent, wxWindowID id, const wxString& caption) { wxDialog::Create( parent, id, caption); CreateControls(); InitSourceConfigList(); } /*! * Control creation for ctConfigItemsSelector */ void ctConfigItemsSelector::CreateControls() { ////@begin ctConfigItemsSelector content construction ctConfigItemsSelector* item1 = this; wxBoxSizer* item2 = new wxBoxSizer(wxVERTICAL); item1->SetSizer(item2); wxBoxSizer* item3 = new wxBoxSizer(wxVERTICAL); item2->Add(item3, 1, wxGROW|wxALL, 5); wxStaticText* item4 = new wxStaticText(item1, wxID_STATIC, _("Please edit the list of configuration items by selecting from the\nlist below."), wxDefaultPosition, wxDefaultSize, 0); item3->Add(item4, 0, wxALIGN_LEFT|wxALL|wxADJUST_MINSIZE, 5); wxStaticText* item5 = new wxStaticText(item1, wxID_STATIC, _("&Available items:"), wxDefaultPosition, wxDefaultSize, 0); item3->Add(item5, 0, wxALIGN_LEFT|wxALL|wxADJUST_MINSIZE, 5); wxString* item6Strings = NULL; wxListBox* item6 = new wxListBox(item1, ID_AVAILABLE_CONFIG_ITEMS, wxDefaultPosition, wxSize(wxDefaultCoord, 150), 0, item6Strings, wxLB_SINGLE|wxLB_SORT); item3->Add(item6, 1, wxGROW|wxALL, 5); wxStaticText* item7 = new wxStaticText(item1, wxID_STATIC, _("&List of configuration items:"), wxDefaultPosition, wxDefaultSize, 0); item3->Add(item7, 0, wxALIGN_LEFT|wxALL|wxADJUST_MINSIZE, 5); wxBoxSizer* item8 = new wxBoxSizer(wxHORIZONTAL); item3->Add(item8, 0, wxGROW, 5); wxString* item9Strings = NULL; wxListBox* item9 = new wxListBox(item1, ID_CONFIG_ITEMS, wxDefaultPosition, wxSize(wxDefaultCoord, 100), 0, item9Strings, wxLB_SINGLE); item8->Add(item9, 1, wxGROW|wxALL, 5); wxBoxSizer* item10 = new wxBoxSizer(wxVERTICAL); item8->Add(item10, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxButton* item11 = new wxButton(item1, ID_CONFIG_ADD, _("A&dd"), wxDefaultPosition, wxDefaultSize, 0); item10->Add(item11, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); wxButton* item12 = new wxButton(item1, ID_CONFIG_REMOVE, _("&Remove"), wxDefaultPosition, wxDefaultSize, 0); item10->Add(item12, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); wxBoxSizer* item13 = new wxBoxSizer(wxHORIZONTAL); item3->Add(item13, 0, wxGROW, 5); item13->Add(5, 5, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxButton* item15 = new wxButton(item1, wxID_OK); item15->SetDefault(); item13->Add(item15, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); wxButton* item16 = new wxButton(item1, wxID_CANCEL); item13->Add(item16, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); GetSizer()->Fit(this); GetSizer()->SetSizeHints(this); Centre(); ////@end ctConfigItemsSelector content construction } /*! * Event handler for ID_CONFIG_ADD */ void ctConfigItemsSelector::OnConfigAdd( wxCommandEvent& WXUNUSED(event) ) { wxListBox* masterList = wxDynamicCast(FindWindow(ID_AVAILABLE_CONFIG_ITEMS), wxListBox); wxListBox* listBox = wxDynamicCast(FindWindow(ID_CONFIG_ITEMS), wxListBox); if (masterList) { if (masterList->GetSelection() > -1) { wxString str = masterList->GetStringSelection(); if (m_configItems.Index(str) == wxNOT_FOUND) { listBox->Append(str); m_configItems.Add(str); } } } } /*! * Event handler for ID_CONFIG_REMOVE */ void ctConfigItemsSelector::OnConfigRemove( wxCommandEvent& WXUNUSED(event) ) { wxListBox* listBox = wxDynamicCast(FindWindow(ID_CONFIG_ITEMS), wxListBox); if (listBox) { if (listBox->GetSelection() > -1) { wxString str = listBox->GetStringSelection(); listBox->Delete(listBox->GetSelection()); m_configItems.Remove(str); } } } /*! * Event handler for wxID_OK */ void ctConfigItemsSelector::OnOk( wxCommandEvent& event ) { // Replace with custom code event.Skip(); } /*! * Should we show tooltips? */ bool ctConfigItemsSelector::ShowToolTips() { return true; } /*! * Update event handler for ID_CONFIG_ADD */ void ctConfigItemsSelector::OnUpdateConfigAdd( wxUpdateUIEvent& event ) { wxListBox* masterList = wxDynamicCast(FindWindow(ID_AVAILABLE_CONFIG_ITEMS), wxListBox); event.Enable(masterList && masterList->GetSelection() != -1); } /*! * Update event handler for ID_CONFIG_REMOVE */ void ctConfigItemsSelector::OnUpdateConfigRemove( wxUpdateUIEvent& event ) { wxListBox* listBox = wxDynamicCast(FindWindow(ID_CONFIG_ITEMS), wxListBox); event.Enable(listBox && listBox->GetSelection() != -1); } /// Initialise the master list void ctConfigItemsSelector::InitSourceConfigList(ctConfigItem* item) { wxListBox* masterList = wxDynamicCast(FindWindow(ID_AVAILABLE_CONFIG_ITEMS), wxListBox); if (!item) item = wxGetApp().GetMainFrame()->GetDocument()->GetTopItem(); if (!item) return; bool addIt = false; if (item->GetType() == ctTypeGroup) addIt = false; else if (item->GetType() == ctTypeCheckGroup) addIt = true; else if (item->GetType() == ctTypeRadioGroup) addIt = true; else if (item->GetType() == ctTypeString) addIt = true; else if (item->GetType() == ctTypeBoolCheck) addIt = true; else if (item->GetType() == ctTypeBoolRadio) addIt = true; else if (item->GetType() == ctTypeInteger) addIt = true; if (addIt) { masterList->Append(item->GetName()); } wxObjectList::compatibility_iterator node = item->GetChildren().GetFirst(); while (node) { ctConfigItem* child = (ctConfigItem*) node->GetData(); InitSourceConfigList(child); node = node->GetNext(); } } /// Set the initial list void ctConfigItemsSelector::SetConfigList(const wxArrayString& items) { m_configItems = items; wxListBox* listBox = wxDynamicCast(FindWindow(ID_CONFIG_ITEMS), wxListBox); listBox->Clear(); size_t i; for (i = 0; i < items.GetCount(); i++) listBox->Append(items[i]); }
28.866426
185
0.681591
Bloodknight
027f93f9f55f52c8c10d1e4c7a8670ed046b9008
1,939
cpp
C++
usaco/section3.1/contact.cpp
chasingegg/Online_Judge
8a3f4b5b207cbeda921c743a527a25bf9c7b6248
[ "MIT" ]
1
2017-10-13T10:34:46.000Z
2017-10-13T10:34:46.000Z
usaco/section3.1/contact.cpp
chasingegg/Online_Judge
8a3f4b5b207cbeda921c743a527a25bf9c7b6248
[ "MIT" ]
null
null
null
usaco/section3.1/contact.cpp
chasingegg/Online_Judge
8a3f4b5b207cbeda921c743a527a25bf9c7b6248
[ "MIT" ]
null
null
null
/* PROG: contact LANG: C++ */ //2017.5.29 //这道题我选择抄答案 //不过发现在进行字符串的匹配过程中其实实现的依然是暴力的做法 //主要的想法就是hash 把字符串的数值作为index保存下来 但有问题就是 00 000 0000 这种情况方式就是前面加上1作为区分 #include<iostream> #include<fstream> #include<string> #include<memory.h> #include<algorithm> using namespace std; ifstream fin("contact.in"); ofstream fout("contact.out"); struct Node { int count, index; char str[15]; }; Node n[200000]; int used[200000]; int cmp(Node n1, Node n2) { if(n1.count == n2.count) return n1.index < n2.index; return n1.count > n2.count; } int main() { int A, B, N; string s, temp; fin >> A >> B >> N; //getline(cin, temp); while(fin >> temp) s += temp; //return 0; if(s.length() < B) B = s.length(); //是个可能会出现的bug int counter, num; for(int i = A; i <= B; ++i) { for(int j = 0; j < s.length() - i + 1; ++j) { counter = 0, num = 1; while(counter < i) { num <<= 1; num = num | (int)(s[j + counter] - '0'); ++counter; } n[num].count++; if(n[num].count == 1) { n[num].index = num; for(int k = 0; k < i; ++k) n[num].str[k] = s[k + j]; } } } sort(n, n+200000, cmp); bool judge = true; counter = 0; for(int i = 0; i < 200000; ++i) { if(n[i].count != 0) { if(!used[n[i].count]) { ++counter; num = 1; if(counter > N) break; if(!judge) fout << endl; judge = false; fout << n[i].count << endl << n[i].str; used[n[i].count] = 1; } else { if(num % 6 == 0) fout << endl << n[i].str; else fout << " " << n[i].str; ++num; } } } fout << endl; return 0; }
22.546512
69
0.436307
chasingegg
028104b7714953839a12c04612e6e6e671966089
11,207
cpp
C++
PS4Engine/PS4Engine/api_gnm/simplet-gs-stream-out/simplet-gs-stream-out.cpp
Enderderder/SonyEngine
ee8b3726d293c667d2e2a849808b993e954b84c7
[ "MIT" ]
2
2020-02-22T01:27:28.000Z
2021-12-20T08:41:43.000Z
PS4Engine/PS4Engine/api_gnm/simplet-gs-stream-out/simplet-gs-stream-out.cpp
Enderderder/SonyEngine
ee8b3726d293c667d2e2a849808b993e954b84c7
[ "MIT" ]
null
null
null
PS4Engine/PS4Engine/api_gnm/simplet-gs-stream-out/simplet-gs-stream-out.cpp
Enderderder/SonyEngine
ee8b3726d293c667d2e2a849808b993e954b84c7
[ "MIT" ]
2
2019-09-17T19:54:00.000Z
2020-03-06T15:08:52.000Z
/* SIE CONFIDENTIAL PlayStation(R)4 Programmer Tool Runtime Library Release 05.008.001 * Copyright (C) 2016 Sony Interactive Entertainment Inc. * All Rights Reserved. */ // Simplet #7 // This simplet shows how to setup es, gs shaders to create geometry #include "../toolkit/simplet-common.h" #include "std_cbuffer.h" using namespace sce; bool screenshot = false; // { // "title" : "simplet-gs-stream-out", // "overview" : "This sample demonstrates simple stream out with geometry shading.", // "explanation" : ["This sample sets up required compile switches, stream out buffers and registers and performs simple geometry shading with them.", // "There are three necessary steps to use streamout:", // "1. Use the geometry shader compiled with the -gsstream switches.", // "2. Set streamout buffers.", // "3. Set streamout config registers.", // "Streamout config registers need to be set before each streamout draw because the GPU maintains persistent streamout state and the next draw call may continue writing where the last call ended causing possible memory corruption."] // } static const unsigned s_shader_g[] = { #include "shader_g.h" }; static const unsigned s_shader_p[] = { #include "shader_p.h" }; static const unsigned s_shader_ve[] = { #include "shader_ve.h" }; static void Test() { // // Define window size and set up a window to render to it // uint32_t targetWidth = 1920; uint32_t targetHeight = 1080; SimpletUtil::getResolution(targetWidth, targetHeight); // // Setup the render target: // Gnm::DataFormat format = Gnm::kDataFormatB8G8R8A8UnormSrgb; Gnm::RenderTarget fbTarget; Gnm::TileMode tileMode; GpuAddress::computeSurfaceTileMode(Gnm::getGpuMode(), &tileMode, GpuAddress::kSurfaceTypeColorTargetDisplayable, format, 1); Gnm::SizeAlign fbSize = Gnmx::Toolkit::init(&fbTarget, targetWidth, targetHeight, 1, format, tileMode, Gnm::kNumSamples1, Gnm::kNumFragments1, NULL, NULL); void *fbCpuBaseAddr = SimpletUtil::allocateGarlicMemory(fbSize); uint8_t *fbBaseAddr = static_cast<uint8_t*>(fbCpuBaseAddr); memset(fbCpuBaseAddr, 0x0, fbSize.m_size); fbTarget.setAddresses(fbBaseAddr, 0, 0); // // Load all shader binaries to video memory // Gnmx::EsShader *exportShader = SimpletUtil::LoadEsShaderFromMemory(s_shader_ve); Gnmx::GsShader *geometryShader = SimpletUtil::LoadGsShaderFromMemory(s_shader_g); Gnmx::PsShader *pixelShader = SimpletUtil::LoadPsShaderFromMemory(s_shader_p); // // Allocate esgs and gsvs rings // const uint32_t esgsRingSize = Gnm::kGsRingSizeSetup4Mb, gsvsRingSize = Gnm::kGsRingSizeSetup4Mb; void *esgsRing = SimpletUtil::allocateGarlicMemory(esgsRingSize, Gnm::kAlignmentOfBufferInBytes); void *gsvsRing = SimpletUtil::allocateGarlicMemory(gsvsRingSize, Gnm::kAlignmentOfBufferInBytes); // // Create a synchronization point: // volatile uint64_t *label = (uint64_t*)SimpletUtil::allocateOnionMemory(sizeof(uint64_t), sizeof(uint64_t)); // // Setup the Command and constant buffers: // Gnmx::GfxContext gfxc; const uint32_t kNumRingEntries = 64; const uint32_t cueHeapSize = Gnmx::ConstantUpdateEngine::computeHeapSize(kNumRingEntries); gfxc.init(SimpletUtil::allocateGarlicMemory(cueHeapSize, Gnm::kAlignmentOfBufferInBytes), kNumRingEntries, // Constant Update Engine SimpletUtil::allocateOnionMemory(Gnm::kIndirectBufferMaximumSizeInBytes, Gnm::kAlignmentOfBufferInBytes), Gnm::kIndirectBufferMaximumSizeInBytes, // Draw command buffer SimpletUtil::allocateOnionMemory(Gnm::kIndirectBufferMaximumSizeInBytes, Gnm::kAlignmentOfBufferInBytes), Gnm::kIndirectBufferMaximumSizeInBytes // Constant command buffer ); #if !SCE_GNM_CUE2_DYNAMIC_GLOBAL_TABLE void *globalResourceTablePtr = SimpletUtil::allocateGarlicMemory(SCE_GNM_SHADER_GLOBAL_TABLE_SIZE, Gnm::kAlignmentOfBufferInBytes); gfxc.setGlobalResourceTableAddr(globalResourceTablePtr); #endif //!SCE_GNM_CUE2_DYNAMIC_GLOBAL_TABLE gfxc.setRenderTarget(0, &fbTarget); gfxc.setRenderTargetMask(0xF); gfxc.setupScreenViewport(0, 0, targetWidth, targetHeight, 0.5f, 0.5f); // Set hardware render in wire frame Gnm::PrimitiveSetup primSetupReg; primSetupReg.init(); primSetupReg.setPolygonMode(Gnm::kPrimitiveSetupPolygonModeLine, Gnm::kPrimitiveSetupPolygonModeLine); gfxc.setLineWidth(8); gfxc.setPrimitiveSetup(primSetupReg); // The HW stages used for geometry shading (when tessellation is disabled) are // ES -> GS -> VS -> PS and the shaders assigned to these stages are: // Vertex Shader --> Geometry Shader --> (Copy VS shader) --> Pixel Shader // The shaders assigned to the ES and GS stages both write their data to off-chip memory. // All of the work described by a single geometry shader invocation is performed by just one thread. // Do we know anything about foot-print yet? // set rings gfxc.setEsGsRingBuffer(esgsRing, esgsRingSize, exportShader->m_memExportVertexSizeInDWord); gfxc.setGsVsRingBuffers(gsvsRing, gsvsRingSize, geometryShader->m_memExportVertexSizeInDWord, geometryShader->m_maxOutputVertexCount); // Setup streamout config: const uint32_t streamSizeInDW = 8*1024*1024; Gnm::StreamoutBufferMapping bufferBinding; bufferBinding.init(); bufferBinding.bindStream(Gnm::kStreamoutBuffer0,Gnm::StreamoutBufferMapping::kGsStreamBuffer0); bufferBinding.bindStream(Gnm::kStreamoutBuffer1,Gnm::StreamoutBufferMapping::kGsStreamBuffer0); // Setting partial vs wave, needed for streamout, the rest of the parameters are default values gfxc.setVgtControl(255); // Setting streamout parameters gfxc.flushStreamout(); gfxc.setStreamoutMapping(&bufferBinding); gfxc.setStreamoutBufferDimensions(Gnm::kStreamoutBuffer0,streamSizeInDW,16/4); gfxc.setStreamoutBufferDimensions(Gnm::kStreamoutBuffer1,streamSizeInDW,12/4); gfxc.writeStreamoutBufferOffset(Gnm::kStreamoutBuffer0,0); gfxc.writeStreamoutBufferOffset(Gnm::kStreamoutBuffer1,0); void* soBuf0 = SimpletUtil::allocateGarlicMemory(streamSizeInDW*4, 256); void* soBuf1 = SimpletUtil::allocateGarlicMemory(streamSizeInDW*4, 256); // Setup streamout buffers. Gnm::Buffer sob0; Gnm::Buffer sob1; // Set Vertex Shader: ES stage is a vertex shader that writes to the ES-GS ring-buffer // uint64_t fetchShaderAddr = 0; // in this sample we're not using a vertex buffer gfxc.setEsShader(exportShader, 0, (void*)0); // so we do not have a fetch shader. // Set Geometry Shader: GS stage is a geometry shader that writes to the GS-VS ring-buffer gfxc.setGsVsShaders(geometryShader); // sets up copy VS shader too // Set Pixel Shader gfxc.setPsShader(pixelShader); sob0.initAsGsStreamoutDescriptor(soBuf0, 16); sob1.initAsGsStreamoutDescriptor(soBuf1, 12); sob0.setResourceMemoryType(Gnm::kResourceMemoryTypeGC); // we write to it, so it's GPU coherent sob1.setResourceMemoryType(Gnm::kResourceMemoryTypeGC); // we write to it, so it's GPU coherent gfxc.setStreamoutBuffers(0, 1, &sob0); gfxc.setStreamoutBuffers(1, 1, &sob1); // Set which stages are enabled gfxc.setActiveShaderStages(Gnm::kActiveShaderStagesEsGsVsPs); // Initiate the actual rendering gfxc.setPrimitiveType(Gnm::kPrimitiveTypePointList); gfxc.drawIndexAuto(NUMSEGS_X*NUMSEGS_Y); // Set hardware state back to its default state gfxc.setActiveShaderStages(Gnm::kActiveShaderStagesVsPs); // In addition of turning off the GS shader stage off; the GS Mode also needs to be turned off. gfxc.setGsModeOff(); // // Add a synchronization point: // gfxc.writeImmediateAtEndOfPipe(Gnm::kEopFlushCbDbCaches, (void *)label, 0x1, Gnm::kCacheActionWriteBackAndInvalidateL1andL2); SimpletUtil::registerRenderTargetForDisplay(&fbTarget); // Loop over the buffer bool done = false; while (!done) { *label =2; // Submit the command buffers: // Note: we are passing the ccb in the last two arguments; when no ccb is used, 0 should be passed in int32_t state = gfxc.submit(); SCE_GNM_ASSERT(state == sce::Gnm::kSubmissionSuccess); // Wait until it's done (waiting for the GPU to write "1" in "label") uint32_t wait = 0; while (*label != 1) ++wait; if(screenshot) { Gnm::Texture fbTexture; fbTexture.initFromRenderTarget(&fbTarget, false); fbTexture.setResourceMemoryType(Gnm::kResourceMemoryTypeRO); // we won't bind this as RWTexture, so it's OK to declare it read-only. SimpletUtil::SaveTextureToTGA(&fbTexture, "screenshot.tga"); screenshot = 0; } // Display the render target on the screen SimpletUtil::requestFlipAndWait(); // Check to see if user has requested to quit the loop done = SimpletUtil::handleUserEvents(); // Verify the streamout output by repeating the computation from the geometry shader // and comparing the output to the data in the streamout buffers. const float* positions = (float*)soBuf0; const float* colors = (float*)soBuf1; bool success = true; float position[4]; position[2] = 0.f; position[3] = 1.f; // The geometry shader outputs a 4 vertices stream that is converted to two triangles (6 vertices) // so the order the quad's vertices appear in the streamout buffers is as follows: const unsigned order[6] = { 0, 1, 2, 1, 3, 2}; for( unsigned j = 0; j != NUMSEGS_Y; ++j) for (unsigned i=0; i != NUMSEGS_X; ++i) { // This is the same code the geometry shader uses to create quad's vertices const unsigned point_index = NUMSEGS_X*j + i; const float t = (float)point_index/(NUMSEGS_X*NUMSEGS_Y - 1); const float color[3] = { 0.5f *(t + (1.f - t)), 0.5f * (1.f - t), 0.5f * (1.f - t) }; for(unsigned idx=0; idx !=6; ++idx ) { const unsigned v = order[idx]; const unsigned ix = i + (v & 1); const unsigned iy = j + (v >> 1); position[0] = 0.5f * (2.f * ix / NUMSEGS_X - 1.f); position[1] = 0.5f * (2.f * iy / NUMSEGS_Y - 1.f); // When doing floating point computations on different processors it's possible to get // slightly different results due to different configuration of the FPUs (e.g. rounding mode, precision etc) // Because of this, bitwise comparison between the results of the simulated geometry shader and the streamout may fail. // Instead of bitwise comparison we are checking if the results are close enough by estimating the mean squared error. float errPos = 0.f; for(unsigned e = 0; e != 4; ++e) { const float d = position[e] - positions[e]; errPos += d*d; } float errColor = 0.f; for(unsigned e = 0; e != 3; ++e) { const float d = colors[e] - color[e]; errColor += d*d; } const float epsilon = 1e-8f; if( errPos >= epsilon || errColor >= epsilon) { success = false; printf("Validation failed at grid cell #(%d,%d)\n",i,j); } positions += 4; colors += 3; } } if( success ) printf("Validated OK\n"); } } int main(int argc, char *argv[]) { if (argc > 1 && !strcmp(argv[1], "screenshot")) screenshot = true; // // Initializes system and video memory and memory allocators. // SimpletUtil::Init(); { // // Run the test // Test(); } return 0; }
35.577778
237
0.725618
Enderderder
0281ccab2da476acf4f88b7b6f45cf1692cf0505
320
cpp
C++
main.cpp
cfiutak1/AdaptiveCacheAwareBlockQuickselect
e736585e276832d9c6d50ce67ad37e72b87129ef
[ "MIT" ]
1
2020-09-11T19:29:30.000Z
2020-09-11T19:29:30.000Z
main.cpp
cfiutak1/AdaptiveCacheAwareBlockQuickselect
e736585e276832d9c6d50ce67ad37e72b87129ef
[ "MIT" ]
null
null
null
main.cpp
cfiutak1/AdaptiveCacheAwareBlockQuickselect
e736585e276832d9c6d50ce67ad37e72b87129ef
[ "MIT" ]
null
null
null
#include <iterator> #include <algorithm> #include <cmath> #include <chrono> #include <vector> #include <cassert> #include <random> #include "adaptive_blockquickselect.hpp" //#include "BlockQuicksort/quickselect.hpp" //#include "MedianOfNinthers/src/median_of_ninthers.h" int main() { std::srand(42); }
11.428571
54
0.7125
cfiutak1
0286bd92415463a20b1fec294ade82406f00fe82
16,714
cpp
C++
msvc/EuhatExpert/Expert/peer/FileMan/FileManSubDlg.cpp
euhat/EuhatExpert
3932238a0bd72a8f12b4ae6ced1ade6482228fe0
[ "BSD-2-Clause" ]
null
null
null
msvc/EuhatExpert/Expert/peer/FileMan/FileManSubDlg.cpp
euhat/EuhatExpert
3932238a0bd72a8f12b4ae6ced1ade6482228fe0
[ "BSD-2-Clause" ]
null
null
null
msvc/EuhatExpert/Expert/peer/FileMan/FileManSubDlg.cpp
euhat/EuhatExpert
3932238a0bd72a8f12b4ae6ced1ade6482228fe0
[ "BSD-2-Clause" ]
null
null
null
#include "stdafx.h" #include "../../Expert.h" #include "../../ExpertDlg.h" #include "FileManDlg.h" #include "FileManCfgDlg.h" #include "FileManSubDlg.h" #include "../EuhatPeerDlg.h" #include "../../EuhatRightDlg.h" #include "../../EuhatLeftDlg.h" #include "FmFileDlg.h" #include <app/FileMan/client/FileManClient.h> #include <app/FileMan/common/FmLocal.h> #include <app/FileMan/common/FmScheduler.h> #include <app/FileMan/common/FmTask.h> #include <EuhatPostDefMfc.h> #define WM_USER_FILE_MAN_CLIENT_NOTIFY (WM_USER + 1) FileManSubDlg::FileManSubDlg(EuhatBase *euhatBase) : MfcBasePage(IDD_FILE_MAN_SUB_DIALOG, euhatBase) { } FileManSubDlg::~FileManSubDlg() { remote_.reset(); } void FileManSubDlg::DoDataExchange(CDataExchange *pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(FileManSubDlg, CDialogEx) ON_WM_SIZE() ON_MESSAGE(WM_USER_FILE_MAN_CLIENT_NOTIFY, &FileManSubDlg::onFileManClientNotify) ON_BN_CLICKED(IDC_BTN_CONNECT, &FileManSubDlg::OnBnClickedBtnConnect) ON_BN_CLICKED(IDC_BTN_REMOTE_COPY_TO_LOCAL, &FileManSubDlg::OnBnClickedBtnRemoteCopyToLocal) ON_BN_CLICKED(IDC_BTN_LOCAL_COPY_TO_REMOTE, &FileManSubDlg::OnBnClickedBtnLocalCopyToRemote) ON_BN_CLICKED(IDC_BTN_REMOTE_MOVE_TO_LOCAL, &FileManSubDlg::OnBnClickedBtnRemoteMoveToLocal) ON_BN_CLICKED(IDC_BTN_LOCAL_MOVE_TO_REMOTE, &FileManSubDlg::OnBnClickedBtnLocalMoveToRemote) ON_BN_CLICKED(IDC_BTN_COPY_CLIPBOARD_TO_REMOTE, &FileManSubDlg::OnBnClickedBtnCopyClipboardToRemote) ON_BN_CLICKED(IDC_BTN_COPY_CLIPBOARD_FROM_REMOTE, &FileManSubDlg::OnBnClickedBtnCopyClipboardFromRemote) END_MESSAGE_MAP() void FileManSubDlg::fmscNotify() { PostMessage(WM_USER_FILE_MAN_CLIENT_NOTIFY); } LRESULT FileManSubDlg::onFileManClientNotify(WPARAM wParam, LPARAM lParam) { if (NULL == scheduler_.get()) return 0; scheduler_->user_->notify(); return 1; } void FileManSubDlg::correctPos() { if (NULL == GetDlgItem(IDC_LIST_REMOTE_FILE_LIST)) return; int margin = 8; int mainBtnWidth = 60; int btnHeight = 28; int cmdListHeight = 100; CRect rc; GetClientRect(&rc); correctPos(rc, margin, IDC_LIST_REMOTE_FILE_LIST, dlgRemote_.get()); correctPos(rc, margin, IDC_LIST_LOCAL_FILE_LIST, dlgLocal_.get()); CRect rcCfg; GetWindowRect(&rcCfg); euhatBase_->mainWnd_->ScreenToClient(&rcCfg); } void FileManSubDlg::correctPos(CRect &rc, int margin, int idd, MfcBasePage *dlg) { CRect rcList; GetDlgItem(idd)->GetWindowRect(&rcList); ScreenToClient(&rcList); rcList.bottom = rc.bottom - margin; dlg->MoveWindow(rcList); } BOOL FileManSubDlg::OnInitDialog() { MfcBasePage::OnInitDialog(); scheduler_.reset(new FmScheduler(this)); local_.reset(new FmLocal(scheduler_.get())); scheduler_->local_ = local_.get(); local_->start(); dlgRemote_.reset(new FmFileDlg(euhatBase_)); dlgRemote_->parentDlg_ = this; dlgRemote_->create(this); dlgLocal_.reset(new FmFileDlg(euhatBase_)); dlgLocal_->engine_ = local_.get(); dlgLocal_->isLocal_ = 1; dlgLocal_->parentDlg_ = this; dlgLocal_->create(this); browserDir(local_.get(), ""); correctPos(); return TRUE; } void FileManSubDlg::OnSize(UINT nType, int cx, int cy) { MfcBasePage::OnSize(nType, cx, cy); correctPos(); } void FileManSubDlg::browserDir(JyMsgLoop *loop, const char *dir) { scheduler_->cleanError(); shared_ptr<FmTaskGetSubList> task(new FmTaskGetSubList(loop == remote_.get() ? FmTask::TypeGetPeerSubList : FmTask::TypeGetSubList)); task->path_.reset(opStrDup(dir)); task->action_ = FmTaskGetSubList::ActionInformUi; scheduler_->add(task); scheduler_->notifyEngine(); fmscOnRefresh(); } void FileManSubDlg::fmscOnGetSubList(JyMsgLoop *loop, JyDataReadStream &ds) { if (loop == remote_.get()) { dlgRemote_->displayFiles(ds); } else { dlgLocal_->displayFiles(ds); } } void FileManSubDlg::fmscNeedReconnect() { parentDlg_->resetFileManClient(); scheduler_->notifyEngine(); scheduler_->notifyUi(); } void FileManSubDlg::fmscOnRefresh() { onClipboardFileComing(); parentDlg_->listTask_->rows_.clear(); WhMutexGuard guard(&scheduler_->mutex_); if (scheduler_->tasks_.size() == 0 && NULL != scheduler_->refreshSubListTask_.get()) { scheduler_->tasks_.push_back(scheduler_->refreshSubListTask_); scheduler_->refreshSubListTask_.reset(); scheduler_->notifyEngine(); scheduler_->notifyUi(); return; } int idx = 0; for (list<shared_ptr<FmTask>>::iterator it = scheduler_->tasks_.begin(); it != scheduler_->tasks_.end(); it++, idx++) { FmTask *t = (*it).get(); parentDlg_->listTask_->rows_.push_back(EuhatListCtrl::Row()); EuhatListCtrl::Row &row = parentDlg_->listTask_->rows_.back(); row.height_ = 18; row.cells_.push_back(EuhatListCtrl::Cell(t->id_)); string name; string detail; if (t->type_ == FmTask::TypeGetSubList || t->type_ == FmTask::TypeGetPeerSubList) { FmTaskGetSubList *task = (FmTaskGetSubList *)t; name = task->path_.get(); if (task->result_ == FmResultOk) detail = "refreshing..."; else detail = "open failed."; } else if (t->type_ == FmTask::TypeDownload) { FmTaskDownload *task = (FmTaskDownload *)t; name = task->localPath_.get(); if (task->offset_ < 0) detail = "downloading..."; else { if (task->result_ == FmResultOk) { double percent = 100.0 * (task->offset_ + task->eatGuess_) / task->totalFileSize_; char buf[1024]; sprintf(buf, "downloading %.02f%%", (float)percent); detail = buf; } else { detail = "downloading failed."; } } } else if (t->type_ == FmTask::TypeUpload) { FmTaskUpload *task = (FmTaskUpload *)t; name = task->localPath_.get(); if (task->offset_ < 0) detail = "uploading..."; else { if (task->result_ == FmResultOk) { double percent = 100.0 * (task->offset_ + task->eatGuess_) / task->totalFileSize_; char buf[1024]; sprintf(buf, "uploading %.02f%%", (float)percent); detail = buf; } else { detail = "uploading failed."; } } } else if (t->type_ == FmTask::TypeCopy || t->type_ == FmTask::TypeCopyPeer) { FmTaskCopy *task = (FmTaskCopy *)t; name = task->toPath_.get(); detail = "copying..."; } else if (t->type_ == FmTask::TypeDel || t->type_ == FmTask::TypeDelPeer) { FmTaskDel *task = (FmTaskDel *)t; name = task->path_.get(); if (task->result_ != FmResultOk) detail = "deleting failed."; else detail = "deleting..."; } else if (t->type_ == FmTask::TypeNew || t->type_ == FmTask::TypeNewPeer) { FmTaskNew *task = (FmTaskNew *)t; name = task->path_.get(); if (task->result_ != FmResultOk) detail = "creating failed."; else detail = "creating..."; } else if (t->type_ == FmTask::TypeConnect) { FmTaskConnect *task = (FmTaskConnect *)t; name = "Connecting " + task->ip_ + ":" + intToString(task->port_) + "..."; if (task->retryTimes_ > 0) { detail = "retry times: "; detail += intToString(task->retryTimes_); } else if (task->retryTimes_ < 0) { if (task->result_ == FmResultVisitCodeMismatch) detail = "visit code mismatch."; else detail = "connected."; } } if (idx > 100) { char buf[1024]; sprintf(buf, "%d tasks left not shown...", scheduler_->tasks_.size() - idx); row.cells_.push_back(EuhatListCtrl::Cell(utf8ToWstr(buf).c_str())); break; } row.cells_.push_back(EuhatListCtrl::Cell(utf8ToWstr(name.c_str()).c_str())); row.cells_.push_back(EuhatListCtrl::Cell(utf8ToWstr(detail.c_str()).c_str())); } EuhatRect rc; ::GetClientRect(parentDlg_->listTask_->hwnd_, &rc.rc_); parentDlg_->listTask_->vscroller_->setRange(parentDlg_->listTask_->getLogicalHeight(), rc.height()); ::InvalidateRect(parentDlg_->listTask_->hwnd_, NULL, 0); } void FileManSubDlg::fmscOnGetSysInfo(JyMsgLoop *loop, JyDataReadStream &ds) { char *hostName = ds.getStr(); dlgRemote_->curDir_.isUnix_ = ds.get<short>(); remote_->isUnix_ = dlgRemote_->curDir_.isUnix_; browserDir(loop, ds.getStr()); FileManDlg *mainDlg = parentDlg_; mainDlg->cfgDlg_->saveData(hostName); mainDlg->cfgDlg_->dataToUi(); mainDlg->parentDlg_->leftDlg_->modifyItem(mainDlg->parentDlg_, hostName); } void FileManSubDlg::OnBnClickedBtnConnect() { parentDlg_->connect(); } void FileManSubDlg::newFolder(JyMsgLoop *loop) { } void FileManSubDlg::delFile(JyMsgLoop *loop) { scheduler_->cleanError(); EuhatPath parentDir; EuhatListCtrl *listCtrl; if (loop == remote_.get()) { parentDir = dlgRemote_->curDir_; listCtrl = dlgRemote_->listCtrl_.get(); } else { parentDir = dlgLocal_->curDir_; listCtrl = dlgLocal_->listCtrl_.get(); } if (!parentDir.isUnix_ && parentDir.path_.size() <= 0) return; int isToGo = 0; for (auto it = listCtrl->rows_.begin(); it != listCtrl->rows_.end(); it++) { if (!it->isSelected_) continue; if (!isToGo) { if (IDOK == MessageBox(_T("Are you sure to delete?"), _T("Warning"), MB_OKCANCEL)) { isToGo = 1; } else { return; } } string fileName = wstrToUtf8(it->cells_.front().value_.get()); if (it->cells_.size() <= 1) { shared_ptr<FmTaskGetSubList> task(new FmTaskGetSubList(loop == remote_.get() ? FmTask::TypeGetPeerSubList : FmTask::TypeGetSubList)); parentDir.goSub(fileName.c_str()); task->path_.reset(opStrDup(parentDir.toStr().c_str())); parentDir.goUp(); task->action_ = FmTaskGetSubList::ActionDel; scheduler_->add(task); } else { shared_ptr<FmTaskDel> task(new FmTaskDel(loop == remote_.get()? FmTask::TypeDelPeer : FmTask::TypeDel)); parentDir.goSub(fileName.c_str()); task->path_.reset(opStrDup(parentDir.toStr().c_str())); parentDir.goUp(); task->isFolder_ = 0; task->priority_ = 100; scheduler_->add(task); } } shared_ptr<FmTaskGetSubList> task(new FmTaskGetSubList(loop == remote_.get() ? FmTask::TypeGetPeerSubList : FmTask::TypeGetSubList)); task->path_.reset(opStrDup(parentDir.toStr().c_str())); task->action_ = FmTaskGetSubList::ActionInformUi; scheduler_->addRefreshTask(task); scheduler_->notifyEngine(); fmscOnRefresh(); } void FileManSubDlg::transfer(int isDownload, int isMove) { scheduler_->cleanError(); EuhatPath euLocal = dlgLocal_->curDir_; if (!euLocal.isUnix_ && euLocal.path_.size() <= 0) return; EuhatPath euPeer = dlgRemote_->curDir_; if (!euPeer.isUnix_ && euPeer.path_.size() <= 0) return; EuhatListCtrl *listFrom; EuhatListCtrl *listTo; if (isDownload) { listFrom = dlgRemote_->listCtrl_.get(); listTo = dlgLocal_->listCtrl_.get(); } else { listFrom = dlgLocal_->listCtrl_.get(); listTo = dlgRemote_->listCtrl_.get(); } list<EuhatListCtrl::Row *> rowsFrom; list<EuhatListCtrl::Row *> rowsAnd; for (auto it = listFrom->rows_.begin(); it != listFrom->rows_.end(); it++) { if (!it->isSelected_) continue; rowsFrom.push_back(&*it); } for (auto itTo = listTo->rows_.begin(); itTo != listTo->rows_.end(); itTo++) { for (auto itFrom = rowsFrom.begin(); itFrom != rowsFrom.end(); itFrom++) { wchar_t *strFrom = (*itFrom)->cells_.front().value_.get(); wchar_t *strTo = itTo->cells_.front().value_.get(); if (opStrCmpNoCase(strFrom, strTo) == 0) { rowsAnd.push_back(*itFrom); } } } if (rowsAnd.size() > 0) { wstring txt = L"Below files will be overwritten, Are you sure?\n"; int idx = 0; list<EuhatListCtrl::Row *>::iterator it; for (it = rowsAnd.begin(); it != rowsAnd.end() && idx < 5; it++, idx++) { txt += L"\n\t"; txt += (*it)->cells_.front().value_.get(); } if (it != rowsAnd.end()) txt += L"\n\t..."; if (IDOK != MessageBox(txt.c_str(), L"Warning", MB_OKCANCEL)) { return; } } for (auto it = rowsFrom.begin(); it != rowsFrom.end(); it++) { if (!(*it)->isSelected_) continue; string fileName = wstrToUtf8((*it)->cells_.front().value_.get()); if ((*it)->cells_.size() <= 1) { shared_ptr<FmTaskGetSubList> task(new FmTaskGetSubList(isDownload? FmTask::TypeGetPeerSubList : FmTask::TypeGetSubList)); euLocal.goSub(fileName.c_str()); if (isDownload) task->peerPath_.reset(opStrDup(euLocal.toStr().c_str())); else task->path_.reset(opStrDup(euLocal.toStr().c_str())); euLocal.goUp(); euPeer.goSub(fileName.c_str()); if (isDownload) task->path_.reset(opStrDup(euPeer.toStr().c_str())); else task->peerPath_.reset(opStrDup(euPeer.toStr().c_str())); euPeer.goUp(); task->action_ = FmTaskGetSubList::ActionDownUp; task->isMove_ = isMove; scheduler_->add(task); } else { shared_ptr<FmTaskDownload> task(isDownload ? new FmTaskDownload() : new FmTaskUpload()); euLocal.goSub(fileName.c_str()); task->localPath_.reset(opStrDup(euLocal.toStr().c_str())); euLocal.goUp(); euPeer.goSub(fileName.c_str()); task->peerPath_.reset(opStrDup(euPeer.toStr().c_str())); euPeer.goUp(); task->isMove_ = isMove; auto cellIt = (*it)->cells_.begin(); cellIt++; task->totalFileSize_ = cellIt->i_; cellIt++; cellIt++; task->lastWriteTime_ = cellIt->i_; task->offset_ = -1; scheduler_->add(task); } } shared_ptr<FmTaskGetSubList> task(new FmTaskGetSubList(isDownload ? FmTask::TypeGetSubList : FmTask::TypeGetPeerSubList)); if (isDownload) task->path_.reset(opStrDup(euLocal.toStr().c_str())); else task->path_.reset(opStrDup(euPeer.toStr().c_str())); task->action_ = FmTaskGetSubList::ActionInformUi; scheduler_->addRefreshTask(task); scheduler_->notifyEngine(); fmscOnRefresh(); } void FileManSubDlg::OnBnClickedBtnRemoteCopyToLocal() { transfer(1, 0); } void FileManSubDlg::OnBnClickedBtnLocalCopyToRemote() { transfer(0, 0); } void FileManSubDlg::OnBnClickedBtnRemoteMoveToLocal() { transfer(1, 1); } void FileManSubDlg::OnBnClickedBtnLocalMoveToRemote() { transfer(0, 1); } void FileManSubDlg::OnBnClickedBtnCopyClipboardToRemote() { EuhatPath localPath; localPath.isUnix_ = dlgLocal_->curDir_.isUnix_; string dir = "clipboard"; localPath.goSub(dir.c_str()); string fileName = "client.txt"; localPath.goSub(fileName.c_str()); opMkDir(dir.c_str()); string localPathStr = localPath.toStr(); HWND hWnd = GetSafeHwnd(); ::OpenClipboard(hWnd); HANDLE hClipMemory = ::GetClipboardData(CF_UNICODETEXT); DWORD dwLength = GlobalSize(hClipMemory); LPBYTE lpClipMemory = (LPBYTE)GlobalLock(hClipMemory); string utf8Buf = wstrToUtf8((wchar_t *)lpClipMemory); memToFile(localPathStr.c_str(), (char*)utf8Buf.c_str(), utf8Buf.length()); GlobalUnlock(hClipMemory); ::CloseClipboard(); EuhatPath remotePath; remotePath.isUnix_ = dlgRemote_->curDir_.isUnix_; remotePath.goSub(dir.c_str()); remotePath.goSub(fileName.c_str()); shared_ptr<FmTaskDownload> task(new FmTaskUpload()); task->localPath_.reset(opStrDup(localPathStr.c_str())); task->peerPath_.reset(opStrDup(remotePath.toStr(0).c_str())); task->totalFileSize_ = whGetFileSize(localPathStr.c_str()); task->lastWriteTime_ = time(NULL); task->offset_ = -1; scheduler_->add(task); scheduler_->notifyEngine(); fmscOnRefresh(); } void FileManSubDlg::OnBnClickedBtnCopyClipboardFromRemote() { EuhatPath localPath; localPath.isUnix_ = dlgLocal_->curDir_.isUnix_; string dir = "clipboard"; localPath.goSub(dir.c_str()); string fileName = "server.txt"; localPath.goSub(fileName.c_str()); opMkDir(dir.c_str()); string localPathStr = localPath.toStr(); opUnlink(localPathStr.c_str()); EuhatPath remotePath; remotePath.isUnix_ = dlgRemote_->curDir_.isUnix_; remotePath.goSub(dir.c_str()); remotePath.goSub(fileName.c_str()); shared_ptr<FmTaskDownload> task(new FmTaskDownload()); task->localPath_.reset(opStrDup(localPathStr.c_str())); task->peerPath_.reset(opStrDup(remotePath.toStr(0).c_str())); task->totalFileSize_ = 0; task->lastWriteTime_ = time(NULL); task->offset_ = -1; scheduler_->add(task); scheduler_->notifyEngine(); fmscOnRefresh(); } void FileManSubDlg::onClipboardFileComing() { EuhatPath localPath; localPath.isUnix_ = dlgLocal_->curDir_.isUnix_; string dir = "clipboard"; localPath.goSub(dir.c_str()); string fileName = "server.txt"; localPath.goSub(fileName.c_str()); opMkDir(dir.c_str()); string localPathStr = localPath.toStr(); if (!doesFileExist(localPathStr.c_str())) return; unsigned int len; unique_ptr<char[]> buf(memFromWholeFile(localPathStr.c_str(), &len)); wstring wstrBuf = utf8ToWstr(buf.get()); len = (wstrBuf.length() + 1) * sizeof(wchar_t); HANDLE hGlobalMemory = GlobalAlloc(GHND, len + 1); LPBYTE lpGlobalMemory = (LPBYTE)GlobalLock(hGlobalMemory); memcpy(lpGlobalMemory, wstrBuf.c_str(), len); GlobalUnlock(hGlobalMemory); HWND hWnd = GetSafeHwnd(); ::OpenClipboard(hWnd); ::EmptyClipboard(); ::SetClipboardData(CF_UNICODETEXT, hGlobalMemory); ::CloseClipboard(); opUnlink(localPathStr.c_str()); }
26.958065
136
0.698875
euhat
02877bf755aa8eaf21aa65649d106f0e1b00c707
3,249
cc
C++
trick_source/er7_utils/integration/beeman/src/beeman_integrator_constructor.cc
TheCivilAge/RogueKitten
0b9fbe17624e77752f6160463c6d8aa5a781aad1
[ "NASA-1.3" ]
null
null
null
trick_source/er7_utils/integration/beeman/src/beeman_integrator_constructor.cc
TheCivilAge/RogueKitten
0b9fbe17624e77752f6160463c6d8aa5a781aad1
[ "NASA-1.3" ]
null
null
null
trick_source/er7_utils/integration/beeman/src/beeman_integrator_constructor.cc
TheCivilAge/RogueKitten
0b9fbe17624e77752f6160463c6d8aa5a781aad1
[ "NASA-1.3" ]
null
null
null
/** * @if Er7UtilsUseGroups * @addtogroup Er7Utils * @{ * @addtogroup Integration * @{ * @endif */ /** * @file * Defines member functions for the class BeemanIntegratorConstructor. */ /* Purpose: () */ // System includes // Interface includes #include "er7_utils/interface/include/alloc.hh" // Integration includes #include "er7_utils/integration/core/include/integrator_constructor_utils.hh" #include "er7_utils/integration/core/include/priming_integration_controls.hh" #include "er7_utils/integration/rk2_heun/include/rk2_heun_integrator_constructor.hh" // Model includes #include "../include/beeman_integrator_constructor.hh" #include "../include/beeman_second_order_ode_integrator.hh" namespace er7_utils { // Named constructor; create an BeemanIntegratorConstructor. IntegratorConstructor* BeemanIntegratorConstructor::create_constructor ( void) { return alloc::allocate_object<BeemanIntegratorConstructor> (); } // Create a duplicate of the constructor. IntegratorConstructor * BeemanIntegratorConstructor::create_copy ( void) const { return alloc::replicate_object (*this); } // Create an Beeman integration controls. IntegrationControls * BeemanIntegratorConstructor::create_integration_controls ( void) const { return integ_utils::allocate_controls<PrimingIntegrationControls> ( *primer_constructor, 2, 2); } // Create a Heun's method state integrator for a first order ODE. FirstOrderODEIntegrator * BeemanIntegratorConstructor::create_first_order_ode_integrator ( unsigned int size, IntegrationControls & controls) const { return integ_utils::allocate_integrator<RK2HeunFirstOrderODEIntegrator> ( size, controls); } // Create an Beeman state integrator for a second order ODE. SecondOrderODEIntegrator * BeemanIntegratorConstructor::create_second_order_ode_integrator ( unsigned int size, IntegrationControls & controls) const { return integ_utils::allocate_integrator< BeemanSimpleSecondOrderODEIntegrator> ( *primer_constructor, size, controls); } // Create an Beeman state integrator for a second order ODE. SecondOrderODEIntegrator * BeemanIntegratorConstructor:: create_generalized_deriv_second_order_ode_integrator ( unsigned int position_size, unsigned int velocity_size, const GeneralizedPositionDerivativeFunctions & deriv_funs, IntegrationControls & controls) const { return integ_utils::allocate_integrator< BeemanGeneralizedDerivSecondOrderODEIntegrator> ( *primer_constructor, position_size, velocity_size, deriv_funs, controls); } #if 0 // Create an Beeman state integrator for a second order ODE. SecondOrderODEIntegrator * BeemanIntegratorConstructor:: create_generalized_step_second_order_ode_integrator ( unsigned int position_size, unsigned int velocity_size, const GeneralizedPositionStepFunctions & step_funs, IntegrationControls & controls) const { return integ_utils::allocate_integrator< BeemanGeneralizedStepSecondOrderODEIntegrator> ( *primer_constructor, position_size, velocity_size, step_funs, controls); } #endif } /** * @if Er7UtilsUseGroups * @} * @} * @endif */
24.246269
84
0.761773
TheCivilAge
0288d98acb7eb8d694d664c6cd7fc5dc8baf8af8
1,175
hpp
C++
src/JMParser.hpp
iCurlmyster/JMLang
cec9f66dcdcebfc87cdd3538c10c50bb85c2ab8e
[ "MIT" ]
null
null
null
src/JMParser.hpp
iCurlmyster/JMLang
cec9f66dcdcebfc87cdd3538c10c50bb85c2ab8e
[ "MIT" ]
null
null
null
src/JMParser.hpp
iCurlmyster/JMLang
cec9f66dcdcebfc87cdd3538c10c50bb85c2ab8e
[ "MIT" ]
null
null
null
#ifndef JMPARSER_HPP #define JMPARSER_HPP #include <string> #include <vector> #include "JMTypes.h" namespace JM { class Parser { /** * Instance variable to hold the current string being parsed. * @type std::string */ std::string parsedString; /** * Instance variable to hold the current Type the parsedString is. * @type JMType */ JMType currentType; public: Parser(); ~Parser(); /** * Method to set parsedString variable with string passed * as parameter and then match the type of what the string is and * set the currentType variable to the corresponding type. * * @param line std::string * @return JMType */ JMType evaluateParse(std::string line); /** * Method to return the current string thats held by this class * broken up by what type it is. * * @return std::vector<std::string> */ std::vector<std::string> returnParsedString(); /** * Method to split a string into a std::vector by a specfied delimiter. * * @param line std::string * @param del std::string * @return std::vector<std::string> */ static std::vector<std::string> split(std::string line, std::string del); }; } #endif
20.258621
75
0.67234
iCurlmyster
0289b5f250b067f6fcf14d97a0f4b9525b403928
3,257
cc
C++
base-usage/cplusplus/test_thread.cc
sczzq/symmetrical-spoon
aa0c27bb40a482789c7c6a7088307320a007b49b
[ "Unlicense" ]
null
null
null
base-usage/cplusplus/test_thread.cc
sczzq/symmetrical-spoon
aa0c27bb40a482789c7c6a7088307320a007b49b
[ "Unlicense" ]
null
null
null
base-usage/cplusplus/test_thread.cc
sczzq/symmetrical-spoon
aa0c27bb40a482789c7c6a7088307320a007b49b
[ "Unlicense" ]
null
null
null
#include <inttypes.h> #include <chrono> #include <cstdio> #include <cstdlib> #include <ctime> #include <string> #include <thread> #include <vector> #include <iostream> #include <atomic> #define OS_LINUX #if defined(OS_LINUX) #include <dirent.h> #include <signal.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <assert.h> #include <string.h> #endif // !OS_LINUX using namespace std; inline bool IsLittleEndian() { uint32_t x = 1; return *reinterpret_cast<char*>(&x) != 0; } static std::atomic<int>& ShouldSecondaryWait() { static std::atomic<int> should_secondary_wait{1}; return should_secondary_wait; } static std::string Key(uint64_t k) { std::string ret; if (IsLittleEndian()) { ret.append(reinterpret_cast<char*>(&k), sizeof(k)); } else { char buf[sizeof(k)]; buf[0] = k & 0xff; buf[1] = (k >> 8) & 0xff; buf[2] = (k >> 16) & 0xff; buf[3] = (k >> 24) & 0xff; buf[4] = (k >> 32) & 0xff; buf[5] = (k >> 40) & 0xff; buf[6] = (k >> 48) & 0xff; buf[7] = (k >> 56) & 0xff; ret.append(buf, sizeof(k)); } size_t i = 0, j = ret.size() - 1; while (i < j) { char tmp = ret[i]; ret[i] = ret[j]; ret[j] = tmp; ++i; --j; } return ret; } static uint64_t Key(std::string key) { assert(key.size() == sizeof(uint64_t)); size_t i = 0, j = key.size() - 1; while (i < j) { char tmp = key[i]; key[i] = key[j]; key[j] = tmp; ++i; --j; } uint64_t ret = 0; if (IsLittleEndian()) { memcpy(&ret, key.c_str(), sizeof(uint64_t)); } else { const char* buf = key.c_str(); ret |= static_cast<uint64_t>(buf[0]); ret |= (static_cast<uint64_t>(buf[1]) << 8); ret |= (static_cast<uint64_t>(buf[2]) << 16); ret |= (static_cast<uint64_t>(buf[3]) << 24); ret |= (static_cast<uint64_t>(buf[4]) << 32); ret |= (static_cast<uint64_t>(buf[5]) << 40); ret |= (static_cast<uint64_t>(buf[6]) << 48); ret |= (static_cast<uint64_t>(buf[7]) << 56); } return ret; } void secondary_instance_sigint_handler(int signal) { ShouldSecondaryWait().store(0, std::memory_order_relaxed); fprintf(stdout, "\n"); fflush(stdout); }; void RunSecondary() { ::signal(SIGINT, secondary_instance_sigint_handler); long my_pid = static_cast<long>(getpid()); std::vector<std::thread> test_threads; auto helper = [&]() { std::srand(time(nullptr)); int count = 0; int kMaxKey = 12345667; while (1 == ShouldSecondaryWait().load(std::memory_order_relaxed)) { uint64_t curr_key = std::rand() % kMaxKey; count++; fprintf(stderr, "count: %d, key: %llu\n", count, curr_key); std::this_thread::sleep_for(std::chrono::seconds(1)); } fprintf(stdout, "[process %ld] Point lookup thread finished\n", my_pid); }; test_threads.emplace_back(helper); test_threads.emplace_back(helper); test_threads.emplace_back(helper); test_threads.emplace_back(helper); test_threads.emplace_back(helper); while (1 == ShouldSecondaryWait().load(std::memory_order_relaxed)) { std::this_thread::sleep_for(std::chrono::seconds(1)); } for (auto& thr : test_threads) { thr.join(); } } int main(int argc, char** argv) { RunSecondary(); return 0; }
24.30597
76
0.61529
sczzq
028b40ad3998317c2d2901b8165ebcbcc0570857
832
cpp
C++
Engine/Plugins/2D/Paper2D/Source/Paper2DEditor/Private/PaperFlipbookFactory.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Plugins/2D/Paper2D/Source/Paper2DEditor/Private/PaperFlipbookFactory.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Plugins/2D/Paper2D/Source/Paper2DEditor/Private/PaperFlipbookFactory.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "PaperFlipbookFactory.h" #define LOCTEXT_NAMESPACE "Paper2D" ///////////////////////////////////////////////////// // UPaperFlipbookFactory UPaperFlipbookFactory::UPaperFlipbookFactory(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { bCreateNew = true; bEditAfterNew = true; SupportedClass = UPaperFlipbook::StaticClass(); } UObject* UPaperFlipbookFactory::FactoryCreateNew(UClass* Class, UObject* InParent, FName Name, EObjectFlags Flags, UObject* Context, FFeedbackContext* Warn) { UPaperFlipbook* NewFlipbook = NewObject<UPaperFlipbook>(InParent, Class, Name, Flags | RF_Transactional); { FScopedFlipbookMutator EditLock(NewFlipbook); EditLock.KeyFrames = KeyFrames; } return NewFlipbook; } #undef LOCTEXT_NAMESPACE
28.689655
156
0.746394
windystrife
028bc7541879411c849c8e67746d3f439745f7a8
937
hpp
C++
Source/Engine/ClientSubsystem/Renderer/RenderingCommon.hpp
Scapior/KompotEngine
9de8c7c6a1158198a18aa237e6a2dbe41ffb44cc
[ "MIT" ]
null
null
null
Source/Engine/ClientSubsystem/Renderer/RenderingCommon.hpp
Scapior/KompotEngine
9de8c7c6a1158198a18aa237e6a2dbe41ffb44cc
[ "MIT" ]
36
2020-10-14T15:17:46.000Z
2022-02-07T22:10:54.000Z
Source/Engine/ClientSubsystem/Renderer/RenderingCommon.hpp
Scapior/KompotEngine
9de8c7c6a1158198a18aa237e6a2dbe41ffb44cc
[ "MIT" ]
1
2019-05-12T16:59:50.000Z
2019-05-12T16:59:50.000Z
/* * RenderingCommon.hpp * Copyright (C) 2021 by Maxim Stoianov * Licensed under the MIT license. */ #pragma once #include <string_view> namespace Kompot { class Window; } namespace Kompot::Rendering { struct WindowRendererAttributes { virtual ~WindowRendererAttributes() { } }; enum class ShaderType { Vertex, Fragment, Compute }; class IShader { public: virtual ~IShader(){}; virtual std::string_view getSourceFilename() const = 0; }; class IRenderer { public: virtual ~IRenderer(){}; virtual void draw(Window* window) = 0; virtual void notifyWindowResized(Window* window) = 0; virtual WindowRendererAttributes* updateWindowAttributes(Window* window) = 0; virtual void unregisterWindow(Window* window) = 0; virtual std::string_view getName() const = 0; }; } // namespace Kompot
17.351852
81
0.629669
Scapior
028d25724e5d7df7470a92a80d20211526021349
3,715
hpp
C++
source/utils.hpp
albanbruder/BruderAlban_119902_Assignment5
9cfea32263feef896e2780dffb0726c008e899d4
[ "MIT" ]
null
null
null
source/utils.hpp
albanbruder/BruderAlban_119902_Assignment5
9cfea32263feef896e2780dffb0726c008e899d4
[ "MIT" ]
null
null
null
source/utils.hpp
albanbruder/BruderAlban_119902_Assignment5
9cfea32263feef896e2780dffb0726c008e899d4
[ "MIT" ]
null
null
null
#include <vector> #include <stdlib.h> #include <time.h> #include <algorithm> #include <math.h> #include "line.hpp" #include "segment.hpp" /** * Checks if a point p is in the bounding box spanned by points a and b. */ bool between(Point const& p, Point const& a, Point const& b) { // check for x-coordinates if(p.x < std::min(a.x, b.x) || p.x > std::max(a.x, b.x)) { return false; } // check for y-coordinates if(p.y < std::min(a.y, b.y) || p.y > std::max(a.y, b.y)) { return false; } return true; } /** * Intersects 2 lines. (not segments) * Returns the point of intersection or a point with x and y set to infinity. */ Point intersect(Line const& line1, Line const& line2) { // a1*x + b1*y = c1 float a1 = line1.b.y - line1.a.y; float b1 = line1.a.x - line1.b.x; float c1 = a1*line1.a.x + b1*line1.a.y; // a2*x + b2*y = c2 float a2 = line2.b.y - line2.a.y; float b2 = line2.a.x - line2.b.x; float c2 = a2*line2.a.x + b2*line2.a.y; float det = a1*b2 - a2*b1; // lines are parallel if(det == 0) { return Point(); } float x = (b2*c1 - b1*c2) / det; float y = (a1*c2 - a2*c1) / det; return Point{ x, y }; } /** * Intersects a line and a segment. * Returns the point of intersection or a point with x and y set to infinity. */ Point intersect(Line const& line, Segment const& segment) { Point intersection = intersect(line, Line{ segment.a, segment.b }); if(!between(intersection, segment.a, segment.b)) { return Point(); } else { return intersection; } } /** * Intersect 2 segments. */ Point intersect(Segment const& segment1, Segment const& segment2) { Point intersection = intersect(Line{ segment1.a, segment1.b }, segment2); // check for both segments if Point(x,y) is between Point a and b if(!between(intersection, segment1.a, segment1.b)) { return Point(); } else { return intersection; } } /** * Generate a random Point. */ Point generateRandomPoint(int minX, int maxX, int minY, int maxY) { float x = minX + std::rand() % (( maxX + 1 ) - minX); float y = minY + std::rand() % (( maxY + 1 ) - minY); return Point{x, y}; } /** * Generate a random vector of segments. */ std::vector<Segment> generateRandomSegements(unsigned int n, int minX, int maxX, int minY, int maxY) { // initialize the randomizer srand(time(0)); std::vector<Point> points; std::vector<Segment> segments; // as long as the list is not full while(segments.size() < n) { Point a = generateRandomPoint(minX, maxX, minY, maxY); Point b = generateRandomPoint(minX, maxX, minY, maxY); // check if line is vertical // or inverse if(a.x >= b.x) { continue; } // check if one of the points already exists auto it = std::find_if(std::cbegin(points), std::cend(points), [a, b](Point const& p) { return a.x == p.x || b.x == p.x; }); if(it != std::cend(points)) { continue; } /* std::vector<Point> intersections; bool duplicateFound = false; for(auto seg : segments) { Point intersection = intersect(seg, Segment{a, b}); if(isinf(intersection.x)) { continue; } auto it = std::find_if(std::cbegin(intersections), std::cend(intersections), [intersection](Point const& p) { return p.x == intersection.x; }); if(it != std::cend(intersections)) { duplicateFound = true; } else { intersections.push_back(intersection); } } if(duplicateFound) { continue; } points.push_back(a); points.push_back(b); for(auto p : intersections) { points.push_back(p); } */ segments.push_back({ a, b }); } return segments; }
23.814103
115
0.607268
albanbruder
028d72478ee03fe80f132207cdc39cf07d68c7fa
2,293
hpp
C++
stan/math/prim/meta/is_constant.hpp
kedartal/math
77248cf73c1110660006c9700f78d9bb7c02be1d
[ "BSD-3-Clause" ]
null
null
null
stan/math/prim/meta/is_constant.hpp
kedartal/math
77248cf73c1110660006c9700f78d9bb7c02be1d
[ "BSD-3-Clause" ]
null
null
null
stan/math/prim/meta/is_constant.hpp
kedartal/math
77248cf73c1110660006c9700f78d9bb7c02be1d
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_PRIM_META_IS_CONSTANT_HPP #define STAN_MATH_PRIM_META_IS_CONSTANT_HPP #include <stan/math/prim/fun/Eigen.hpp> #include <stan/math/prim/meta/is_eigen.hpp> #include <stan/math/prim/meta/bool_constant.hpp> #include <stan/math/prim/meta/conjunction.hpp> #include <stan/math/prim/meta/is_vector.hpp> #include <stan/math/prim/meta/require_generics.hpp> #include <type_traits> #include <vector> namespace stan { /** \ingroup type_trait * Metaprogramming struct to detect whether a given type is constant * in the mathematical sense (not the C++ <code>const</code> * sense). If the parameter type is constant, <code>value</code> * will be equal to <code>true</code>. * * The baseline implementation in this abstract base class is to * classify a type <code>T</code> as constant if it can be converted * (i.e., assigned) to a <code>double</code>. This baseline should * be overridden for any type that should be treated as a variable. * * @tparam T Type being tested. */ template <typename T, typename = void> struct is_constant : bool_constant<std::is_convertible<T, double>::value> {}; /** \ingroup type_trait * Metaprogram defining an enum <code>value</code> which * is <code>true</code> if all of the type parameters * are constant (i.e., primtive types) and * <code>false</code> otherwise. */ template <typename... T> using is_constant_all = math::conjunction<is_constant<T>...>; /** \ingroup type_trait * Defines a static member named value and sets it to true * if the type of the elements in the provided std::vector * is constant, false otherwise. This is used in * the is_constant_all metaprogram. * @tparam type of the elements in the std::vector */ template <typename T> struct is_constant<T, require_std_vector_t<T>> : bool_constant<is_constant<typename std::decay_t<T>::value_type>::value> { }; /** \ingroup type_trait * Defines a public enum named value and sets it to true * if the type of the elements in the provided Eigen Matrix * is constant, false otherwise. This is used in * the is_constant_all metaprogram. * * @tparam T type of the Eigen Matrix */ template <typename T> struct is_constant<T, require_eigen_t<T>> : bool_constant<is_constant<typename std::decay_t<T>::Scalar>::value> {}; } // namespace stan #endif
35.276923
79
0.73877
kedartal
028e4a951c4340e2adc3ea867763a7a604804e74
9,052
cpp
C++
cwinte.cpp
dylancarlson/citplus
90aedfc7047fe92bdd0d09f1eb1671d7ddcde8a3
[ "Unlicense" ]
1
2020-08-11T06:12:01.000Z
2020-08-11T06:12:01.000Z
cwinte.cpp
dylancarlson/citplus
90aedfc7047fe92bdd0d09f1eb1671d7ddcde8a3
[ "Unlicense" ]
null
null
null
cwinte.cpp
dylancarlson/citplus
90aedfc7047fe92bdd0d09f1eb1671d7ddcde8a3
[ "Unlicense" ]
null
null
null
// -------------------------------------------------------------------------- // Citadel: CWinTE.CPP // // Citadel Windows Text Editor #ifndef WINCIT #include "ctdl.h" #pragma hdrstop #include "cwindows.h" // -------------------------------------------------------------------------- // Contents Bool teHandler(EVENT evt, long param, int more, CITWINDOW *wnd) { switch (evt) { case EVT_ISCTRLID: { return (((TEINFO *)(wnd->LocalData))->ci.id == more); } case EVT_NEWWINDOW: { TEINFO *te = (TEINFO *) wnd->LocalData; te->end = strlen((char *)(te->ci.ptr)); te->cur = te->end; while (te->cur - te->start > wnd->extents.right - wnd->extents.left - 1) { te->start++; } break; } case EVT_LOSTFOCUS: // when losing focus, return cursor { TEINFO *te = (TEINFO *) wnd->LocalData; CitWindowsCsr = FALSE; cursoff(); position(logiRow, logiCol); te->focused = FALSE; (wnd->func)(EVT_DRAWINT, 0, 0, wnd); break; } case EVT_GOTFOCUS: // when getting focus, capture cursor { TEINFO *te = (TEINFO *) wnd->LocalData; CitWindowsCsr = TRUE; te->focused = TRUE; physPosition((uchar) wnd->parent->extents.top + wnd->extents.top, (uchar) wnd->parent->extents.left + wnd->extents.left + te->cur - te->start); if (!wnd->parent->flags.minimized) { if (te->ins) { curshalf(); } else { curson(); } } (wnd->func)(EVT_DRAWINT, 0, 0, wnd); break; } case EVT_DESTROY: { TEINFO *te = (TEINFO *) wnd->LocalData; if (te->ci.ptr) { freeMemG(te->ci.ptr); te->ci.ptr = NULL; } if (te->ci.more) { freeMemG(te->ci.more); te->ci.more = NULL; } break; } case EVT_DRAWINT: { TEINFO *te = (TEINFO *) wnd->LocalData; SRECT pr = wnd->parent->extents; SRECT r = wnd->extents; int attr; if (te->focused) { physPosition((uchar) wnd->parent->extents.top + wnd->extents.top, (uchar) wnd->parent->extents.left + wnd->extents.left + te->cur - te->start); attr = cfg.cattr; } else { attr = cfg.attr; } wnd->parent->extents.right = wnd->parent->extents.left + r.right; wnd->parent->extents.bottom = wnd->parent->extents.top + r.bottom; wnd->parent->extents.top += r.top; wnd->parent->extents.left += r.left; if (buildClipArray(wnd->parent)) { int i; if (te->usenopwecho) { char Output; if (cfg.nopwecho == 1) // Nothing (actually, spaces for us) { Output = 0; } else if (cfg.nopwecho) // Echo character (count if digit) { Output = cfg.nopwecho; } for (i = 0; i < te->end - te->start; i++) { char ToOutput; if (!cfg.nopwecho) // Echo it { ToOutput = ((char *)(te->ci.ptr))[te->start + i]; } else // Echo mask { // if digit - count (this is really stupid: it // should happen after the assignment. However, // we don't set the precedent here. That's in // getString()... if (isdigit(Output)) { Output++; if (!isdigit(Output)) { Output = '0'; } } ToOutput = Output; } CitWindowOutChr(wnd->parent, i, 0, ToOutput, attr); } } else { CitWindowOutStr(wnd->parent, 0, 0, (char *)(te->ci.ptr) + te->start, attr); } for (i = te->end - te->start; i < r.right - r.left; i++) { CitWindowOutChr(wnd->parent, i, 0, ' ', cfg.attr); } freeClipArray(); } wnd->parent->extents = pr; break; } case EVT_INKEY: { if (param == 13) // return string { TEINFO *te = (TEINFO *) wnd->LocalData; normalizeString((char *) te->ci.ptr); (wnd->parent->func)(EVT_CTRLRET, (long) &(te->ci), 0, wnd->parent); return (TRUE); } else if (param == ESC) // abort edit { destroyCitWindow(wnd->parent, FALSE); return (TRUE); } else if (param == 8) // backspace { TEINFO *te = (TEINFO *) wnd->LocalData; if (te->cur) { int i; te->cur--; te->end--; if (te->cur < te->start) { te->start = te->cur; } for (i = te->cur; ((char *)(te->ci.ptr))[i]; i++) { ((char *)(te->ci.ptr))[i] = ((char *)(te->ci.ptr))[i + 1]; } (wnd->func)(EVT_DRAWINT, 0, 0, wnd); } return (TRUE); } else if (param < 256 && param > 31) // add to string { TEINFO *te = (TEINFO *) wnd->LocalData; if ((te->cur < te->len) && (!te->ins || (te->end < te->len))) { if (te->ins) { int i; ((char *)(te->ci.ptr))[te->end + 1] = 0; for (i = te->end; i != te->cur; i--) { ((char *)(te->ci.ptr))[i] = ((char *)(te->ci.ptr))[i - 1]; } } ((char *)(te->ci.ptr))[te->cur] = (char) param; te->cur++; if (te->cur > te->end || te->ins) { te->end++; } while (te->cur - te->start > wnd->extents.right - wnd->extents.left - 1) { te->start++; } (wnd->func)(EVT_DRAWINT, 0, 0, wnd); } return (TRUE); } else if (param > 255) { switch (param >> 8) { case CURS_DEL: { TEINFO *te = (TEINFO *) wnd->LocalData; if (te->cur != te->end) { int i; for (i = te->cur; ((char *)(te->ci.ptr))[i]; i++) { ((char *)(te->ci.ptr))[i] = ((char *)(te->ci.ptr))[i + 1]; } te->end--; (wnd->func)(EVT_DRAWINT, 0, 0, wnd); } return (TRUE); } case CURS_INS: { TEINFO *te = (TEINFO *) wnd->LocalData; te->ins = !te->ins; if (!wnd->parent->flags.minimized) { if (te->ins) { curshalf(); } else { curson(); } } return (TRUE); } case CTL_CURS_LEFT: { TEINFO *te = (TEINFO *) wnd->LocalData; if (te->cur) { // eat up space while (te->cur && isspace(((char *)(te->ci.ptr))[te->cur - 1])) { te->cur--; } // eat up word while (te->cur && !isspace(((char *)(te->ci.ptr))[te->cur - 1])) { te->cur--; } if (te->cur < te->start) { te->start = te->cur; } (wnd->func)(EVT_DRAWINT, 0, 0, wnd); } return (TRUE); } case CTL_CURS_RIGHT: { TEINFO *te = (TEINFO *) wnd->LocalData; if (te->cur < te->end) { // eat up word while ((te->cur < te->end) && !isspace(((char *)(te->ci.ptr))[te->cur + 1])) { te->cur++; } // eat up space while ((te->cur < te->end) && isspace(((char *)(te->ci.ptr))[te->cur + 1])) { te->cur++; } if (te->cur < te->end) { te->cur++; } while (te->cur - te->start > wnd->extents.right - wnd->extents.left - 1) { te->start++; } (wnd->func)(EVT_DRAWINT, 0, 0, wnd); } return (TRUE); } case CURS_LEFT: { TEINFO *te = (TEINFO *) wnd->LocalData; if (te->cur) { te->cur--; if (te->cur < te->start) { te->start = te->cur; } (wnd->func)(EVT_DRAWINT, 0, 0, wnd); } return (TRUE); } case CURS_RIGHT: { TEINFO *te = (TEINFO *) wnd->LocalData; if (te->cur < te->end) { te->cur++; while (te->cur - te->start > wnd->extents.right - wnd->extents.left - 1) { te->start++; } (wnd->func)(EVT_DRAWINT, 0, 0, wnd); } return (TRUE); } case CURS_HOME: { TEINFO *te = (TEINFO *) wnd->LocalData; te->start = te->cur = 0; (wnd->func)(EVT_DRAWINT, 0, 0, wnd); return (TRUE); } case CURS_END: { TEINFO *te = (TEINFO *) wnd->LocalData; te->end = strlen((char *)(te->ci.ptr)); te->cur = te->end; while (te->cur - te->start > wnd->extents.right - wnd->extents.left - 1) { te->start++; } (wnd->func)(EVT_DRAWINT, 0, 0, wnd); return (TRUE); } } } return (FALSE); } default: { return (FALSE); } } return (TRUE); } #endif
19.056842
78
0.422559
dylancarlson
028fc7c23e790ff567d5c756ef09fadbcf3eda44
1,324
cpp
C++
tests/test_silence_remover.cpp
CyberSinh/chromaprint
3dbc9adeec86f1bafc7a05969766562b9217deac
[ "MIT" ]
582
2016-06-14T14:49:36.000Z
2022-03-27T16:17:57.000Z
tests/test_silence_remover.cpp
CyberSinh/chromaprint
3dbc9adeec86f1bafc7a05969766562b9217deac
[ "MIT" ]
72
2016-07-28T14:27:55.000Z
2022-03-19T18:32:44.000Z
tests/test_silence_remover.cpp
CyberSinh/chromaprint
3dbc9adeec86f1bafc7a05969766562b9217deac
[ "MIT" ]
102
2016-08-21T17:36:10.000Z
2022-02-13T15:35:44.000Z
#include <gtest/gtest.h> #include <algorithm> #include <vector> #include <fstream> #include "test_utils.h" #include "silence_remover.h" #include "audio_buffer.h" #include "utils.h" using namespace chromaprint; TEST(SilenceRemover, PassThrough) { short samples[] = { 1000, 2000, 3000, 4000, 5000, 6000 }; std::vector<short> data(samples, samples + NELEMS(samples)); AudioBuffer buffer; SilenceRemover processor(&buffer); processor.Reset(44100, 1); processor.Consume(data.data(), data.size()); processor.Flush(); ASSERT_EQ(data.size(), buffer.data().size()); for (size_t i = 0; i < data.size(); i++) { ASSERT_EQ(data[i], buffer.data()[i]) << "Signals differ at index " << i; } } TEST(SilenceRemover, RemoveLeadingSilence) { short samples1[] = { 0, 60, 0, 1000, 2000, 0, 4000, 5000, 0 }; std::vector<short> data1(samples1, samples1 + NELEMS(samples1)); short samples2[] = { 1000, 2000, 0, 4000, 5000, 0 }; std::vector<short> data2(samples2, samples2 + NELEMS(samples2)); AudioBuffer buffer; SilenceRemover processor(&buffer, 100); processor.Reset(44100, 1); processor.Consume(data1.data(), data1.size()); processor.Flush(); ASSERT_EQ(data2.size(), buffer.data().size()); for (size_t i = 0; i < data2.size(); i++) { ASSERT_EQ(data2[i], buffer.data()[i]) << "Signals differ at index " << i; } }
27.583333
75
0.679758
CyberSinh
0290b3d813d44d635d181b3bcf1ee27ab2365b82
1,362
cpp
C++
data/transcoder_evaluation_gfg/cpp/COUNT_INDEX_PAIRS_EQUAL_ELEMENTS_ARRAY.cpp
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
241
2021-07-20T08:35:20.000Z
2022-03-31T02:39:08.000Z
data/transcoder_evaluation_gfg/cpp/COUNT_INDEX_PAIRS_EQUAL_ELEMENTS_ARRAY.cpp
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
49
2021-07-22T23:18:42.000Z
2022-03-24T09:15:26.000Z
data/transcoder_evaluation_gfg/cpp/COUNT_INDEX_PAIRS_EQUAL_ELEMENTS_ARRAY.cpp
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
71
2021-07-21T05:17:52.000Z
2022-03-29T23:49:28.000Z
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // #include <iostream> #include <cstdlib> #include <string> #include <vector> #include <fstream> #include <iomanip> #include <bits/stdc++.h> using namespace std; int f_gold ( int arr [ ], int n ) { int ans = 0; for ( int i = 0; i < n; i ++ ) for ( int j = i + 1; j < n; j ++ ) if ( arr [ i ] == arr [ j ] ) ans ++; return ans; } //TOFILL int main() { int n_success = 0; vector<vector<int>> param0 {{4,6,9,16,16,21,36,41,58,60,62,73,77,81,95},{-86,-72,-26,-34,18,-62,-66},{1},{16},{-88,-80,-72,-68,-64,-26,4,14,16,22,30,32,60,74,82},{0,0,1,1,1,0,1,0,0,0,1},{3,9,10,12,17,23,27,29,42,44,59,61,71,76,78,82,84,84,89,90,93,93,97,97},{68,-40,-46,-20,-64,90},{0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1},{99,17,94,43,97,17,11,58,75,94,37,22,54,31,41,4,55,69,92,80,45,97,16,33,36,17,43,82,81,64,22,65,85,44,47,14}}; vector<int> param1 {12,3,0,0,11,9,15,5,15,23}; for(int i = 0; i < param0.size(); ++i) { if(f_filled(&param0[i].front(),param1[i]) == f_gold(&param0[i].front(),param1[i])) { n_success+=1; } } cout << "#Results:" << " " << n_success << ", " << param0.size(); return 0; }
32.428571
446
0.561674
mxl1n
02950af9a8771f70640dd8f535517ebb3b106091
5,382
cpp
C++
EncoderOpus.cpp
dcealopez/VUPlayer
ff8a5032579a0adf01740e03a9067aa2875d7af1
[ "MIT" ]
57
2017-06-05T00:10:05.000Z
2022-02-17T10:59:54.000Z
EncoderOpus.cpp
dcealopez/VUPlayer
ff8a5032579a0adf01740e03a9067aa2875d7af1
[ "MIT" ]
26
2018-07-09T00:05:46.000Z
2021-12-30T22:50:24.000Z
EncoderOpus.cpp
dcealopez/VUPlayer
ff8a5032579a0adf01740e03a9067aa2875d7af1
[ "MIT" ]
4
2019-07-31T13:31:51.000Z
2021-08-16T21:50:32.000Z
#include "EncoderOpus.h" #include "Handler.h" #include "Utility.h" #include <vector> // Minimum/maximum/default bit rates. static const int s_MinimumBitrate = 8; static const int s_MaximumBitrate = 256; static const int s_DefaultBitrate = 128; EncoderOpus::EncoderOpus() : Encoder(), m_Channels( 0 ), m_OpusEncoder( nullptr ), m_Callbacks( {} ) { } EncoderOpus::~EncoderOpus() { } int EncoderOpus::WriteCallback( void *user_data, const unsigned char *ptr, opus_int32 len ) { FILE* f = reinterpret_cast<FILE*>( user_data ); if ( ( nullptr != f ) && ( nullptr != ptr ) && ( len > 0 ) ) { fwrite( ptr, 1, len, f ); } return 0; } int EncoderOpus::CloseCallback( void *user_data ) { FILE* f = reinterpret_cast<FILE*>( user_data ); if ( nullptr != f ) { fclose( f ); } return 0; } bool EncoderOpus::Open( std::wstring& filename, const long sampleRate, const long channels, const std::optional<long> /*bitsPerSample*/, const std::string& settings ) { m_Channels = channels; OggOpusComments* opusComments = ope_comments_create(); if ( nullptr != opusComments ) { filename += L".opus"; FILE* f = _wfsopen( filename.c_str(), L"wb", _SH_DENYRW ); if ( nullptr != f ) { m_Callbacks.write = WriteCallback; m_Callbacks.close = CloseCallback; m_OpusEncoder = ope_encoder_create_callbacks( &m_Callbacks, f /*userData*/, opusComments, sampleRate, channels, 0 /*family*/, nullptr /*error*/ ); if ( nullptr != m_OpusEncoder ) { const int bitrate = 1000 * GetBitrate( settings ); ope_encoder_ctl( m_OpusEncoder, OPUS_SET_BITRATE( bitrate ) ); } } ope_comments_destroy( opusComments ); } const bool success = ( nullptr != m_OpusEncoder ); return success; } bool EncoderOpus::Write( float* samples, const long sampleCount ) { // For multi-channel streams, change from BASS to Opus channel ordering. switch ( m_Channels ) { case 3 : { // (left, right, center) -> // (left, center, right) long offset = 0; for ( long n = 0; n < sampleCount; n++, offset += m_Channels ) { std::swap( samples[ offset + 1 ], samples[ offset + 2 ] ); } break; } case 5 : { // (front left, front right, front center, rear left, rear right) -> // (front left, front center, front right, rear left, rear right) long offset = 0; for ( long n = 0; n < sampleCount; n++, offset += m_Channels ) { std::swap( samples[ offset + 1 ], samples[ offset + 2 ] ); } break; } case 6 : { // (front left, front right, front center, LFE, rear left, rear right) -> // (front left, front center, front right, rear left, rear right, LFE) long offset = 0; for ( long n = 0; n < sampleCount; n++, offset += m_Channels ) { std::swap( samples[ offset + 1 ], samples[ offset + 2 ] ); const float lfe = samples[ offset + 3 ]; const float rearL = samples[ offset + 4 ]; const float rearR = samples[ offset + 5 ]; samples[ offset + 3 ] = rearL; samples[ offset + 4 ] = rearR; samples[ offset + 5 ] = lfe; } break; } case 7 : { // (front left, front right, front center, LFE, rear center, side left, side right) -> // (front left, front center, front right, side left, side right, rear center, LFE) long offset = 0; for ( long n = 0; n < sampleCount; n++, offset += m_Channels ) { std::swap( samples[ offset + 1 ], samples[ offset + 2 ] ); const float lfe = samples[ offset + 3 ]; const float rearC = samples[ offset + 4 ]; const float sideL = samples[ offset + 5 ]; const float sideR = samples[ offset + 6 ]; samples[ offset + 3 ] = sideL; samples[ offset + 4 ] = sideR; samples[ offset + 5 ] = rearC; samples[ offset + 6 ] = lfe; } break; } case 8 : { // (front left, front right, front center, LFE, rear left, rear right, side left, side right) -> // (front left, front center, front right, side left, side right, rear left, rear right, LFE) long offset = 0; for ( long n = 0; n < sampleCount; n++, offset += m_Channels ) { std::swap( samples[ offset + 1 ], samples[ offset + 2 ] ); const float lfe = samples[ offset + 3 ]; const float rearL = samples[ offset + 4 ]; const float rearR = samples[ offset + 5 ]; const float sideL = samples[ offset + 6 ]; const float sideR = samples[ offset + 7 ]; samples[ offset + 3 ] = sideL; samples[ offset + 4 ] = sideR; samples[ offset + 5 ] = rearL; samples[ offset + 6 ] = rearR; samples[ offset + 7 ] = lfe; } break; } default: { break; } } const bool success = ( OPE_OK == ope_encoder_write_float( m_OpusEncoder, samples, sampleCount ) ); return success; } void EncoderOpus::Close() { if ( nullptr != m_OpusEncoder ) { ope_encoder_drain( m_OpusEncoder ); ope_encoder_destroy( m_OpusEncoder ); } } int EncoderOpus::GetBitrate( const std::string& settings ) { int bitrate = s_DefaultBitrate; try { bitrate = std::stoi( settings ); } catch ( ... ) { } LimitBitrate( bitrate ); return bitrate; } int EncoderOpus::GetDefaultBitrate() { return s_DefaultBitrate; } int EncoderOpus::GetMinimumBitrate() { return s_MinimumBitrate; } int EncoderOpus::GetMaximumBitrate() { return s_MaximumBitrate; } void EncoderOpus::LimitBitrate( int& bitrate ) { if ( bitrate < s_MinimumBitrate ) { bitrate = s_MinimumBitrate; } else if ( bitrate > s_MaximumBitrate ) { bitrate = s_MaximumBitrate; } }
28.17801
166
0.63861
dcealopez
029dcd2075705ce8d975377091a9464af8e6fff7
6,343
cpp
C++
src/ftxui/component/component_options.cpp
VatamanuBogdan/FTXUI
62fb6298bef19618a43aff9f09401309c307a156
[ "MIT" ]
1
2022-01-24T23:53:32.000Z
2022-01-24T23:53:32.000Z
src/ftxui/component/component_options.cpp
VatamanuBogdan/FTXUI
62fb6298bef19618a43aff9f09401309c307a156
[ "MIT" ]
null
null
null
src/ftxui/component/component_options.cpp
VatamanuBogdan/FTXUI
62fb6298bef19618a43aff9f09401309c307a156
[ "MIT" ]
null
null
null
#include "ftxui/component/component_options.hpp" #include <memory> // for allocator, shared_ptr #include "ftxui/component/animation.hpp" // for Function, Duration #include "ftxui/dom/elements.hpp" // for Element, operator|, text, bold, dim, inverted, automerge namespace ftxui { void AnimatedColorOption::Set(Color a_inactive, Color a_active, animation::Duration a_duration, animation::easing::Function a_function) { enabled = true; inactive = a_inactive; active = a_active; duration = a_duration; function = a_function; } void UnderlineOption::SetAnimation(animation::Duration d, animation::easing::Function f) { SetAnimationDuration(d); SetAnimationFunction(f); } void UnderlineOption::SetAnimationDuration(animation::Duration d) { leader_duration = d; follower_duration = d; } void UnderlineOption::SetAnimationFunction(animation::easing::Function f) { leader_function = f; follower_function = f; } void UnderlineOption::SetAnimationFunction( animation::easing::Function f_leader, animation::easing::Function f_follower) { leader_function = f_leader; follower_function = f_follower; } // static MenuOption MenuOption::Horizontal() { MenuOption option; option.direction = Direction::Right; option.entries.transform = [](EntryState state) { Element e = text(state.label); if (state.focused) e |= inverted; if (state.active) e |= bold; if (!state.focused && !state.active) e |= dim; return e; }; option.elements_infix = [] { return text(" "); }; return option; } // static MenuOption MenuOption::HorizontalAnimated() { auto option = Horizontal(); option.underline.enabled = true; return option; } // static MenuOption MenuOption::Vertical() { MenuOption option; option.entries.transform = [](EntryState state) { if (state.active) state.label = "> " + state.label; else state.label = " " + state.label; Element e = text(state.label); if (state.focused) e |= inverted; if (state.active) e |= bold; if (!state.focused && !state.active) e |= dim; return e; }; return option; } // static MenuOption MenuOption::VerticalAnimated() { auto option = MenuOption::Vertical(); option.entries.transform = [](EntryState state) { Element e = text(state.label); if (state.focused) e |= inverted; if (state.active) e |= bold; if (!state.focused && !state.active) e |= dim; return e; }; option.underline.enabled = true; return option; } // static MenuOption MenuOption::Toggle() { auto option = MenuOption::Horizontal(); option.elements_infix = [] { return text("│") | automerge; }; return option; } /// @brief Create a ButtonOption, highlighted using [] characters. // static ButtonOption ButtonOption::Ascii() { ButtonOption option; option.transform = [](EntryState s) { s.label = s.focused ? "[" + s.label + "]" // : " " + s.label + " "; return text(s.label); }; return option; } /// @brief Create a ButtonOption, inverted when focused. // static ButtonOption ButtonOption::Simple() { ButtonOption option; option.transform = [](EntryState s) { auto element = text(s.label) | borderLight; if (s.focused) element |= inverted; return element; }; return option; } /// @brief Create a ButtonOption, using animated colors. // static ButtonOption ButtonOption::Animated() { return Animated(Color::Black, Color::GrayLight, // Color::GrayDark, Color::White); } /// @brief Create a ButtonOption, using animated colors. // static ButtonOption ButtonOption::Animated(Color color) { return ButtonOption::Animated(Color::Interpolate(0.85f, color, Color::Black), Color::Interpolate(0.10f, color, Color::White), Color::Interpolate(0.10f, color, Color::Black), Color::Interpolate(0.85f, color, Color::White)); } /// @brief Create a ButtonOption, using animated colors. // static ButtonOption ButtonOption::Animated(Color background, Color foreground) { return ButtonOption::Animated(background, foreground, foreground, background); } /// @brief Create a ButtonOption, using animated colors. // static ButtonOption ButtonOption::Animated(Color background, Color foreground, Color background_focused, Color foreground_focused) { ButtonOption option; option.transform = [](EntryState s) { auto element = text(s.label) | borderEmpty; if (s.focused) element |= bold; return element; }; option.animated_colors.foreground.Set(foreground, foreground_focused); option.animated_colors.background.Set(background, background_focused); return option; } /// @brief Option for standard Checkbox. // static CheckboxOption CheckboxOption::Simple() { auto option = CheckboxOption(); option.transform = [](EntryState s) { #if defined(FTXUI_MICROSOFT_TERMINAL_FALLBACK) // Microsoft terminal do not use fonts able to render properly the default // radiobox glyph. auto prefix = text(s.state ? "[X] " : "[ ] "); #else auto prefix = text(s.state ? "▣ " : "☐ "); #endif auto t = text(s.label); if (s.active) t |= bold; if (s.focused) t |= inverted; return hbox({prefix, t}); }; return option; } /// @brief Option for standard Radiobox // static RadioboxOption RadioboxOption::Simple() { auto option = RadioboxOption(); option.transform = [](EntryState s) { #if defined(FTXUI_MICROSOFT_TERMINAL_FALLBACK) // Microsoft terminal do not use fonts able to render properly the default // radiobox glyph. auto prefix = text(s.state ? "(*) " : "( ) "); #else auto prefix = text(s.state ? "◉ " : "○ "); #endif auto t = text(s.label); if (s.active) t |= bold; if (s.focused) t |= inverted; return hbox({prefix, t}); }; return option; } } // namespace ftxui // Copyright 2022 Arthur Sonzogni. All rights reserved. // Use of this source code is governed by the MIT license that can be found in // the LICENSE file.
27.69869
98
0.63976
VatamanuBogdan
029e698687a9d36ee1095d0ed42fd2d9c03112ad
4,960
cpp
C++
deprecated_compiler/src/StringReader.cpp
Limvot/kraken
6e5a372f07a864555c0e6492de4f46ffab75bfe7
[ "MIT" ]
14
2015-12-28T10:33:33.000Z
2022-03-29T04:04:52.000Z
deprecated_compiler/src/StringReader.cpp
Limvot/kraken
6e5a372f07a864555c0e6492de4f46ffab75bfe7
[ "MIT" ]
3
2016-04-20T23:10:09.000Z
2022-01-30T21:59:56.000Z
deprecated_compiler/src/StringReader.cpp
Limvot/kraken
6e5a372f07a864555c0e6492de4f46ffab75bfe7
[ "MIT" ]
1
2016-04-20T01:02:53.000Z
2016-04-20T01:02:53.000Z
#include "StringReader.h" #include <cassert> StringReader::StringReader() { str_pos = 0; } StringReader::StringReader(std::string inputString) { str_pos = 0; setString(inputString); } StringReader::~StringReader() { //dtor } void StringReader::setString(std::string inputString) { rd_string = inputString; end_reached = false; } std::string StringReader::word(bool truncateEnd) { std::string result = getTokens(" \n\t", truncateEnd); while (result == " " || result == "\n" || result == "\t") { result = getTokens(" \n\t", truncateEnd); } return(result); } std::string StringReader::line(bool truncateEnd) { return getTokens("\n", truncateEnd); } std::string StringReader::getTokens(const char *stop_chars, bool truncateEnd) { if (str_pos >= rd_string.size()) return ""; size_t found_pos = rd_string.find_first_of(stop_chars, str_pos); if (rd_string[str_pos] == '\"') { //Find the next quote found_pos = rd_string.find("\"", str_pos+1); //Check to see if the quote is escaped int numBackslashes = 0; int countBack = 1; while (found_pos >= countBack && rd_string[found_pos-countBack] == '\\') { numBackslashes++; countBack++; } //While the quote is escaped while (numBackslashes % 2 == 1) { //find the next quote found_pos = rd_string.find("\"", found_pos+1); //Check to see if it's escaped numBackslashes = 0; countBack = 1; while (found_pos >= countBack && rd_string[found_pos-countBack] == '\\') { numBackslashes++; countBack++; } } } if (found_pos == str_pos) //We are at the endline { std::string stop_char(1, rd_string[str_pos]); str_pos++; return stop_char; } else if (found_pos == std::string::npos) //We are at the end of the file { //End of String end_reached = true; //std::cout << "Reached end of file!\n"; return ""; } else { if (truncateEnd) //If we want to get rid of the delimiting character, which is the default, don't add the last char. Note we have to increase str_pos by one manually later found_pos -= 1; if (rd_string[str_pos] == '\"') found_pos++; std::string string_section = rd_string.substr(str_pos, found_pos - str_pos + 1); str_pos = found_pos + 1; if (truncateEnd) //Ok, we didn't add the last char, but str_pos now points at that char. So we move it one ahead. str_pos++; return string_section; } } void StringReader::test() { { StringReader reader("\"x\""); assert(reader.word() == "\"x\""); assert(reader.word() == ""); } { StringReader reader("\"y\" ;\n"); assert(reader.word() == "\"y\""); assert(reader.word() == ";"); assert(reader.word() == ""); } { StringReader reader("Goal = greeting ;\n" "greeting = \"hello\" | greeting \"world\" ;\n"); assert(reader.word() == "Goal"); assert(reader.word() == "="); assert(reader.word() == "greeting"); assert(reader.word() == ";"); assert(reader.word() == "greeting"); assert(reader.word() == "="); assert(reader.word() == "\"hello\""); assert(reader.word() == "|"); assert(reader.word() == "greeting"); assert(reader.word() == "\"world\""); assert(reader.word() == ";"); assert(reader.word() == ""); } { StringReader reader("one # pretend this is a comment\n" " two\n"); assert(reader.word() == "one"); assert(reader.word() == "#"); assert(reader.line() == "pretend this is a comment"); assert(reader.word() == "two"); assert(reader.word() == ""); } { // Quoted strings can span lines. StringReader reader("x = \"\n \" ;\n"); assert(reader.word() == "x"); assert(reader.word() == "="); assert(reader.word() == "\"\n \""); assert(reader.word() == ";"); assert(reader.word() == ""); } { // Strings may contain backslash-escaped quote characters. StringReader reader( "\"abc\\\"def\\\\\\\\\\\" \"\n"); assert(reader.word() == "\"abc\\\"def\\\\\\\\\\\" \""); assert(reader.word() == ""); } { // A backslash-escaped backslash can be the last character in a string. StringReader reader( "\"\\\\\" \n"); assert(reader.word() == "\"\\\\\""); assert(reader.word() == ""); } std::cout << "StringReader tests pass\n"; }
29.700599
217
0.509879
Limvot
02a21e1be3d55119cb4936b7741881775c7b9f5e
3,117
cpp
C++
tools/relation_finder_client.cpp
fhd/relation-finder
37dec835be079e6158c1304cffcb33d43cd13393
[ "MIT" ]
1
2018-09-11T02:37:42.000Z
2018-09-11T02:37:42.000Z
tools/relation_finder_client.cpp
fhd/relation-finder
37dec835be079e6158c1304cffcb33d43cd13393
[ "MIT" ]
null
null
null
tools/relation_finder_client.cpp
fhd/relation-finder
37dec835be079e6158c1304cffcb33d43cd13393
[ "MIT" ]
null
null
null
/* * This is an example client for relation-finder, demonstrating its protocol * using Boost.Asio for network communication. * * The protocol is pretty simple, the only data send is a couple of unsigned * 32-bit integers. It basically works like this: * 1. Connect to relation-finder via TCP. * 2. Send the user ID of the first person (user A). * 3. Send the user ID of the second person (user B). * 4. Read the length of path. If that number is 0, no path could be found. * 5. Read as many user IDs as the path was long. * This is the result, the path from user A to user B. */ #include <string> #include <iostream> #include <boost/array.hpp> #include <asio.hpp> using asio::ip::tcp; uint32_t read_uint(tcp::socket& socket) { asio::error_code error; uint32_t uint; socket.read_some(asio::buffer((void*) &uint, sizeof(uint)), error); if (error) throw asio::system_error(error); return uint; } void write_uint(tcp::socket& socket, uint32_t uint) { asio::error_code error; socket.write_some(asio::buffer((void*) &uint, sizeof(uint)), error); if (error) throw asio::system_error(error); } int main(int argc, char* argv[]) { // Read address and request parameters from the commandline if (argc < 5) { std::cerr << "relation-finder-client - asks relation-finder for a " << "connection between two people" << std::endl << "Usage: relation-finder-client HOST PORT PERSON1 PERSON2" << std::endl; return 1; } std::string host = argv[1]; std::string port = argv[2]; unsigned int pid1 = atoi(argv[3]); unsigned int pid2 = atoi(argv[4]); try { // Resolve the host asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(host, port); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); tcp::resolver::iterator end; // Connect to the server tcp::socket socket(io_service); asio::error_code error = asio::error::host_not_found; while (error && endpoint_iterator != end) { socket.close(); socket.connect(*endpoint_iterator++, error); } if (error) throw asio::system_error(error); // Write the person's id write_uint(socket, pid1); // Write the other person's id write_uint(socket, pid2); // Read the length of the path int path_length = read_uint(socket); if (path_length == 0) { std::cout << "No path was found." << std::endl; } else { std::cout << "Found a path: "; // Read the path for (int i = 0; i < path_length; i++) { unsigned int node = read_uint(socket); std::cout << node; if (i != path_length - 1) std::cout << " -> "; } std::cout << std::endl; } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
30.558824
78
0.582291
fhd
02a5613c565618469ee306948cf7090e8838a3ae
1,293
cpp
C++
leetcode/cpp/qt_binary_tree_upside_down.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
5
2016-10-29T09:28:11.000Z
2019-10-19T23:02:48.000Z
leetcode/cpp/qt_binary_tree_upside_down.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
leetcode/cpp/qt_binary_tree_upside_down.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
/** * @Author: Tian Qiao <qiaotian> * @Date: 2016-07-06T23:46:38+08:00 * @Email: qiaotian@me.com * @Last modified by: qiaotian * @Last modified time: 2016-07-07T01:33:48+08:00 * @Inc: LinkedIn */ Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root. For example: Given a binary tree {1,2,3,4,5}, 1 / \ 2 3 / \ 4 5 return the root of the binary tree [4,5,2,#,#,3,1]. 4 / \ 5 2 / \ 3 1 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* upsideDownBinaryTree(TreeNode* root) { if (!root || !root->left) return root; TreeNode* cur_left = root->left; TreeNode* cur_right = root->right; TreeNode* new_root = upsideDownBinaryTree(root->left); cur_left->right = root; cur_left->left = cur_right; root->left = nullptr; root->right = nullptr; return new_root; } };
23.944444
264
0.603248
qiaotian
02a5f62e1280a8f6927bc550e79d8ad56d3f86b0
3,072
cpp
C++
mr.Sadman/Classes/GameAct/Objects/Physical/Shared/Pivot/Pivot.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
null
null
null
mr.Sadman/Classes/GameAct/Objects/Physical/Shared/Pivot/Pivot.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
3
2020-12-11T10:01:27.000Z
2022-02-13T22:12:05.000Z
mr.Sadman/Classes/GameAct/Objects/Physical/Shared/Pivot/Pivot.cpp
1pkg/dump
0ee579cb6a97ae64d5367cc624b2407d7d4b1c7b
[ "MIT" ]
null
null
null
#include "Pivot.hpp" namespace GameAct { namespace Physical { void Pivot::initialize() { Object::initialize(); getBody()->setDynamic( false ); } std::string Pivot::getResourcesName() const { return "Pivot"; } void Pivot::setAdditionalParam( std::string additionalParam ) { std::string rotationTime = ThirdParty::readToken( additionalParam ); _time = atof( rotationTime.data() ); Object::setAdditionalParam( additionalParam ); } void Pivot::setRotation( float angle ) { _angle = angle; Object::setRotation( angle ); } void Pivot::runAction( const std::string & action ) { if( action == "RotateSaw" ) { float delta = getSize().width / 2.0f; float deltaX = delta * sin( CC_DEGREES_TO_RADIANS( _angle + 90.0f ) ); float deltaY = delta * cos( CC_DEGREES_TO_RADIANS( _angle + 90.0f ) ); cocos2d::Vec2 center = getPosition(); center.x -= deltaX; center.y -= deltaY; cocos2d::Vector< cocos2d::FiniteTimeAction * > rotatePnt; cocos2d::Vec2 posit = getPosition(); posit.x += deltaX; posit.y += deltaY; for( int i = 0; i < 360; ++i ) { rotatePnt.pushBack( cocos2d::MoveTo::create( _time / 360, posit ) ); posit = rotatePoint( posit, center, 1.0f ); } auto action = cocos2d::RepeatForever::create( cocos2d::Sequence::create( rotatePnt ) ); _representation->runAction( cocos2d::RepeatForever::create( action ) ); } if( action == "FluctuatePendulum" ) { float delta = getSize().width / 2.0f; float deltaX = delta * sin( CC_DEGREES_TO_RADIANS( _angle + 90.0f ) ); float deltaY = delta * cos( CC_DEGREES_TO_RADIANS( _angle + 90.0f ) ); cocos2d::Vec2 center = getPosition(); center.x -= deltaX; center.y -= deltaY; cocos2d::Vector< cocos2d::FiniteTimeAction * > rotatePnt; cocos2d::Vec2 posit = getPosition(); posit.x += deltaX; posit.y += deltaY; for( int i = 0; i < 60; ++i ) { rotatePnt.pushBack( cocos2d::MoveTo::create( _time / 240, posit ) ); posit = rotatePoint( posit, center, 1.0f ); } for( int i = 0; i < 120; ++i ) { rotatePnt.pushBack( cocos2d::MoveTo::create( _time / 240, posit ) ); posit = rotatePoint( posit, center, -1.0f ); } for( int i = 0; i < 60; ++i ) { rotatePnt.pushBack( cocos2d::MoveTo::create( _time / 240, posit ) ); posit = rotatePoint( posit, center, 1.0f ); } auto action = cocos2d::RepeatForever::create( cocos2d::Sequence::create( rotatePnt ) ); } if( action == "Stop" || action == "Off" ) { _representation->setAnchorPoint( cocos2d::Vec2( 0.5f, 0.5f ) ); _representation->stopAllActions(); } } cocos2d::Vec2 Pivot::rotatePoint( cocos2d::Vec2 point, cocos2d::Vec2 center, float angle ) const { angle = CC_DEGREES_TO_RADIANS( angle ); float rotatedX = cos( angle ) * (point.x - center.x) + sin( angle ) * ( point.y - center.y ) + center.x; float rotatedY = -sin( angle ) * ( point.x - center.x ) + cos( angle ) * ( point.y - center.y ) + center.y; return cocos2d::Vec2( rotatedX, rotatedY ); } } }
27.185841
112
0.627279
1pkg
02a894c5184a9621599baf2368ed75fa3c656fd6
7,840
cpp
C++
Tests/DlrComLibrary/SimpleErrors.cpp
TwoUnderscorez/dlr
60dfacb9852ec022dd076c152e286b116553c905
[ "Apache-2.0" ]
307
2015-01-03T19:57:57.000Z
2022-03-30T21:22:59.000Z
Src/Tests/DlrComLibrary/SimpleErrors.cpp
rudimk/dlr-dotnet
71d11769f99d6ff1516ddbaed091a359eb46c670
[ "MS-PL" ]
72
2015-09-28T16:23:24.000Z
2022-03-14T00:47:04.000Z
Src/Tests/DlrComLibrary/SimpleErrors.cpp
rudimk/dlr-dotnet
71d11769f99d6ff1516ddbaed091a359eb46c670
[ "MS-PL" ]
85
2015-01-03T19:58:01.000Z
2021-12-23T15:47:11.000Z
// SimpleErrors.cpp : Implementation of CSimpleErrors #include "stdafx.h" #include "SimpleErrors.h" #include "corerror.h" int CSimpleErrors::s_cConstructed; int CSimpleErrors::s_cReleased; // CSimpleErrors STDMETHODIMP CSimpleErrors::genMseeAppDomainUnloaded(void) { //return MSEE_E_APPDOMAINUNLOADED; return 0x80131015; } STDMETHODIMP CSimpleErrors::genCorApplication(void) { return COR_E_APPLICATION; } STDMETHODIMP CSimpleErrors::genCorArgument(void) { return COR_E_ARGUMENT; } STDMETHODIMP CSimpleErrors::genInvalidArg(void) { return E_INVALIDARG; } STDMETHODIMP CSimpleErrors::genCorArgumentOutOfRange(void) { return COR_E_ARGUMENTOUTOFRANGE; } STDMETHODIMP CSimpleErrors::genCorArithmetic(void) { return COR_E_ARITHMETIC; } STDMETHODIMP CSimpleErrors::genErrorArithmeticOverflow(void) { return ERROR_ARITHMETIC_OVERFLOW; } STDMETHODIMP CSimpleErrors::genCorArrayTypeMismatch(void) { return COR_E_ARRAYTYPEMISMATCH; } STDMETHODIMP CSimpleErrors::genCorBadImageFormat(void) { return COR_E_BADIMAGEFORMAT; } STDMETHODIMP CSimpleErrors::genErrorBadFormat(void) { return ERROR_BAD_FORMAT; } STDMETHODIMP CSimpleErrors::genCorContextMarshal(void) { return COR_E_CONTEXTMARSHAL; } STDMETHODIMP CSimpleErrors::genNTEFail(void) { return NTE_FAIL; } STDMETHODIMP CSimpleErrors::genCorDirectoryNotFound(void) { return COR_E_DIRECTORYNOTFOUND; } STDMETHODIMP CSimpleErrors::genErrorPathNotFound(void) { return ERROR_PATH_NOT_FOUND; } STDMETHODIMP CSimpleErrors::genCorDivideByZero(void) { return COR_E_DIVIDEBYZERO; } STDMETHODIMP CSimpleErrors::genCorDuplicateWaitObject(void) { return COR_E_DUPLICATEWAITOBJECT; } STDMETHODIMP CSimpleErrors::genCorEndOfStream(void) { return COR_E_ENDOFSTREAM; } STDMETHODIMP CSimpleErrors::genCorTypeLoad(void) { return COR_E_TYPELOAD; } STDMETHODIMP CSimpleErrors::genCorException(void) { return COR_E_EXCEPTION; } STDMETHODIMP CSimpleErrors::genCorExecutionEngine(void) { return COR_E_EXECUTIONENGINE; } STDMETHODIMP CSimpleErrors::genCorFieldAccess(void) { return COR_E_FIELDACCESS; } STDMETHODIMP CSimpleErrors::genCorFileNotFound(void) { return COR_E_FILENOTFOUND; } STDMETHODIMP CSimpleErrors::genErrorFileNotFound(void) { return ERROR_FILE_NOT_FOUND; } STDMETHODIMP CSimpleErrors::genCorFormat(void) { return COR_E_FORMAT; } STDMETHODIMP CSimpleErrors::genCorIndexOutOfRange(void) { return COR_E_INDEXOUTOFRANGE; } STDMETHODIMP CSimpleErrors::genCorInvalidCast(void) { return COR_E_INVALIDCAST; } STDMETHODIMP CSimpleErrors::genNoInterface(void) { return E_NOINTERFACE; } STDMETHODIMP CSimpleErrors::genCorInvalidCOMObject(void) { return COR_E_INVALIDCOMOBJECT; } STDMETHODIMP CSimpleErrors::genCorInvalidFilterCriteria(void) { return COR_E_INVALIDFILTERCRITERIA; } STDMETHODIMP CSimpleErrors::genCorInvalidOleVariantType(void) { return COR_E_INVALIDOLEVARIANTTYPE; } STDMETHODIMP CSimpleErrors::genCorInvalidOperation(void) { return COR_E_INVALIDOPERATION; } STDMETHODIMP CSimpleErrors::genCorIO(void) { return COR_E_IO; } STDMETHODIMP CSimpleErrors::genCorMemberAccess(void) { return COR_E_MEMBERACCESS; } STDMETHODIMP CSimpleErrors::genCorMethodAccess(void) { return COR_E_METHODACCESS; } STDMETHODIMP CSimpleErrors::genCorMissingField(void) { return COR_E_MISSINGFIELD; } STDMETHODIMP CSimpleErrors::genCorMissingManifestResource(void) { return COR_E_MISSINGMANIFESTRESOURCE; } STDMETHODIMP CSimpleErrors::genCorMissingMember(void) { return COR_E_MISSINGMEMBER; } STDMETHODIMP CSimpleErrors::genCorMissingMethod(void) { return COR_E_MISSINGMETHOD; } STDMETHODIMP CSimpleErrors::genCorMulticastNotSupported(void) { return COR_E_MULTICASTNOTSUPPORTED; } STDMETHODIMP CSimpleErrors::genCorNotFiniteNumber(void) { return COR_E_NOTFINITENUMBER; } STDMETHODIMP CSimpleErrors::genNotImpl(void) { return E_NOTIMPL; } STDMETHODIMP CSimpleErrors::genCorNotSupported(void) { return COR_E_NOTSUPPORTED; } STDMETHODIMP CSimpleErrors::genCorNullReference(void) { return COR_E_NULLREFERENCE; } STDMETHODIMP CSimpleErrors::genPointer(void) { return E_POINTER; } STDMETHODIMP CSimpleErrors::genCorOutOfMemory(void) { return COR_E_OUTOFMEMORY; } STDMETHODIMP CSimpleErrors::genOutOfMemory(void) { return E_OUTOFMEMORY; } STDMETHODIMP CSimpleErrors::genCorOverflow(void) { return COR_E_OVERFLOW; } STDMETHODIMP CSimpleErrors::genCorPathTooLong(void) { return COR_E_PATHTOOLONG; } STDMETHODIMP CSimpleErrors::genErrorFilenameExcedRange(void) { return ERROR_FILENAME_EXCED_RANGE; } STDMETHODIMP CSimpleErrors::genCorRank(void) { return COR_E_RANK; } STDMETHODIMP CSimpleErrors::genCorTargetInvocation(void) { return COR_E_TARGETINVOCATION; } STDMETHODIMP CSimpleErrors::genCorReflectionTypeLoad(void) { return COR_E_REFLECTIONTYPELOAD; } STDMETHODIMP CSimpleErrors::genCorRemoting(void) { return COR_E_REMOTING; } STDMETHODIMP CSimpleErrors::genCorSafeArrayTypeMismatch(void) { return COR_E_SAFEARRAYTYPEMISMATCH; } STDMETHODIMP CSimpleErrors::genCorSecurity(void) { return COR_E_SECURITY; } STDMETHODIMP CSimpleErrors::genCorSerialization(void) { return COR_E_SERIALIZATION; } STDMETHODIMP CSimpleErrors::genCorStackOverflow(void) { return COR_E_STACKOVERFLOW; } STDMETHODIMP CSimpleErrors::genErrorStackOverflow(void) { return ERROR_STACK_OVERFLOW; } STDMETHODIMP CSimpleErrors::genCorSynchronizationLock(void) { return COR_E_SYNCHRONIZATIONLOCK; } STDMETHODIMP CSimpleErrors::genCorSystem(void) { return COR_E_SYSTEM; } STDMETHODIMP CSimpleErrors::genCorTarget(void) { return COR_E_TARGET; } STDMETHODIMP CSimpleErrors::genCorTargetParamCount(void) { return COR_E_TARGETPARAMCOUNT; } STDMETHODIMP CSimpleErrors::genCorThreadAborted(void) { return COR_E_THREADABORTED; } STDMETHODIMP CSimpleErrors::genCorThreadInterrupted(void) { return COR_E_THREADINTERRUPTED; } STDMETHODIMP CSimpleErrors::genCorThreadState(void) { return COR_E_THREADSTATE; } STDMETHODIMP CSimpleErrors::genCorThreadStop(void) { return COR_E_THREADSTOP; } STDMETHODIMP CSimpleErrors::genCorTypeInitialization(void) { return COR_E_TYPEINITIALIZATION; } STDMETHODIMP CSimpleErrors::genCorVerification(void) { return COR_E_VERIFICATION; } STDMETHODIMP CSimpleErrors::genUndefinedHresult(ULONG hresult) { return (HRESULT)hresult; } STDMETHODIMP CSimpleErrors::genDispArrayIsLocked(void) { return DISP_E_ARRAYISLOCKED ; } STDMETHODIMP CSimpleErrors::genDispBadCallee(void) { return DISP_E_BADCALLEE; } STDMETHODIMP CSimpleErrors::genDispBadIndex(void) { return DISP_E_BADINDEX; } STDMETHODIMP CSimpleErrors::genDispBadParamCount(void) { return DISP_E_BADPARAMCOUNT; } STDMETHODIMP CSimpleErrors::genDispBadVarType(void) { return DISP_E_BADVARTYPE; } STDMETHODIMP CSimpleErrors::genDispBufferTooSmall(void) { return DISP_E_BUFFERTOOSMALL; } STDMETHODIMP CSimpleErrors::genDispDivByZero(void) { return DISP_E_DIVBYZERO; } STDMETHODIMP CSimpleErrors::genDispException(void) { return DISP_E_EXCEPTION; } STDMETHODIMP CSimpleErrors::genDispMemberNotFound(void) { return DISP_E_MEMBERNOTFOUND; } STDMETHODIMP CSimpleErrors::genDispNoNamedArgs(void) { return DISP_E_NONAMEDARGS; } STDMETHODIMP CSimpleErrors::genDispNotACollection(void) { return DISP_E_NOTACOLLECTION; } STDMETHODIMP CSimpleErrors::genDispOverflow(void) { return DISP_E_OVERFLOW; } STDMETHODIMP CSimpleErrors::genDispParamNotFound(void) { return DISP_E_PARAMNOTFOUND; } STDMETHODIMP CSimpleErrors::genDispParamNotOptional(void) { return DISP_E_PARAMNOTOPTIONAL; } STDMETHODIMP CSimpleErrors::genDispTypeMismatch(void) { return DISP_E_TYPEMISMATCH; } STDMETHODIMP CSimpleErrors::genDispUnknownInterface(void) { return DISP_E_UNKNOWNINTERFACE ; } STDMETHODIMP CSimpleErrors::genDispUnknownLCID(void) { return DISP_E_UNKNOWNLCID; } STDMETHODIMP CSimpleErrors::genDispUnknownName(void) { return DISP_E_UNKNOWNNAME; }
17.5
63
0.826276
TwoUnderscorez
02a94f378ed16f784a838b13b832a3baa61b2354
5,554
cpp
C++
cynosdb/src/v20190107/model/NetAddr.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
1
2022-01-27T09:27:34.000Z
2022-01-27T09:27:34.000Z
cynosdb/src/v20190107/model/NetAddr.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
cynosdb/src/v20190107/model/NetAddr.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/cynosdb/v20190107/model/NetAddr.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cynosdb::V20190107::Model; using namespace std; NetAddr::NetAddr() : m_vipHasBeenSet(false), m_vportHasBeenSet(false), m_wanDomainHasBeenSet(false), m_wanPortHasBeenSet(false), m_netTypeHasBeenSet(false) { } CoreInternalOutcome NetAddr::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Vip") && !value["Vip"].IsNull()) { if (!value["Vip"].IsString()) { return CoreInternalOutcome(Core::Error("response `NetAddr.Vip` IsString=false incorrectly").SetRequestId(requestId)); } m_vip = string(value["Vip"].GetString()); m_vipHasBeenSet = true; } if (value.HasMember("Vport") && !value["Vport"].IsNull()) { if (!value["Vport"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `NetAddr.Vport` IsInt64=false incorrectly").SetRequestId(requestId)); } m_vport = value["Vport"].GetInt64(); m_vportHasBeenSet = true; } if (value.HasMember("WanDomain") && !value["WanDomain"].IsNull()) { if (!value["WanDomain"].IsString()) { return CoreInternalOutcome(Core::Error("response `NetAddr.WanDomain` IsString=false incorrectly").SetRequestId(requestId)); } m_wanDomain = string(value["WanDomain"].GetString()); m_wanDomainHasBeenSet = true; } if (value.HasMember("WanPort") && !value["WanPort"].IsNull()) { if (!value["WanPort"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `NetAddr.WanPort` IsInt64=false incorrectly").SetRequestId(requestId)); } m_wanPort = value["WanPort"].GetInt64(); m_wanPortHasBeenSet = true; } if (value.HasMember("NetType") && !value["NetType"].IsNull()) { if (!value["NetType"].IsString()) { return CoreInternalOutcome(Core::Error("response `NetAddr.NetType` IsString=false incorrectly").SetRequestId(requestId)); } m_netType = string(value["NetType"].GetString()); m_netTypeHasBeenSet = true; } return CoreInternalOutcome(true); } void NetAddr::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_vipHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Vip"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_vip.c_str(), allocator).Move(), allocator); } if (m_vportHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Vport"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_vport, allocator); } if (m_wanDomainHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "WanDomain"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_wanDomain.c_str(), allocator).Move(), allocator); } if (m_wanPortHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "WanPort"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_wanPort, allocator); } if (m_netTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "NetType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_netType.c_str(), allocator).Move(), allocator); } } string NetAddr::GetVip() const { return m_vip; } void NetAddr::SetVip(const string& _vip) { m_vip = _vip; m_vipHasBeenSet = true; } bool NetAddr::VipHasBeenSet() const { return m_vipHasBeenSet; } int64_t NetAddr::GetVport() const { return m_vport; } void NetAddr::SetVport(const int64_t& _vport) { m_vport = _vport; m_vportHasBeenSet = true; } bool NetAddr::VportHasBeenSet() const { return m_vportHasBeenSet; } string NetAddr::GetWanDomain() const { return m_wanDomain; } void NetAddr::SetWanDomain(const string& _wanDomain) { m_wanDomain = _wanDomain; m_wanDomainHasBeenSet = true; } bool NetAddr::WanDomainHasBeenSet() const { return m_wanDomainHasBeenSet; } int64_t NetAddr::GetWanPort() const { return m_wanPort; } void NetAddr::SetWanPort(const int64_t& _wanPort) { m_wanPort = _wanPort; m_wanPortHasBeenSet = true; } bool NetAddr::WanPortHasBeenSet() const { return m_wanPortHasBeenSet; } string NetAddr::GetNetType() const { return m_netType; } void NetAddr::SetNetType(const string& _netType) { m_netType = _netType; m_netTypeHasBeenSet = true; } bool NetAddr::NetTypeHasBeenSet() const { return m_netTypeHasBeenSet; }
25.59447
135
0.662405
suluner
02aa1c90a68e80c19bcdd0b2a1f9d1f98238024d
5,709
cpp
C++
examples/airhockey/openglwindow.cpp
LJC-DB/abcg
e771d847b17eaf1af9c0d1b383ddbb9d7416ae65
[ "MIT" ]
null
null
null
examples/airhockey/openglwindow.cpp
LJC-DB/abcg
e771d847b17eaf1af9c0d1b383ddbb9d7416ae65
[ "MIT" ]
null
null
null
examples/airhockey/openglwindow.cpp
LJC-DB/abcg
e771d847b17eaf1af9c0d1b383ddbb9d7416ae65
[ "MIT" ]
null
null
null
#include "openglwindow.hpp" #include <imgui.h> #include <string> #include "abcg.hpp" void OpenGLWindow::handleEvent(SDL_Event &event) { // Keyboard events if (event.type == SDL_KEYDOWN) { if (event.key.keysym.sym == SDLK_UP) m_gameData.m_input.set(static_cast<size_t>(Input::Up)); if (event.key.keysym.sym == SDLK_DOWN) m_gameData.m_input.set(static_cast<size_t>(Input::Down)); if (event.key.keysym.sym == SDLK_LEFT) m_gameData.m_input.set(static_cast<size_t>(Input::Left)); if (event.key.keysym.sym == SDLK_RIGHT) m_gameData.m_input.set(static_cast<size_t>(Input::Right)); if (event.key.keysym.sym == SDLK_w) m_gameData.m_input.set(static_cast<size_t>(Input::W)); if (event.key.keysym.sym == SDLK_s) m_gameData.m_input.set(static_cast<size_t>(Input::S)); if (event.key.keysym.sym == SDLK_a) m_gameData.m_input.set(static_cast<size_t>(Input::A)); if (event.key.keysym.sym == SDLK_d) m_gameData.m_input.set(static_cast<size_t>(Input::D)); } if (event.type == SDL_KEYUP) { if (event.key.keysym.sym == SDLK_UP) m_gameData.m_input.reset(static_cast<size_t>(Input::Up)); if (event.key.keysym.sym == SDLK_DOWN) m_gameData.m_input.reset(static_cast<size_t>(Input::Down)); if (event.key.keysym.sym == SDLK_LEFT) m_gameData.m_input.reset(static_cast<size_t>(Input::Left)); if (event.key.keysym.sym == SDLK_RIGHT) m_gameData.m_input.reset(static_cast<size_t>(Input::Right)); if (event.key.keysym.sym == SDLK_w) m_gameData.m_input.reset(static_cast<size_t>(Input::W)); if (event.key.keysym.sym == SDLK_s) m_gameData.m_input.reset(static_cast<size_t>(Input::S)); if (event.key.keysym.sym == SDLK_a) m_gameData.m_input.reset(static_cast<size_t>(Input::A)); if (event.key.keysym.sym == SDLK_d) m_gameData.m_input.reset(static_cast<size_t>(Input::D)); } } void OpenGLWindow::initializeGL() { // Load a new font ImGuiIO &io{ImGui::GetIO()}; auto filename{getAssetsPath() + "Inconsolata-Medium.ttf"}; m_font = io.Fonts->AddFontFromFileTTF(filename.c_str(), 60.0f); if (m_font == nullptr) { throw abcg::Exception{abcg::Exception::Runtime("Cannot load font file")}; } // Create program to render the other objects m_objectsProgram = createProgramFromFile(getAssetsPath() + "objects.vert", getAssetsPath() + "objects.frag"); abcg::glClearColor(0, 0, 0, 1); #if !defined(__EMSCRIPTEN__) abcg::glEnable(GL_PROGRAM_POINT_SIZE); #endif restart(); } void OpenGLWindow::restart() { m_gameData.m_state = State::Playing; m_player.initializeGL(m_objectsProgram); m_puck.initializeGL(m_objectsProgram); m_board.initializeGL(m_objectsProgram); } void OpenGLWindow::update() { const float deltaTime{static_cast<float>(getDeltaTime())}; // Wait 5 seconds before restarting if (m_gameData.m_state != State::Playing && m_restartWaitTimer.elapsed() > 5) { m_gameData.m_score.fill(0); restart(); return; } m_player.update(m_gameData, deltaTime); m_puck.update(m_player, m_gameData, deltaTime); if (m_gameData.m_state == State::Playing) { checkGoals(); checkWinCondition(); } } void OpenGLWindow::paintGL() { update(); abcg::glClear(GL_COLOR_BUFFER_BIT); abcg::glViewport(0, 0, m_viewportWidth, m_viewportHeight); m_player.paintGL(m_gameData); m_puck.paintGL(m_gameData); m_board.paintGL(m_gameData); } void OpenGLWindow::paintUI() { abcg::OpenGLWindow::paintUI(); { ImVec2 size; ImVec2 position; if (m_gameData.m_state == State::Playing) { size = ImVec2(180, 80); position = ImVec2((m_viewportWidth - size.x) / 2.0f, (m_viewportHeight - size.y) / 4.0f); } else { size = ImVec2(400, 85); position = ImVec2((m_viewportWidth - size.x) / 2.0f, (m_viewportHeight - size.y) / 2.0f); } ImGui::SetNextWindowPos(position); ImGui::SetNextWindowSize(size); ImGuiWindowFlags flags{ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoInputs}; ImGui::Begin(" ", nullptr, flags); ImGui::PushFont(m_font); if (m_gameData.m_state == State::WinP1) { ImGui::Text("Player 1 Wins!"); } else if (m_gameData.m_state == State::WinP2) { ImGui::Text("Player 2 Wins!"); } else { std::string text = std::to_string(m_gameData.m_score.at(0)) + std::string(" ") + std::to_string(m_gameData.m_score.at(1)); ImGui::Text(text.c_str()); } ImGui::PopFont(); ImGui::End(); } } void OpenGLWindow::resizeGL(int width, int height) { m_viewportWidth = width; m_viewportHeight = height; abcg::glClear(GL_COLOR_BUFFER_BIT); } void OpenGLWindow::terminateGL() { abcg::glDeleteProgram(m_objectsProgram); m_player.terminateGL(); m_puck.terminateGL(); m_board.terminateGL(); } void OpenGLWindow::checkGoals() { auto pos_x = abs(m_puck.m_translation.x) + m_puck.m_scale; auto pos_y = abs(m_puck.m_translation.y) + m_puck.m_scale; if (pos_x >= .9f && pos_y < .3f) { if (m_puck.m_translation.x > 0) m_gameData.m_score.at(0)++; else m_gameData.m_score.at(1)++; restart(); } } void OpenGLWindow::checkWinCondition() { if (std::any_of(std::begin(m_gameData.m_score), std::end(m_gameData.m_score), [=](int n) { return n >= 5; })) { if (m_gameData.m_score.at(0) >= 5) m_gameData.m_state = State::WinP1; else m_gameData.m_state = State::WinP2; m_restartWaitTimer.restart(); } }
30.529412
79
0.652128
LJC-DB
02ac059c16f068988bd9a138885c13f70391079a
1,589
cpp
C++
source/Ch10/Drill10.cpp
DBalazs22/UDProg-Introduction
b443a831f2e3496928593d4b5d73db141d8be17c
[ "CC0-1.0" ]
null
null
null
source/Ch10/Drill10.cpp
DBalazs22/UDProg-Introduction
b443a831f2e3496928593d4b5d73db141d8be17c
[ "CC0-1.0" ]
null
null
null
source/Ch10/Drill10.cpp
DBalazs22/UDProg-Introduction
b443a831f2e3496928593d4b5d73db141d8be17c
[ "CC0-1.0" ]
null
null
null
#include "std_lib_facilities.h" struct Point { int x,y; }; vector<Point> original_points; vector<Point> processed_points; void get_points() { int x,y; while (cin >> x >> y ) { original_points.push_back(Point{x,y}); if(original_points.size()==7) break; } } void write_points() { string name = "pontok.txt"; ofstream ost {name}; if (!ost) error ("Can't open output file ", name); for (int i=0;i<original_points.size();++i) { ost << original_points[i].x << ' ' << original_points[i].y << endl; } ost.close(); } void read_points() { int x,y; string name = "pontok.txt"; ifstream ist {name}; if (!ist) error ("Can't open input file ", name); while (ist >> x >> y) { processed_points.push_back(Point{x,y}); } } void compare() { for (int i=0; i<original_points.size(); i++) { if ((original_points[i].x!=processed_points[i].x) || (original_points[i].y!=processed_points[i].y)) error("Something's wrong"); } } int main() try{ cout << "Kérlek adj meg 7 db x és y pár egész számot\n"; get_points(); write_points(); read_points(); // eredeti vektor cout << "Eredeti pontok: \n"; for (int i=0;i<original_points.size();++i) { cout << original_points[i].x << ' ' << original_points[i].y << endl; } // beolvasott vektor cout << "Feldolgozott pontok: \n"; for (int i=0;i<processed_points.size();++i) { cout << processed_points[i].x << ' ' << processed_points[i].y << endl; } compare(); return 0; } catch (exception& e) { cout<<e.what()<<endl; return 1; } catch (...) { cerr << "Oops: unknown exception!\n"; return 2; }
16.050505
101
0.618628
DBalazs22
02ad6d84b1eaec671870f9e2ea6e046182267ef9
2,173
cc
C++
chromium/chrome/browser/geolocation/geolocation_infobar_delegate_android.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/chrome/browser/geolocation/geolocation_infobar_delegate_android.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/chrome/browser/geolocation/geolocation_infobar_delegate_android.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/geolocation/geolocation_infobar_delegate_android.h" #include "chrome/browser/android/android_theme_resources.h" #include "chrome/browser/infobars/infobar_service.h" #include "chrome/grit/generated_resources.h" #include "components/infobars/core/infobar.h" #include "components/url_formatter/elide_url.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" // static infobars::InfoBar* GeolocationInfoBarDelegateAndroid::Create( InfoBarService* infobar_service, const GURL& requesting_frame, const std::string& display_languages, const PermissionSetCallback& callback) { return infobar_service->AddInfoBar(infobar_service->CreateConfirmInfoBar( scoped_ptr<ConfirmInfoBarDelegate>(new GeolocationInfoBarDelegateAndroid( requesting_frame, display_languages, callback)))); } GeolocationInfoBarDelegateAndroid::GeolocationInfoBarDelegateAndroid( const GURL& requesting_frame, const std::string& display_languages, const PermissionSetCallback& callback) : PermissionInfobarDelegate(requesting_frame, content::PermissionType::GEOLOCATION, CONTENT_SETTINGS_TYPE_GEOLOCATION, callback), requesting_frame_(requesting_frame), display_languages_(display_languages) {} GeolocationInfoBarDelegateAndroid::~GeolocationInfoBarDelegateAndroid() {} infobars::InfoBarDelegate::InfoBarIdentifier GeolocationInfoBarDelegateAndroid::GetIdentifier() const { return GEOLOCATION_INFOBAR_DELEGATE_ANDROID; } int GeolocationInfoBarDelegateAndroid::GetIconId() const { return IDR_ANDROID_INFOBAR_GEOLOCATION; } base::string16 GeolocationInfoBarDelegateAndroid::GetMessageText() const { return l10n_util::GetStringFUTF16(IDS_GEOLOCATION_INFOBAR_QUESTION, url_formatter::FormatUrlForSecurityDisplay( requesting_frame_, display_languages_)); }
41
80
0.754257
wedataintelligence
02add380db14246448830f81bc6c9ae9dc762dba
6,669
hpp
C++
src/config/config-schema.hpp
bsc-ssrg/NORNS
4fd2d181019eceadb8b1b04a94e3756476326239
[ "MIT" ]
2
2019-11-11T11:34:56.000Z
2020-12-08T02:13:48.000Z
src/config/config-schema.hpp
bsc-ssrg/NORNS
4fd2d181019eceadb8b1b04a94e3756476326239
[ "MIT" ]
null
null
null
src/config/config-schema.hpp
bsc-ssrg/NORNS
4fd2d181019eceadb8b1b04a94e3756476326239
[ "MIT" ]
null
null
null
/************************************************************************* * Copyright (C) 2017-2019 Barcelona Supercomputing Center * * Centro Nacional de Supercomputacion * * All rights reserved. * * * * This file is part of NORNS, a service that allows other programs to * * start, track and manage asynchronous transfers of data resources * * between different storage backends. * * * * See AUTHORS file in the top level directory for information regarding * * developers and contributors. * * * * This software was developed as part of the EC H2020 funded project * * NEXTGenIO (Project ID: 671951). * * www.nextgenio.eu * * * * 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. * *************************************************************************/ #ifndef __CONFIG_SCHEMA_HPP__ #define __CONFIG_SCHEMA_HPP__ #include "file-options.hpp" #include "parsers.hpp" #include "keywords.hpp" #include "defaults.hpp" namespace norns { namespace config { using file_options::file_schema; using file_options::declare_option; using file_options::declare_list; using file_options::declare_group; using file_options::declare_file; using file_options::converter; using file_options::sec_type; using file_options::opt_type; // define the configuration file structure and declare the supported options const file_schema valid_options = declare_file({ // section for global settings declare_section( keywords::global_settings, sec_type::mandatory, declare_group({ declare_option<bool>( keywords::use_syslog, opt_type::mandatory, converter<bool>(parsers::parse_bool)), declare_option<bfs::path>( keywords::log_file, opt_type::optional, converter<bfs::path>(parsers::parse_path)), declare_option<uint32_t>( keywords::log_file_max_size, opt_type::optional, converter<uint32_t>(parsers::parse_capacity)), declare_option<bool>( keywords::dry_run, opt_type::optional, defaults::dry_run, converter<bool>(parsers::parse_bool)), declare_option<bfs::path>( keywords::global_socket, opt_type::mandatory, converter<bfs::path>(parsers::parse_path)), declare_option<bfs::path>( keywords::control_socket, opt_type::mandatory, converter<bfs::path>(parsers::parse_path)), declare_option<std::string>( keywords::bind_address, opt_type::mandatory), declare_option<uint32_t>( keywords::remote_port, opt_type::mandatory, converter<uint32_t>(parsers::parse_number)), declare_option<bfs::path>( keywords::pidfile, opt_type::mandatory, converter<bfs::path>(parsers::parse_path)), declare_option<uint32_t>( keywords::workers, opt_type::mandatory, converter<uint32_t>(parsers::parse_number)), declare_option<bfs::path>( keywords::staging_directory, opt_type::mandatory, converter<bfs::path>(parsers::parse_path)), }) ), // section for namespaces declare_section( keywords::namespaces, sec_type::optional, declare_list({ declare_option<std::string>( keywords::nsid, opt_type::mandatory), declare_option<bool>( keywords::track_contents, opt_type::mandatory, converter<bool>(parsers::parse_bool)), declare_option<bfs::path>( keywords::mountpoint, opt_type::mandatory, converter<bfs::path>(parsers::parse_existing_path)), declare_option<std::string>( keywords::type, opt_type::mandatory), declare_option<uint64_t>( keywords::capacity, opt_type::mandatory, converter<uint64_t>(parsers::parse_capacity)), declare_option<std::string>( keywords::visibility, opt_type::mandatory) }) ) }); } // namespace config } // namespace norns #endif /* __CONFIG_SCHEMA_HPP__ */
42.477707
76
0.504873
bsc-ssrg
02b01f26a2187256df07b830867909f11f98be27
8,378
cxx
C++
pandatool/src/pstatserver/pStatReader.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
pandatool/src/pstatserver/pStatReader.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
pandatool/src/pstatserver/pStatReader.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file pStatReader.cxx * @author drose * @date 2000-07-09 */ #include "pStatReader.h" #include "pStatServer.h" #include "pStatMonitor.h" #include "pStatClientControlMessage.h" #include "pStatServerControlMessage.h" #include "pStatFrameData.h" #include "pStatProperties.h" #include "datagram.h" #include "datagramIterator.h" #include "connectionManager.h" /** * */ PStatReader:: PStatReader(PStatServer *manager, PStatMonitor *monitor) : #ifdef HAVE_THREADS ConnectionReader(manager, monitor->is_thread_safe() ? 1 : 0), #else // HAVE_THREADS ConnectionReader(manager, 0), #endif // HAVE_THREADS _manager(manager), _monitor(monitor), _writer(manager, 0) { set_tcp_header_size(4); _writer.set_tcp_header_size(4); _udp_port = 0; _client_data = new PStatClientData(this); _monitor->set_client_data(_client_data); } /** * */ PStatReader:: ~PStatReader() { _manager->release_udp_port(_udp_port); } /** * This will be called by the PStatClientData in response to its close() call. * It will tell the server to let go of the reader so it can shut down its * connection. */ void PStatReader:: close() { _manager->remove_reader(_tcp_connection, this); lost_connection(); } /** * This is intended to be called only once, immediately after construction, by * the PStatListener that created it. It tells the reader about the newly- * established TCP connection to a client. */ void PStatReader:: set_tcp_connection(Connection *tcp_connection) { _tcp_connection = tcp_connection; add_connection(_tcp_connection); _udp_port = _manager->get_udp_port(); _udp_connection = _manager->open_UDP_connection(_udp_port); while (_udp_connection.is_null()) { // That UDP port was no good. Try another. _udp_port = _manager->get_udp_port(); _udp_connection = _manager->open_UDP_connection(_udp_port); } add_connection(_udp_connection); send_hello(); } /** * This is called by the PStatServer when it detects that the connection has * been lost. It should clean itself up and shut down nicely. */ void PStatReader:: lost_connection() { _client_data->_is_alive = false; _monitor->lost_connection(); _client_data.clear(); _manager->close_connection(_tcp_connection); _manager->close_connection(_udp_connection); _tcp_connection.clear(); _udp_connection.clear(); } /** * Called each frame to do what needs to be done for the monitor's user- * defined idle routines. */ void PStatReader:: idle() { dequeue_frame_data(); _monitor->idle(); } /** * Returns the monitor that this reader serves. */ PStatMonitor *PStatReader:: get_monitor() { return _monitor; } /** * Returns the current machine's hostname. */ std::string PStatReader:: get_hostname() { if (_hostname.empty()) { _hostname = ConnectionManager::get_host_name(); if (_hostname.empty()) { _hostname = "unknown"; } } return _hostname; } /** * Sends the initial greeting message to the client. */ void PStatReader:: send_hello() { PStatServerControlMessage message; message._type = PStatServerControlMessage::T_hello; message._server_hostname = get_hostname(); message._server_progname = _monitor->get_monitor_name(); message._udp_port = _udp_port; Datagram datagram; message.encode(datagram); _writer.send(datagram, _tcp_connection); } /** * Called by the net code whenever a new datagram is detected on a either the * TCP or UDP connection. */ void PStatReader:: receive_datagram(const NetDatagram &datagram) { Connection *connection = datagram.get_connection(); if (connection == _tcp_connection) { PStatClientControlMessage message; if (message.decode(datagram, _client_data)) { handle_client_control_message(message); } else if (message._type == PStatClientControlMessage::T_datagram) { handle_client_udp_data(datagram); } else { nout << "Got unexpected message from client.\n"; } } else if (connection == _udp_connection) { handle_client_udp_data(datagram); } else { nout << "Got datagram from unexpected socket.\n"; } } /** * Called when a control message has been received by the client over the TCP * connection. */ void PStatReader:: handle_client_control_message(const PStatClientControlMessage &message) { switch (message._type) { case PStatClientControlMessage::T_hello: { _client_data->set_version(message._major_version, message._minor_version); int server_major_version = get_current_pstat_major_version(); int server_minor_version = get_current_pstat_minor_version(); if (message._major_version != server_major_version || (message._major_version == server_major_version && message._minor_version > server_minor_version)) { _monitor->bad_version(message._client_hostname, message._client_progname, message._major_version, message._minor_version, server_major_version, server_minor_version); _monitor->close(); } else { _monitor->hello_from(message._client_hostname, message._client_progname); } } break; case PStatClientControlMessage::T_define_collectors: { for (int i = 0; i < (int)message._collectors.size(); i++) { _client_data->add_collector(message._collectors[i]); _monitor->new_collector(message._collectors[i]->_index); } } break; case PStatClientControlMessage::T_define_threads: { for (int i = 0; i < (int)message._names.size(); i++) { int thread_index = message._first_thread_index + i; std::string name = message._names[i]; _client_data->define_thread(thread_index, name); _monitor->new_thread(thread_index); } } break; default: nout << "Invalid control message received from client.\n"; } } /** * Called when a UDP datagram has been received by the client. This should be * a single frame's worth of data. */ void PStatReader:: handle_client_udp_data(const Datagram &datagram) { if (!_monitor->is_client_known()) { // If we haven't heard a "hello" from the client yet, we don't know what // version data it will be sending us, so we can't decode the data. // Chances are good we can't display it sensibly yet anyway. Ignore frame // data until we get that hello. return; } DatagramIterator source(datagram); if (_client_data->is_at_least(2, 1)) { // Throw away the zero byte at the beginning. int initial_byte = source.get_uint8(); nassertv(initial_byte == 0); } if (!_queued_frame_data.full()) { FrameData data; data._thread_index = source.get_uint16(); data._frame_number = source.get_uint32(); data._frame_data = new PStatFrameData; data._frame_data->read_datagram(source, _client_data); // Queue up the data till we're ready to handle it in a single-threaded // way. _queued_frame_data.push_back(data); } } /** * Called during the idle loop to pull out all the frame data that we might * have read while the threaded reader was running. */ void PStatReader:: dequeue_frame_data() { while (!_queued_frame_data.empty()) { const FrameData &data = _queued_frame_data.front(); nassertv(_client_data != nullptr); // Check to see if any new collectors have level data. int num_levels = data._frame_data->get_num_levels(); for (int i = 0; i < num_levels; i++) { int collector_index = data._frame_data->get_level_collector(i); if (!_client_data->get_collector_has_level(collector_index, data._thread_index)) { // This collector is now reporting level data, and it wasn't before. _client_data->set_collector_has_level(collector_index, data._thread_index, true); _monitor->new_collector(collector_index); } } _client_data->record_new_frame(data._thread_index, data._frame_number, data._frame_data); _monitor->new_data(data._thread_index, data._frame_number); _queued_frame_data.pop_front(); } }
28.304054
89
0.700645
cmarshall108
02b18662fc96a17a916f6576826a6c7903305d48
2,882
cpp
C++
dibot _template/DIBotFramework/CAN/can.cpp
Guvernant/DIBot
dfda9924b0fd39eca725a2724bc759e7b62ef671
[ "Apache-2.0" ]
null
null
null
dibot _template/DIBotFramework/CAN/can.cpp
Guvernant/DIBot
dfda9924b0fd39eca725a2724bc759e7b62ef671
[ "Apache-2.0" ]
null
null
null
dibot _template/DIBotFramework/CAN/can.cpp
Guvernant/DIBot
dfda9924b0fd39eca725a2724bc759e7b62ef671
[ "Apache-2.0" ]
null
null
null
#include "can.hpp" Can::Can() { } bool Can::begin() { static PORT_InitTypeDef PortInit; /* Fill PortInit structure*/ PortInit.PORT_PULL_UP = PORT_PULL_UP_OFF; PortInit.PORT_PULL_DOWN = PORT_PULL_DOWN_OFF; PortInit.PORT_PD_SHM = PORT_PD_SHM_OFF; PortInit.PORT_PD = PORT_PD_DRIVER; PortInit.PORT_GFEN = PORT_GFEN_OFF; PortInit.PORT_FUNC = PORT_FUNC_ALTER; PortInit.PORT_SPEED = PORT_SPEED_MAXFAST; PortInit.PORT_MODE = PORT_MODE_DIGITAL; /* Configure PORTA pins 7 (CAN2_RX) as input */ PortInit.PORT_OE = PORT_OE_IN; PortInit.PORT_Pin = PORT_Pin_7; PORT_Init(MDR_PORTA, &PortInit); /* Configure PORTA pins 6 (CAN2_TX) as output */ PortInit.PORT_OE = PORT_OE_OUT; PortInit.PORT_Pin = PORT_Pin_6; PORT_Init(MDR_PORTA, &PortInit); CAN_InitTypeDef sCAN; RST_CLK_PCLKcmd((RST_CLK_PCLK_RST_CLK | RST_CLK_PCLK_CAN1),ENABLE); RST_CLK_PCLKcmd(RST_CLK_PCLK_PORTA,ENABLE); CAN_BRGInit(MDR_CAN1,CAN_HCLKdiv1); /* CAN register init */ CAN_DeInit(MDR_CAN1); /* CAN cell init */ CAN_StructInit (&sCAN); sCAN.CAN_ROP = ENABLE; sCAN.CAN_SAP = ENABLE; sCAN.CAN_STM = DISABLE; sCAN.CAN_ROM = DISABLE; //сделать расчет частоты на 500кбс sCAN.CAN_PSEG = CAN_PSEG_Mul_2TQ; sCAN.CAN_SEG1 = CAN_SEG1_Mul_5TQ; sCAN.CAN_SEG2 = CAN_SEG2_Mul_5TQ; sCAN.CAN_SJW = CAN_SJW_Mul_4TQ; sCAN.CAN_SB = CAN_SB_3_SAMPLE; sCAN.CAN_BRP = 1; CAN_Init (MDR_CAN1,&sCAN); CAN_Cmd(MDR_CAN1, ENABLE); /* Disable all CAN1 interrupt */ CAN_ITConfig( MDR_CAN1, CAN_IT_GLBINTEN | CAN_IT_RXINTEN | CAN_IT_TXINTEN | CAN_IT_ERRINTEN | CAN_IT_ERROVERINTEN, DISABLE); /* Enable CAN1 interrupt from receive buffer */ CAN_RxITConfig( MDR_CAN1 ,rx_buf, ENABLE); /* Enable CAN1 interrupt from transmit buffer */ CAN_TxITConfig( MDR_CAN1 ,tx_buf, ENABLE); /* receive buffer enable */ CAN_Receive(MDR_CAN1, rx_buf, DISABLE); return true; } void Can::end() { } void Can::write() { CAN_TxMsgTypeDef TxMsg; /* transmit */ TxMsg.IDE = CAN_ID_STD; TxMsg.DLC = 0x08; TxMsg.PRIOR_0 = DISABLE; TxMsg.ID = 0x7; TxMsg.Data[1] = 0x01234567; TxMsg.Data[0] = 0x89ABCDEF; CAN_Transmit(MDR_CAN1, tx_buf, &TxMsg); uint32_t i = 0; //i это таймаут while(((CAN_GetStatus(MDR_CAN1) & CAN_STATUS_TX_READY) != RESET) && (i != 0xFFF)) { i++; } CAN_ITClearRxTxPendingBit(MDR_CAN1, tx_buf, CAN_STATUS_TX_READY); } void Can::read() { CAN_RxMsgTypeDef RxMsg; uint32_t i = 0; //i это таймаут while(((CAN_GetStatus(MDR_CAN1) & CAN_STATUS_RX_READY) == RESET) && (i != 0xFFF)) { i++; } CAN_GetRawReceivedData(MDR_CAN1, rx_buf, &RxMsg); CAN_ITClearRxTxPendingBit(MDR_CAN1, rx_buf, CAN_STATUS_RX_READY); }
23.430894
85
0.667939
Guvernant
02b4a4cd0b1806a0738989533c578016d79446a2
1,464
hpp
C++
src/types/inc/User32Utils.hpp
hessedoneen/terminal
aa54de1d648f45920996aeba1edecc67237c6642
[ "MIT" ]
34,359
2019-05-06T21:04:42.000Z
2019-05-14T22:06:43.000Z
src/types/inc/User32Utils.hpp
Ingridamilsina/terminal
788d33ce94d28e2903bc49f841ce279211b7f557
[ "MIT" ]
356
2019-05-06T21:03:35.000Z
2019-05-14T21:38:47.000Z
src/types/inc/User32Utils.hpp
Ingridamilsina/terminal
788d33ce94d28e2903bc49f841ce279211b7f557
[ "MIT" ]
3,164
2019-05-06T21:06:01.000Z
2019-05-14T20:25:52.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. // Routine Description: // - Retrieves the string resource from the current module with the given ID // from the resources files. See resource.h and the .rc definitions for valid // IDs. // Arguments: // - id - Resource ID // Return Value: // - String resource retrieved from that ID. // NOTE: `__declspec(noinline) inline`: make one AND ONLY ONE copy of this // function, and don't actually inline it __declspec(noinline) inline std::wstring GetStringResource(const UINT id) { // Calling LoadStringW with a pointer-sized storage and no length will // return a read-only pointer directly to the resource data instead of // copying it immediately into a buffer. LPWSTR readOnlyResource = nullptr; const auto length = LoadStringW(wil::GetModuleInstanceHandle(), id, reinterpret_cast<LPWSTR>(&readOnlyResource), 0); LOG_LAST_ERROR_IF(length == 0); // However, the pointer and length given are NOT guaranteed to be // zero-terminated and most uses of this data will probably want a // zero-terminated string. So we're going to construct and return a // std::wstring copy from the pointer/length since those are certainly // zero-terminated. return { readOnlyResource, gsl::narrow<size_t>(length) }; }
45.75
81
0.661202
hessedoneen
02b5e1ad621cc806ee5bd2275752aab00db6b8a8
12,117
hpp
C++
libraries/belle/Source/Modern/Music/State.hpp
jogawebb/Spaghettis
78f21ba3065ce316ef0cb84e94aecc9e8787343d
[ "Zlib", "BSD-2-Clause", "BSD-3-Clause" ]
47
2017-09-05T02:49:22.000Z
2022-01-20T08:11:47.000Z
libraries/belle/Source/Modern/Music/State.hpp
jogawebb/Spaghettis
78f21ba3065ce316ef0cb84e94aecc9e8787343d
[ "Zlib", "BSD-2-Clause", "BSD-3-Clause" ]
106
2018-05-16T14:58:52.000Z
2022-01-12T13:57:24.000Z
libraries/belle/Source/Modern/Music/State.hpp
jogawebb/Spaghettis
78f21ba3065ce316ef0cb84e94aecc9e8787343d
[ "Zlib", "BSD-2-Clause", "BSD-3-Clause" ]
11
2018-05-16T06:44:51.000Z
2021-11-10T07:04:46.000Z
/* Copyright (c) 2007-2013 William Andrew Burnson. Copyright (c) 2013-2020 Nicolas Danet. */ /* < http://opensource.org/licenses/BSD-2-Clause > */ // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- /* State while traversing the graph. */ // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- namespace belle { // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- namespace State { // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - class Clef { /* Get accidental and line depending on clef and key. */ // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: Clef() { setKeyAccidentals (mica::NoAccidentals); } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - #if PRIM_CPP11 public: Clef (const Clef&) = delete; Clef& operator = (const Clef&) = delete; #else private: Clef (const Clef&); Clef& operator = (const Clef&); #endif // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: void reset() { attributes_.clear(); actives_.clear(); keys_.clear(); setKeyAccidentals (mica::NoAccidentals); } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: void parse (NodePtr token) { mica::Concept kind = token->getObject().getAttribute (mica::Kind); mica::Concept value = token->getObject().getAttribute (mica::Value); if (kind == mica::Clef) { attributes_[kind] = value; } else if (kind == mica::KeySignature) { actives_.clear(); setKeyAccidentals (value); } else if (kind == mica::Barline) { actives_.clear(); } } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: mica::Concept getAttribute (mica::Concept concept) const { return attributes_[concept]; } mica::Concept getLinespace (mica::Concept chromatic) const { mica::Concept diatonic = mica::map (chromatic, mica::DiatonicPitch); mica::Concept linespace = mica::map (getAttribute (mica::Clef), diatonic); return linespace; } mica::Concept getAccidental (mica::Concept chromatic) { mica::Concept accidental = mica::map (chromatic, mica::Accidental); mica::Concept diatonic = mica::map (chromatic, mica::DiatonicPitch); mica::Concept letter = mica::map (diatonic, mica::Letter); mica::Concept current = actives_[diatonic]; if (current != mica::Undefined) { if (accidental == current) { return mica::Undefined; } } else if (keys_[letter] == accidental) { return mica::Undefined; } actives_[diatonic] = accidental; return accidental; } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - private: void setKeyAccidentals (mica::Concept keySignature) { keys_ = mica::MIR::Utils::getAccidentalsByLetters (keySignature); } private: Table < mica::Concept > attributes_; Table < mica::Concept > actives_; /* Active accidentals. */ Table < mica::Concept > keys_; /* Key accidentals. */ private: PRIM_LEAK_DETECTOR (Clef) }; // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - class Chord { /* Buffering chord values to define ties. */ // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: Chord() { } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - #if PRIM_CPP11 public: Chord (const Chord&) = delete; Chord& operator = (const Chord&) = delete; #else private: Chord (const Chord&); Chord& operator = (const Chord&); #endif // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: void reset() { attributes_.clear(); stamps_.clear(); } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: void parse (NodePtr island, NodePtr token, const Pointer < Stamp > & stamp) { mica::Concept kind = token->getObject().getAttribute (mica::Kind); mica::Concept value = token->getObject().getAttribute (mica::Value); if (kind == mica::Chord) { attributes_[mica::Stem] = token->getObject().getAttribute (mica::Stem); attributes_[mica::Size] = token->getObject().getAttribute (mica::Size); attributes_[mica::Status] = island->getObject().getAttribute (mica::Status); } else if (kind == mica::Note) { mica::Concept tie = token->getObject().getAttribute (mica::Tie); if (tie == mica::End) { stamps_[value] = nullptr; } else if (tie == mica::Beginning || tie == mica::Middle) { stamps_[value] = stamp; } } } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: mica::Concept getAttribute (mica::Concept concept) const { return attributes_[concept]; } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- /* Note that values are returned in context. */ public: Path getPath (mica::Concept chromatic) const { if (stamps_[chromatic] == nullptr) { return Path(); } else { return stamps_[chromatic]->getPath (stamps_[chromatic]->getContext()); } } Box getBox (mica::Concept chromatic) const { if (stamps_[chromatic] == nullptr) { return Box::empty(); } else { return stamps_[chromatic]->getBox (chromatic, stamps_[chromatic]->getContext()); } } private: Table < mica::Concept > attributes_; Table < mica::Concept, Pointer < Stamp > > stamps_; /* Stamps of active notes to determine ties. */ private: PRIM_LEAK_DETECTOR (Chord) }; // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - class Group { /* Collecting chords to define tuplets and beams. */ // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: Group() { } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - #if PRIM_CPP11 public: Group (const Group&) = delete; Group& operator = (const Group&) = delete; #else private: Group (const Group&); Group& operator = (const Group&); #endif // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: void reset() { group_.clear(); boxes_.clear(); } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: void setBox (mica::Concept concept, const Box& box) { if (concept != mica::Undefined) { boxes_[concept] = box; } } Box getBox (mica::Concept concept) const { return boxes_[concept]; } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: void add (NodePtr token) { group_.add (token); } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: const Array < NodePtr > & getTokens() const { return group_; } Array < NodePtr > reclaimTokens() { Array < NodePtr > scoped; scoped.swapWith (group_); return scoped; } private: Array < NodePtr > group_; Table < mica::Concept, Box > boxes_; private: PRIM_LEAK_DETECTOR (Group) }; // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- } // namespace State // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- } // namespace belle // ----------------------------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------------------------
34.132394
110
0.28885
jogawebb
02b5f782dd156093ddf25189a779ef8ad353b5fd
3,107
hpp
C++
src/gui/solarsys/CelestialBodyPropertiesPanel.hpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
1
2020-05-16T16:58:21.000Z
2020-05-16T16:58:21.000Z
src/gui/solarsys/CelestialBodyPropertiesPanel.hpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
null
null
null
src/gui/solarsys/CelestialBodyPropertiesPanel.hpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
null
null
null
//$Id$ //------------------------------------------------------------------------------ // CelestialBodyPropertiesPanel //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002-2011 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number NNG06CA54C // // Author: Wendy C. Shoan // Created: 2009.01.13 // /** * This is the panel for the Properties tab on the notebook on the CelestialBody * Panel. * */ //------------------------------------------------------------------------------ #ifndef CelestialBodyPropertiesPanel_hpp #define CelestialBodyPropertiesPanel_hpp #include "gmatdefs.hpp" #include "CelestialBody.hpp" #include "gmatwxdefs.hpp" #include "GuiItemManager.hpp" #include "GmatPanel.hpp" #include "GmatStaticBoxSizer.hpp" class CelestialBodyPropertiesPanel : public wxPanel { public: CelestialBodyPropertiesPanel(GmatPanel *cbPanel, wxWindow *parent, CelestialBody *body); ~CelestialBodyPropertiesPanel(); void SaveData(); void LoadData(); bool IsDataChanged() { return dataChanged;}; bool CanClosePanel() { return canClose;}; private: bool dataChanged; bool canClose; CelestialBody *theBody; GuiItemManager *guiManager; Real mu; Real eqRad; Real flat; std::string textureMap; bool muChanged; bool eqRadChanged; bool flatChanged; bool textureChanged; GmatPanel *theCBPanel; void Create(); void ResetChangeFlags(bool discardMods = false); //Event Handling DECLARE_EVENT_TABLE(); void OnMuTextCtrlChange(wxCommandEvent &event); void OnEqRadTextCtrlChange(wxCommandEvent &event); void OnFlatTextCtrlChange(wxCommandEvent &event); void OnTextureTextCtrlChange(wxCommandEvent &event); void OnBrowseButton(wxCommandEvent &event); wxString ToString(Real rval); // wx wxStaticText *muStaticText; wxStaticText *eqRadStaticText; wxStaticText *flatStaticText; wxStaticText *textureStaticText; wxStaticText *muUnitsStaticText; wxStaticText *eqRadUnitsStaticText; wxStaticText *flatUnitsStaticText; wxTextCtrl *muTextCtrl; wxTextCtrl *eqRadTextCtrl; wxTextCtrl *flatTextCtrl; wxTextCtrl *textureTextCtrl; wxBitmapButton *browseButton; /// string versions of current data wxString muString; wxString eqRadString; wxString flatString; wxString textureString; GmatStaticBoxSizer *pageSizer; /// IDs for the controls enum { ID_TEXT = 7100, ID_BUTTON_BROWSE, ID_TEXT_CTRL_MU, ID_TEXT_CTRL_EQRAD, ID_TEXT_CTRL_FLAT, ID_TEXT_CTRL_TEXTURE, }; }; #endif // CelestialBodyPropertiesPanel_hpp
26.109244
91
0.626006
ddj116
02b8d4f257288fd229dc1d940117855bd9d32eaf
2,241
cpp
C++
klib_renewal/menu_squad.cpp
asm128/gpk_samples
7875af0c9116d0c9377a2e7ade0a61364358f4b1
[ "Apache-2.0" ]
null
null
null
klib_renewal/menu_squad.cpp
asm128/gpk_samples
7875af0c9116d0c9377a2e7ade0a61364358f4b1
[ "Apache-2.0" ]
null
null
null
klib_renewal/menu_squad.cpp
asm128/gpk_samples
7875af0c9116d0c9377a2e7ade0a61364358f4b1
[ "Apache-2.0" ]
null
null
null
#include "Agent_helper.h" #include "draw.h" ::klib::SGameState drawSquadSetupMenu (::klib::SGame& instanceGame) { ::klib::drawSquadSlots(instanceGame); ::klib::SGamePlayer & player = instanceGame.Players[::klib::PLAYER_INDEX_USER]; ::gpk::array_obj<::gpk::array_pod<char_t>> menuItems = {}; ::gpk::array_obj<::gpk::view_const_char> menuItemsView = {}; menuItems .resize(player.Tactical.Squad.Size); menuItemsView .resize(menuItems.size()); static int32_t maxNameLen = 0; for(uint32_t i = 0, count = player.Tactical.Squad.Size; i < count; ++i) { char buffer[128]; if(player.Tactical.Squad.Agents[i] != -1) { const ::klib::CCharacter & playerAgent = *player.Tactical.Army[player.Tactical.Squad.Agents[i]]; maxNameLen = ::gpk::max(maxNameLen, sprintf_s(buffer, "Agent #%u: %s", i + 1, playerAgent.Name.begin())); menuItems[i] = ::gpk::view_const_string{buffer}; } else { maxNameLen = ::gpk::max(maxNameLen, sprintf_s(buffer, "Agent #%u: Empty slot", i + 1)); menuItems[i] = ::gpk::view_const_string{buffer}; } menuItemsView[i] = menuItems[i]; } static ::klib::SDrawMenuState menuState; int32_t result = ::klib::drawMenu ( menuState , instanceGame.GlobalDisplay.Screen.Color.View , instanceGame.GlobalDisplay.Screen.DepthStencil.begin() , ::gpk::view_const_string{"Squad setup"} , ::gpk::view_array<const ::gpk::view_const_char>{menuItemsView.begin(), menuItemsView.size()} , instanceGame.FrameInput , -1 , ::gpk::max(24, maxNameLen+4) ); if(menuItems.size() == (uint32_t)result) return {::klib::GAME_STATE_WELCOME_COMMANDER}; if( result < 0 || result >= (int32_t)player.Tactical.Squad.Agents.size() ) return {::klib::GAME_STATE_MENU_SQUAD_SETUP}; player.Tactical.Selection.PlayerUnit = (int16_t)result; if( player.Tactical.Squad.Agents[result] != -1 && 0 == instanceGame.FrameInput.Keys[VK_LSHIFT] ) return {::klib::GAME_STATE_MENU_EQUIPMENT}; return {::klib::GAME_STATE_MENU_EQUIPMENT, ::klib::GAME_SUBSTATE_CHARACTER}; }
43.941176
121
0.629183
asm128