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
31dbffd6b5779c68ec93537e13f905efda9a14ec
1,757
cpp
C++
src/cppLinqUnitTest/emptyTest.cpp
paolosev/cpplinq
9d631e852ebb8f3a0f134524fb82abccd799a361
[ "Apache-2.0" ]
null
null
null
src/cppLinqUnitTest/emptyTest.cpp
paolosev/cpplinq
9d631e852ebb8f3a0f134524fb82abccd799a361
[ "Apache-2.0" ]
null
null
null
src/cppLinqUnitTest/emptyTest.cpp
paolosev/cpplinq
9d631e852ebb8f3a0f134524fb82abccd799a361
[ "Apache-2.0" ]
null
null
null
// Copyright 2012 Paolo Severini // // 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 "stdafx.h" #include "CppUnitTest.h" #include "testUtils.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace UnitTest { TEST_CLASS(EmptyTest) { public: static void test() { fprintf(stdout, "empty\n"); EmptyTest t; t.Empty_EmptyContainsNoElements(); t.Empty_EmptyIsASingletonPerElementType(); } TEST_METHOD(Empty_EmptyContainsNoElements) { auto empty = IEnumerable<int>::Empty()->GetEnumerator(); Assert::IsFalse(empty->MoveNext()); } TEST_METHOD(Empty_EmptyIsASingletonPerElementType) { Assert::IsTrue(IEnumerable<int>::Empty().get() == IEnumerable<int>::Empty().get()); Assert::IsTrue(IEnumerable<long>::Empty().get() == IEnumerable<long>::Empty().get()); Assert::IsTrue(IEnumerable<std::string>::Empty().get() == IEnumerable<std::string>::Empty().get()); Assert::IsFalse((void*)IEnumerable<long>::Empty().get() == (void*)IEnumerable<int>::Empty().get()); } }; }
33.788462
112
0.627775
paolosev
31dd567dedb65314795c4b49818e6c1d792f0827
18,443
cpp
C++
library/src/Json.cpp
StratifyLabs/JsonAPI
82283d2571452d75468d508db19c328f052ecac7
[ "MIT" ]
null
null
null
library/src/Json.cpp
StratifyLabs/JsonAPI
82283d2571452d75468d508db19c328f052ecac7
[ "MIT" ]
null
null
null
library/src/Json.cpp
StratifyLabs/JsonAPI
82283d2571452d75468d508db19c328f052ecac7
[ "MIT" ]
null
null
null
// Copyright 2016-2021 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md #include <type_traits> #if USE_PRINTER #include "sys/Printer.hpp" #endif //#include "sys/Sys.hpp" #include <printer/Printer.hpp> #include <var/StackString.hpp> #include <var/StringView.hpp> #include <var/Tokenizer.hpp> #include "json/Json.hpp" printer::Printer & printer::operator<<(Printer &printer, const json::JsonValue &a) { return print_value(printer, a, ""); } printer::Printer & printer::operator<<(Printer &printer, const json::JsonError &a) { printer.key("text", a.text()); printer.key("line", var::NumberString(a.line()).string_view()); printer.key("column", var::NumberString(a.column()).string_view()); printer.key("position", var::NumberString(a.position()).string_view()); printer.key("source", a.source()); return printer; } printer::Printer &printer::print_value( Printer &printer, const json::JsonValue &a, var::StringView key) { if (a.is_object()) { json::JsonValue::KeyList key_list = a.to_object().get_key_list(); if (!key.is_empty()) { printer.print_open_object(printer.verbose_level(), key); } for (const auto &subkey : key_list) { const json::JsonValue &entry = a.to_object().at(subkey); print_value(printer, entry, subkey); } if (!key.is_empty()) { printer.print_close_object(); } } else if (a.is_array()) { if (!key.is_empty()) { printer.print_open_array(printer.verbose_level(), key); } for (u32 i = 0; i < a.to_array().count(); i++) { const json::JsonValue &entry = a.to_array().at(i); print_value(printer, entry, var::NumberString().format("[%04d]", i)); } if (!key.is_empty()) { printer.print_close_array(); } } else if (a.is_integer()) { printer.key(key, var::NumberString(a.to_integer()).string_view()); } else if (a.is_real()) { printer.key(key, var::NumberString(a.to_real()).string_view()); } else { printer.key(key, var::StringView(a.to_cstring())); } return printer; } using namespace var; using namespace json; JsonApi JsonValue::m_api; JsonValue::JsonValue() { if (api().is_valid() == false) { exit_fatal("json api missing"); } m_value = nullptr; // create() method from children are not available in the // constructor } int JsonValue::translate_json_error(int json_result) { switch (json_result) { case json_error_unknown: return -1; case json_error_out_of_memory: return -1; case json_error_stack_overflow: return -1; case json_error_cannot_open_file: return -1; case json_error_invalid_argument: return -1; case json_error_invalid_utf8: return -1; case json_error_premature_end_of_input: return -1; case json_error_end_of_input_expected: return -1; case json_error_invalid_syntax: return -1; case json_error_invalid_format: return -1; case json_error_wrong_type: return -1; case json_error_null_character: return -1; case json_error_null_value: return -1; case json_error_null_byte_in_key: return -1; case json_error_duplicate_key: return -1; case json_error_numeric_overflow: return -1; case json_error_item_not_found: return -1; case json_error_index_out_of_range: return -1; } return 0; } JsonValue::JsonValue(json_t *value) { if (api().is_valid() == false) { exit_fatal("json api missing"); } add_reference(value); } JsonValue::JsonValue(const JsonValue &value) { if (api().is_valid() == false) { exit_fatal("json api missing"); } add_reference(value.m_value); } JsonValue &JsonValue::operator=(const JsonValue &value) { if (this != &value) { api()->decref(m_value); add_reference(value.m_value); } return *this; } void JsonValue::add_reference(json_t *value) { m_value = value; api()->incref(value); } JsonValue::JsonValue(JsonValue &&a) { std::swap(m_value, a.m_value); } JsonValue &JsonValue::operator=(JsonValue &&a) { std::swap(m_value, a.m_value); return *this; } JsonValue::~JsonValue() { // only decref if object was created (not just a reference) if (m_value) { api()->decref(m_value); m_value = nullptr; } } JsonValue JsonValue::lookup(const var::StringView key_path) const { API_ASSERT(key_path.at(0) == '/'); const auto element_list = key_path.split("/"); JsonValue parent = *this; for (size_t i = 1; i < element_list.count(); i++) { const auto element = element_list.at(i); // first element is empty JsonValue child = parent.is_object() ? parent.to_object().at(element) : ( parent.is_array() ? parent.to_array().at(element.to_integer()) : parent); parent = child; } return parent; } const JsonObject &JsonValue::to_object() const { return static_cast<const JsonObject &>(*this); } JsonValue JsonObjectIterator::operator*() const noexcept { return JsonValue(m_json_value) .to_object() .at(api()->object_iter_key(m_json_iter)); } JsonObject &JsonValue::to_object() { return static_cast<JsonObject &>(*this); } const JsonArray &JsonValue::to_array() const { return static_cast<const JsonArray &>(*this); } JsonArray &JsonValue::to_array() { return static_cast<JsonArray &>(*this); } int JsonValue::create_if_not_valid() { API_RETURN_VALUE_IF_ERROR(-1); if (is_valid()) { return 0; } m_value = create(); if (m_value == nullptr) { API_SYSTEM_CALL("", -1); return -1; } return 0; } JsonValue &JsonValue::assign(const var::StringView value) { API_RETURN_VALUE_IF_ERROR(*this); if (is_string()) { API_SYSTEM_CALL( "", api()->string_setn(m_value, value.data(), value.length())); } else if (is_real()) { API_SYSTEM_CALL( "", api()->real_set(m_value, var::NumberString(value).to_float())); } else if (is_integer()) { API_SYSTEM_CALL( "", api()->integer_set(m_value, var::NumberString(value).to_integer())); } else if (is_true() || is_false()) { if (var::StringView(value) == "true") { *this = JsonTrue(); } else { *this = JsonFalse(); } } return *this; } JsonValue &JsonValue::copy(const JsonValue &value, IsDeepCopy is_deep) { api()->decref(m_value); if (is_deep == IsDeepCopy::yes) { m_value = api()->deep_copy(value.m_value); } else { m_value = api()->copy(value.m_value); } return *this; } const char *JsonValue::to_cstring() const { const char *result; if (is_string()) { result = api()->string_value(m_value); } else if (is_true()) { result = "true"; } else if (is_false()) { result = "false"; } else if (is_null()) { result = "null"; } else if (is_object()) { result = "{object}"; } else if (is_array()) { result = "[array]"; } else { result = ""; } return result; } var::String JsonValue::to_string() const { var::String result; if (is_string()) { result = api()->string_value(m_value); } else if (is_real()) { result.format("%f", api()->real_value(m_value)); } else if (is_integer()) { result.format("%ld", api()->integer_value(m_value)); } else if (is_true()) { result = "true"; } else if (is_false()) { result = "false"; } else if (is_null()) { result = "null"; } else if (is_object()) { result = "{object}"; } else if (is_array()) { result = "[array]"; } else { result = ""; } return result; } float JsonValue::to_real() const { if (is_string()) { return to_string_view().to_float(); } else if (is_integer()) { return to_integer() * 1.0f; } else if (is_real()) { return api()->real_value(m_value); } else if (is_true()) { return 1.0f; } return 0.0f; } int JsonValue::to_integer() const { if (is_string()) { return to_string_view().to_integer(); } else if (is_real()) { return to_real(); } else if (is_integer()) { return api()->integer_value(m_value); } if (is_true()) { return 1; } if (is_false()) { return 0; } if (is_null()) { return 0; } return 0; } bool JsonValue::to_bool() const { if (is_true()) { return true; } if (is_false()) { return false; } if (is_string()) { if (to_cstring() == var::StringView("true")) { return true; } return false; } if (is_integer()) { return to_integer() != 0; } if (is_real()) { return to_real() != 0.0f; } if (is_object()) { return true; } if (is_array()) { return true; } return false; } JsonObject::JsonObject() { m_value = JsonObject::create(); } JsonObject::JsonObject(const JsonObject &value) { add_reference(value.m_value); } JsonObject &JsonObject::operator=(const JsonObject &value) { api()->decref(m_value); add_reference(value.m_value); return *this; } json_t *JsonObject::create() { API_RETURN_VALUE_IF_ERROR(nullptr); json_t *result = API_SYSTEM_CALL_NULL("", api()->create_object()); return result; } json_t *JsonArray::create() { API_RETURN_VALUE_IF_ERROR(nullptr); return API_SYSTEM_CALL_NULL("", api()->create_array()); } json_t *JsonReal::create() { API_RETURN_VALUE_IF_ERROR(nullptr); return API_SYSTEM_CALL_NULL("", api()->create_real(0.0f)); } json_t *JsonInteger::create() { API_RETURN_VALUE_IF_ERROR(nullptr); return API_SYSTEM_CALL_NULL("", api()->create_integer(0)); } json_t *JsonTrue::create() { API_RETURN_VALUE_IF_ERROR(nullptr); return API_SYSTEM_CALL_NULL("", api()->create_true()); } json_t *JsonFalse::create() { API_RETURN_VALUE_IF_ERROR(nullptr); return API_SYSTEM_CALL_NULL("", api()->create_false()); } json_t *JsonString::create() { API_RETURN_VALUE_IF_ERROR(nullptr); return API_SYSTEM_CALL_NULL("", api()->create_string("")); } json_t *JsonNull::create() { API_RETURN_VALUE_IF_ERROR(nullptr); return API_SYSTEM_CALL_NULL("", api()->create_null()); } JsonObject &JsonObject::insert_bool(const var::StringView key, bool value) { if (value) { return insert(Key(key).cstring, JsonTrue()); } return insert(Key(key).cstring, JsonFalse()); } JsonObject & JsonObject::insert(const var::StringView key, const JsonValue &value) { if (create_if_not_valid() < 0) { return *this; } API_SYSTEM_CALL( "", api()->object_set(m_value, Key(key).cstring, value.m_value)); return *this; } JsonObject &JsonObject::update(const JsonValue &value, UpdateFlags o_flags) { API_RETURN_VALUE_IF_ERROR(*this); if (o_flags & UpdateFlags::existing) { API_SYSTEM_CALL("", api()->object_update_existing(m_value, value.m_value)); return *this; } if (o_flags & UpdateFlags::missing) { API_SYSTEM_CALL("", api()->object_update_missing(m_value, value.m_value)); return *this; } API_SYSTEM_CALL("", api()->object_update(m_value, value.m_value)); return *this; } JsonObject &JsonObject::remove(const var::StringView key) { API_RETURN_VALUE_IF_ERROR(*this); API_SYSTEM_CALL("", api()->object_del(m_value, Key(key).cstring)); return *this; } u32 JsonObject::count() const { return api()->object_size(m_value); } JsonObject &JsonObject::clear() { API_RETURN_VALUE_IF_ERROR(*this); API_SYSTEM_CALL("", api()->object_clear(m_value)); return *this; } JsonObject::KeyList JsonObject::get_key_list() const { const char *key; u32 count = 0; for (key = api()->object_iter_key(api()->object_iter(m_value)); key; key = api()->object_iter_key( api()->object_iter_next(m_value, api()->object_key_to_iter(key)))) { count++; } KeyList result = KeyList().reserve(count); for (key = api()->object_iter_key(api()->object_iter(m_value)); key; key = api()->object_iter_key( api()->object_iter_next(m_value, api()->object_key_to_iter(key)))) { result.push_back(key); } return result; } JsonValue JsonObject::at(const var::StringView key) const { return JsonValue(api()->object_get(m_value, Key(key).cstring)); } JsonValue JsonObject::at(size_t offset) const { size_t count = 0; for (const auto &child : *this) { if (count == offset) { return child; } count++; } return JsonValue(); } JsonValue JsonValue::find(const var::StringView path, const char *delimiter) const { const auto list = path.split(delimiter); JsonValue current = *this; auto get_offset_from_string = [](var::StringView item) { return item.pop_back().pop_back().to_unsigned_long(); }; for (const auto item : list) { if (item.is_empty()) { API_RETURN_VALUE_ASSIGN_ERROR(JsonValue(), "empty item provided", EINVAL); return JsonValue(); } if (current.is_object()) { auto next = current.to_object().at(item); if (next.is_valid()) { current = next; continue; } if (item.at(0) == '{') { const auto object_offset = get_offset_from_string(item); size_t count = 0; bool is_found = false; for (const auto &value : current.to_object()) { if (count == object_offset) { current = value; is_found = true; break; } count++; } if (!is_found) { API_RETURN_VALUE_ASSIGN_ERROR( JsonValue(), "didn't find {} offset", EINVAL); } } else { current = current.to_object().at(item); } } else if (current.is_array()) { if (item.at(0) == '[') { if (current.is_array() == false) { API_RETURN_VALUE_ASSIGN_ERROR(JsonValue(), "not an array", EINVAL); } const auto array_offset = get_offset_from_string(item); ; if (current.to_array().count() <= array_offset) { API_RETURN_VALUE_ASSIGN_ERROR( JsonValue(), "[] is beyond array", EINVAL); } current = current.to_array().at(array_offset); } else { API_RETURN_VALUE_ASSIGN_ERROR( JsonValue(), "array not specified []", EINVAL); return JsonValue(); } } if (current.is_valid() == false) { API_RETURN_VALUE_ASSIGN_ERROR(JsonValue(), "invalid path", EINVAL); return JsonValue(); } } return current; } JsonArray::JsonArray() { m_value = JsonArray::create(); } JsonArray::JsonArray(const JsonArray &value) { add_reference(value.m_value); } JsonArray &JsonArray::operator=(const JsonArray &value) { api()->decref(m_value); add_reference(value.m_value); return *this; } u32 JsonArray::count() const { return api()->array_size(m_value); } JsonValue JsonArray::at(size_t position) const { return JsonValue(api()->array_get(m_value, position)); } JsonArray::JsonArray(const var::StringList &list) { m_value = JsonArray::create(); for (const auto &entry : list) { append(JsonString(entry.cstring())); } } JsonArray::JsonArray(const var::StringViewList &list) { m_value = JsonArray::create(); for (const auto &entry : list) { append(JsonString(entry)); } } JsonArray::JsonArray(const var::Vector<float> &list) { m_value = JsonArray::create(); for (const auto &entry : list) { append(JsonReal(entry)); } } JsonArray::JsonArray(const var::Vector<u32> &list) { m_value = JsonArray::create(); for (const auto &entry : list) { append(JsonInteger(entry)); } } JsonArray::JsonArray(const var::Vector<s32> &list) { m_value = JsonArray::create(); for (const auto &entry : list) { append(JsonInteger(entry)); } } JsonArray &JsonArray::append(const JsonValue &value) { if (create_if_not_valid() < 0) { return *this; } API_SYSTEM_CALL("", api()->array_append(m_value, value.m_value)); return *this; } JsonArray &JsonArray::append(const JsonArray &array) { if (create_if_not_valid() < 0) { return *this; } API_SYSTEM_CALL("", api()->array_extend(m_value, array.m_value)); return *this; } JsonArray &JsonArray::insert(size_t position, const JsonValue &value) { if (create_if_not_valid() < 0) { return *this; } API_SYSTEM_CALL("", api()->array_insert(m_value, position, value.m_value)); return *this; } JsonArray &JsonArray::remove(size_t position) { API_RETURN_VALUE_IF_ERROR(*this); API_SYSTEM_CALL("", api()->array_remove(m_value, position)); return *this; } JsonArray &JsonArray::clear() { API_RETURN_VALUE_IF_ERROR(*this); API_SYSTEM_CALL("", api()->array_clear(m_value)); return *this; } var::StringViewList JsonArray::string_view_list() const { var::StringViewList result; result.reserve(count()); for (u32 i = 0; i < count(); i++) { result.push_back(var::StringView(at(i).to_cstring())); } return result; } var::Vector<s32> JsonArray::integer_list() const { var::Vector<s32> result; result.reserve(count()); for (u32 i = 0; i < count(); i++) { result.push_back(at(i).to_integer()); } return result; } var::Vector<float> JsonArray::float_list() const { var::Vector<float> result; result.reserve(count()); for (u32 i = 0; i < count(); i++) { result.push_back(at(i).to_real()); } return result; } var::Vector<bool> JsonArray::bool_list() const { var::Vector<bool> result; result.reserve(count()); for (u32 i = 0; i < count(); i++) { result.push_back(at(i).to_bool()); } return result; } JsonString::JsonString() { m_value = JsonString::create(); } JsonString::JsonString(const char *str) { API_RETURN_IF_ERROR(); m_value = API_SYSTEM_CALL_NULL("", api()->create_string(str)); } JsonString::JsonString(const var::StringView str) { API_RETURN_IF_ERROR(); m_value = API_SYSTEM_CALL_NULL("", api()->create_stringn(str.data(), str.length())); } JsonString::JsonString(const var::String &str) { API_RETURN_IF_ERROR(); m_value = API_SYSTEM_CALL_NULL( "", api()->create_stringn(str.cstring(), str.length())); } const char *JsonString::cstring() const { return api()->string_value(m_value); } JsonReal::JsonReal() { m_value = JsonReal::create(); } JsonReal::JsonReal(float value) { API_RETURN_IF_ERROR(); m_value = API_SYSTEM_CALL_NULL("", api()->create_real(value)); } JsonInteger::JsonInteger() { m_value = JsonInteger::create(); } JsonInteger::JsonInteger(int value) { API_RETURN_IF_ERROR(); m_value = API_SYSTEM_CALL_NULL("", api()->create_integer(value)); } JsonNull::JsonNull() { m_value = JsonNull::create(); } JsonTrue::JsonTrue() { m_value = JsonTrue::create(); } JsonFalse::JsonFalse() { m_value = JsonFalse::create(); }
24.922973
80
0.643659
StratifyLabs
31e121c416604cb2efd53cadd02509ac3d3c8f17
1,531
cpp
C++
test/test/data_dictionary_test.cpp
rnburn/satyr
07f336dfd75a73d63d0573245847f03b7700304c
[ "MIT" ]
8
2017-07-03T09:24:36.000Z
2021-07-21T07:36:58.000Z
test/test/data_dictionary_test.cpp
rnburn/satyr
07f336dfd75a73d63d0573245847f03b7700304c
[ "MIT" ]
4
2020-01-10T21:06:07.000Z
2020-09-26T13:24:58.000Z
test/test/data_dictionary_test.cpp
rnburn/satyr
07f336dfd75a73d63d0573245847f03b7700304c
[ "MIT" ]
3
2018-12-08T17:31:37.000Z
2021-04-28T15:22:06.000Z
#include <satyr/test/data_dictionary.h> #include <sstream> #include <cassert> using namespace satyr::testing; int main() { { std::istringstream iss; auto data_dictionaries = read_data_dictionaries(iss); assert(data_dictionaries.empty()); } { std::istringstream iss{R"( double x = 1.0; double y = 2.0; )"}; auto data_dictionaries = read_data_dictionaries(iss); assert(data_dictionaries.size() == 1); assert(get<double>(data_dictionaries[0], "x") == 1.0); assert(get<double>(data_dictionaries[0], "y") == 2.0); } { std::istringstream iss{R"( double x = 1.0; //--- double x = 2.0; )"}; auto data_dictionaries = read_data_dictionaries(iss); assert(data_dictionaries.size() == 2); assert(get<double>(data_dictionaries[0], "x") == 1.0); assert(get<double>(data_dictionaries[1], "x") == 2.0); } { std::istringstream iss{R"( vector v = {1, 2, 3}; matrix m = {{1, 2, 3}, {4, 5, 6}}; symmetric_matrix s = {{1, 5}, {5, 1}}; )"}; auto data_dictionaries = read_data_dictionaries(iss); assert(data_dictionaries.size() == 1); auto v = get<satyr::vector<double>>(data_dictionaries[0], "v"); assert((v == satyr::vector<double>{1, 2, 3})); auto m = get<satyr::matrix<double>>(data_dictionaries[0], "m"); assert((m == satyr::matrix<double>{{1, 2, 3}, {4, 5, 6}})); auto s = get<satyr::symmetric_matrix<double>>(data_dictionaries[0], "s"); assert((s == satyr::symmetric_matrix<double>{{1, 5}, {5, 1}})); } return 0; }
27.339286
77
0.611365
rnburn
31e293a3b1575e0b4889caef9ddfba87b7e9e515
2,349
cpp
C++
board/fpga/net_reliable/tx_arbiter/tb.cpp
WukLab/Clio
7908c3a022fd356cd54616630fcddf59f7f3fd95
[ "MIT" ]
46
2021-12-02T04:45:23.000Z
2022-03-21T08:19:07.000Z
board/fpga/net_reliable/tx_arbiter/tb.cpp
WukLab/Clio
7908c3a022fd356cd54616630fcddf59f7f3fd95
[ "MIT" ]
null
null
null
board/fpga/net_reliable/tx_arbiter/tb.cpp
WukLab/Clio
7908c3a022fd356cd54616630fcddf59f7f3fd95
[ "MIT" ]
2
2022-03-17T04:00:53.000Z
2022-03-20T14:06:25.000Z
/* * Copyright (c) 2020,Wuklab, UCSD. */ #include "arbiter_64.hpp" #include <uapi/gbn.h> #define MAX_CYCLE 50 struct net_axis_64 build_gbn_header(ap_uint<8> type, ap_uint<SEQ_WIDTH> seqnum, ap_uint<1> last) { struct net_axis_64 pkt; pkt.data(7, 0) = type; pkt.data(8 + SEQ_WIDTH - 1, 8) = seqnum; pkt.data(63, 8 + SEQ_WIDTH) = 0; pkt.keep = 0xff; pkt.last = last; pkt.user = 0; return pkt; } int main() { stream<struct udp_info> rsp_header, rt_header, tx_header, out_header; stream<struct net_axis_64> rsp_payload, rt_payload, tx_payload, out_payload; struct udp_info test_header; struct net_axis_64 test_payload; test_header.src_ip = 0xc0a80181; // 192.168.1.129 test_header.dest_ip = 0xc0a80180; // 192.168.1.128 test_header.src_port = 1234; test_header.dest_port = 2345; rsp_header.write(test_header); test_payload = build_gbn_header(GBN_PKT_ACK, 1, 1); rsp_payload.write(test_payload); test_payload.keep = 0xff; test_payload.user = 0; rt_header.write(test_header); for (int j = 0; j < 10; j++) { test_payload.data = 0x0f0f0f0f0f0f0f0f; test_payload.last = 0; rt_payload.write(test_payload); } test_payload.data = 0x0f0f0f0f0f0f0f0f; test_payload.last = 1; rt_payload.write(test_payload); tx_header.write(test_header); for (int j = 0; j < 10; j++) { test_payload.data = 0x0101010101010101; test_payload.last = 0; tx_payload.write(test_payload); } test_payload.data = 0x0101010101010101; test_payload.last = 1; tx_payload.write(test_payload); for (int cycle = 0; cycle < MAX_CYCLE; cycle++) { arbiter_64(&rsp_header, &rsp_payload, &tx_header, &tx_payload, &rt_header, &rt_payload, &out_header, &out_payload); struct udp_info recv_hd; struct net_axis_64 recv_data; if (out_header.read_nb(recv_hd)) { dph("[cycle %2d] send data to net %x:%d -> %x:%d\n", cycle, recv_hd.src_ip.to_uint(), recv_hd.src_port.to_uint(), recv_hd.dest_ip.to_uint(), recv_hd.dest_port.to_uint()); } if (out_payload.read_nb(recv_data)) { dph("[cycle %2d] send data to net %llx, ", cycle, recv_data.data.to_uint64()); ap_uint<8> type = recv_data.data(7, 0); ap_uint<SEQ_WIDTH> seqnum = recv_data.data(8 + SEQ_WIDTH - 1, 8); dph("if gbn header [type %d, seq %lld]\n", type.to_ushort(), seqnum.to_uint64()); } } }
27
79
0.689229
WukLab
31e36365fa9475874f775caf70baa488eacc3cc0
588
hpp
C++
include/MCL/Screenshot.hpp
mattoverby/mclapp
e17cdf5ce1fb22f3061d46c26978ea9c60371841
[ "MIT" ]
null
null
null
include/MCL/Screenshot.hpp
mattoverby/mclapp
e17cdf5ce1fb22f3061d46c26978ea9c60371841
[ "MIT" ]
null
null
null
include/MCL/Screenshot.hpp
mattoverby/mclapp
e17cdf5ce1fb22f3061d46c26978ea9c60371841
[ "MIT" ]
null
null
null
// Copyright Matt Overby 2021. // Distributed under the MIT License. #ifndef MCL_SCREENSHOT_HPP #define MCL_SCREENSHOT_HPP 1 #include <igl/opengl/glfw/Viewer.h> namespace mcl { class Screenshot { public: int frame_counter; bool render_background; bool rendered_init; Screenshot() : frame_counter(0), render_background(0), rendered_init(0) {} // If filename is empty, it's auto computed from the frame_counter. // Otherwise, the frame_counter is NOT incremented. void save_frame(igl::opengl::glfw::Viewer &viewer, std::string fn=""); }; } // end namespace mcl #endif
18.375
71
0.738095
mattoverby
31e4de8ace3e37b2951c4690b3af0bb105b0c50a
966
cpp
C++
src/Root.cpp
syoch/wiiu-libgu
6744c46c9522c1a6def23aa613e8b759c50064c4
[ "MIT" ]
1
2021-02-26T15:49:54.000Z
2021-02-26T15:49:54.000Z
src/Root.cpp
syoch/wiiu-libgui
6744c46c9522c1a6def23aa613e8b759c50064c4
[ "MIT" ]
null
null
null
src/Root.cpp
syoch/wiiu-libgui
6744c46c9522c1a6def23aa613e8b759c50064c4
[ "MIT" ]
null
null
null
#include <Root.hpp> #include <DrawWrapper.hpp> #include <mc/internal/std/string.hpp> void GUI::Root::draw_line(DrawPoint start, DrawPoint end) { GUI::draw_line(start, end); } void GUI::Root::draw_rect(DrawPoint start, DrawPoint end) { GUI::draw_rect(start, end); } void GUI::Root::draw_rect(DrawPoint A, DrawPoint B, DrawPoint C, DrawPoint D) { GUI::draw_rect(A, B, C, D); } void GUI::Root::draw_triangle(DrawPoint A, DrawPoint B, DrawPoint C) { GUI::draw_triangle(A, B, C); } void GUI::Root::draw_text(int row, int column, mstd::wstring text, Color color) { GUI::draw_text(row, column, text, color); } void GUI::Root::draw_textShadow(int row, int column, mstd::wstring text, Color color) { GUI::draw_textShadow(row, column, text, color); } void GUI::Root::draw_translate(float x, float y) { GUI::_draw_translate(x, y); } void GUI::Root::_draw() { ContainerBase::_draw(); } GUI::Root::Root() : GUI::ContainerBase(0, 0, 0, 0) { }
23.560976
85
0.682195
syoch
31e4fc1d129b7959afb1ac46924c6898167485fb
1,970
hpp
C++
cpp/timeSerie/sources/sparseTimeSerie.hpp
jxtopher/quick-codes
577711394f3f338c061f1e53df875d958c645071
[ "Apache-2.0" ]
null
null
null
cpp/timeSerie/sources/sparseTimeSerie.hpp
jxtopher/quick-codes
577711394f3f338c061f1e53df875d958c645071
[ "Apache-2.0" ]
null
null
null
cpp/timeSerie/sources/sparseTimeSerie.hpp
jxtopher/quick-codes
577711394f3f338c061f1e53df875d958c645071
[ "Apache-2.0" ]
null
null
null
/// /// @file sparseTimeSerie.hpp /// @author Jxtopher /// @brief /// @version 0.1 /// @date 2019-11-09 /// /// @copyright Copyright (c) 2019 /// /// #include <iostream> #include <map> #include "timeSerie.hpp" template <typename TYPE_VALUES> class SparseTimeSerie : public TimeSerie { public: SparseTimeSerie(unsigned int size, TYPE_VALUES defaultValue) : _size(size) { _values[0] = defaultValue; } TYPE_VALUES operator()(const unsigned int t) const { if (_size < t) { std::cout<<"_size < t"<<std::endl; exit(0); } if (_values.find(t) != _values.end()) { // Key found return _values.at(t); } else { // Key not found unsigned int index = 0; if (_values.size() == 1) return _values.at(0); for (typename std::map<unsigned int, TYPE_VALUES>::const_iterator it=_values.begin(); it!=_values.end(); ++it) if (t < it->first) return _values.at((--it)->first); return (--_values.end())->second; } } void operator()(const unsigned int t, const TYPE_VALUES value) { if (_values.find(t) == _values.end()) { // Key found TYPE_VALUES tmp = this->operator()(t); _values[t] = value; if (_values.find(t+1) == _values.end())// Key not found _values[t+1] = tmp; } else// Key not found _values[t] = value; } unsigned int size() const { return _size; } friend std::ostream& operator<<(std::ostream& os, const SparseTimeSerie<TYPE_VALUES>& sparseTimeSerie) { for (typename std::map<unsigned int, TYPE_VALUES>::const_iterator it = sparseTimeSerie._values.begin(); it != sparseTimeSerie._values.end(); ++it) os << it->first << " => " << it->second << '\n'; return os; } private: std::map<unsigned int, TYPE_VALUES> _values; unsigned int _size; };
28.142857
155
0.560406
jxtopher
31e5025a55c63a58bf1b541ae3d273de4688f56e
5,706
cc
C++
media/webrtc/webrtcmediaengine.cc
bemasc/libjingle-hack
91a2af519ac2111eaf691ca33752800356f3e7d3
[ "BSL-1.0", "BSD-3-Clause" ]
27
2016-04-27T01:02:03.000Z
2021-12-13T08:53:19.000Z
media/webrtc/webrtcmediaengine.cc
bemasc/libjingle-hack
91a2af519ac2111eaf691ca33752800356f3e7d3
[ "BSL-1.0", "BSD-3-Clause" ]
2
2017-03-09T09:00:50.000Z
2017-09-21T15:48:20.000Z
media/webrtc/webrtcmediaengine.cc
bemasc/libjingle-hack
91a2af519ac2111eaf691ca33752800356f3e7d3
[ "BSL-1.0", "BSD-3-Clause" ]
17
2016-04-27T02:06:39.000Z
2019-12-18T08:07:00.000Z
/* * libjingle * Copyright 2014 Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "talk/media/webrtc/webrtcmediaengine.h" #include <algorithm> #include "talk/media/webrtc/webrtcvideoengine2.h" #include "talk/media/webrtc/webrtcvoiceengine.h" namespace cricket { class WebRtcMediaEngine2 : public CompositeMediaEngine<WebRtcVoiceEngine, WebRtcVideoEngine2> { public: WebRtcMediaEngine2(webrtc::AudioDeviceModule* adm, WebRtcVideoEncoderFactory* encoder_factory, WebRtcVideoDecoderFactory* decoder_factory) { voice_.SetAudioDeviceModule(adm); video_.SetExternalDecoderFactory(decoder_factory); video_.SetExternalEncoderFactory(encoder_factory); } }; } // namespace cricket cricket::MediaEngineInterface* CreateWebRtcMediaEngine( webrtc::AudioDeviceModule* adm, cricket::WebRtcVideoEncoderFactory* encoder_factory, cricket::WebRtcVideoDecoderFactory* decoder_factory) { return new cricket::WebRtcMediaEngine2(adm, encoder_factory, decoder_factory); } void DestroyWebRtcMediaEngine(cricket::MediaEngineInterface* media_engine) { delete media_engine; } namespace cricket { // Used by PeerConnectionFactory to create a media engine passed into // ChannelManager. MediaEngineInterface* WebRtcMediaEngineFactory::Create( webrtc::AudioDeviceModule* adm, WebRtcVideoEncoderFactory* encoder_factory, WebRtcVideoDecoderFactory* decoder_factory) { return CreateWebRtcMediaEngine(adm, encoder_factory, decoder_factory); } namespace { // Remove mutually exclusive extensions with lower priority. void DiscardRedundantExtensions( std::vector<webrtc::RtpExtension>* extensions, rtc::ArrayView<const char*> extensions_decreasing_prio) { RTC_DCHECK(extensions); bool found = false; for (const char* name : extensions_decreasing_prio) { auto it = std::find_if(extensions->begin(), extensions->end(), [name](const webrtc::RtpExtension& rhs) { return rhs.name == name; }); if (it != extensions->end()) { if (found) { extensions->erase(it); } found = true; } } } } // namespace bool ValidateRtpExtensions(const std::vector<RtpHeaderExtension>& extensions) { bool id_used[14] = {false}; for (const auto& extension : extensions) { if (extension.id <= 0 || extension.id >= 15) { LOG(LS_ERROR) << "Bad RTP extension ID: " << extension.ToString(); return false; } if (id_used[extension.id - 1]) { LOG(LS_ERROR) << "Duplicate RTP extension ID: " << extension.ToString(); return false; } id_used[extension.id - 1] = true; } return true; } std::vector<webrtc::RtpExtension> FilterRtpExtensions( const std::vector<RtpHeaderExtension>& extensions, bool (*supported)(const std::string&), bool filter_redundant_extensions) { RTC_DCHECK(ValidateRtpExtensions(extensions)); RTC_DCHECK(supported); std::vector<webrtc::RtpExtension> result; // Ignore any extensions that we don't recognize. for (const auto& extension : extensions) { if (supported(extension.uri)) { result.push_back({extension.uri, extension.id}); } else { LOG(LS_WARNING) << "Unsupported RTP extension: " << extension.ToString(); } } // Sort by name, ascending, so that we don't reset extensions if they were // specified in a different order (also allows us to use std::unique below). std::sort(result.begin(), result.end(), [](const webrtc::RtpExtension& rhs, const webrtc::RtpExtension& lhs) { return rhs.name < lhs.name; }); // Remove unnecessary extensions (used on send side). if (filter_redundant_extensions) { auto it = std::unique(result.begin(), result.end(), [](const webrtc::RtpExtension& rhs, const webrtc::RtpExtension& lhs) { return rhs.name == lhs.name; }); result.erase(it, result.end()); // Keep just the highest priority extension of any in the following list. static const char* kBweExtensionPriorities[] = { kRtpTransportSequenceNumberHeaderExtension, kRtpAbsoluteSenderTimeHeaderExtension, kRtpTimestampOffsetHeaderExtension }; DiscardRedundantExtensions(&result, kBweExtensionPriorities); } return result; } } // namespace cricket
36.576923
80
0.716088
bemasc
31e54d8e5561952e08a33f4e57e87e915b0154dd
540
hpp
C++
flare/include/flare/exceptions/missing_file_exception.hpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
14
2019-04-29T15:17:24.000Z
2020-12-30T12:51:05.000Z
flare/include/flare/exceptions/missing_file_exception.hpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
null
null
null
flare/include/flare/exceptions/missing_file_exception.hpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
6
2019-04-29T15:17:25.000Z
2021-11-16T03:20:59.000Z
#ifndef _FLARE_MISSINGFILEEXCEPTION_HPP_ #define _FLARE_MISSINGFILEEXCEPTION_HPP_ #include <exception> #include <string> namespace flare { class MissingFileException : public std::exception { std::string m_Message; std::string m_Filename; public: MissingFileException(const std::string& msg, const std::string& filename) : m_Message(msg), m_Filename(filename) { } const std::string& message() const { return m_Message; } const std::string& filename() const { return m_Filename; } }; } #endif
18
115
0.709259
taehyub
31e5ee3abf51f0f9a819a5a9406f79dee4d4a305
728
cpp
C++
src/test/test_sensors.cpp
sj0897/my-ARIAC-competition-2021
fbaa26430d5c37444464a3c04d44d80cf11c5ef1
[ "BSD-3-Clause" ]
null
null
null
src/test/test_sensors.cpp
sj0897/my-ARIAC-competition-2021
fbaa26430d5c37444464a3c04d44d80cf11c5ef1
[ "BSD-3-Clause" ]
null
null
null
src/test/test_sensors.cpp
sj0897/my-ARIAC-competition-2021
fbaa26430d5c37444464a3c04d44d80cf11c5ef1
[ "BSD-3-Clause" ]
null
null
null
#include<memory> #include <ros/ros.h> #include "sensors.h" int main(int argc, char **argv){ ros::init(argc, argv, "test_sensors"); ros::NodeHandle nh; auto logical_camera_bins0 = std::make_unique<LogicalCamera>(&nh, "logical_camera_bins0"); auto logical_camera_station2 = std::make_unique<LogicalCamera>(&nh, "logical_camera_station2"); auto depth_camera_bins1 = std::make_unique<DepthCamera>(&nh, "depth_camera_bins1"); auto proximity_sensor_0 = std::make_unique<ProximitySensor>(&nh, "proximity_sensor_0"); auto laser_profiler_0 = std::make_unique<LaserProfiler>(&nh, "laser_profiler_0"); auto breakbeam_0 = std::make_unique<BreakBeam>(&nh, "breakbeam_0"); ros::spin(); return 0; }
30.333333
99
0.722527
sj0897
31e7642123040eebbedfc0a0edd6c08e2a8ff9cc
362
cpp
C++
Online-Judges/HackerEarth/Mangoes.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
3
2021-06-15T01:19:23.000Z
2022-03-16T18:23:53.000Z
Online-Judges/HackerEarth/Mangoes.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
null
null
null
Online-Judges/HackerEarth/Mangoes.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long int lli; typedef long double ld; #define endn "\n" int main(void) { int num; cin >> num; if (num <= 2 || num % 2) cout << "NO" << endn; else cout << "YES" << endn; return 0; } // By Shihab Mahamud // Date: Monday, June 07, 2021 | 08:19:16 AM (+06)
15.73913
50
0.535912
shihab4t
31e908f8e2a8d465e13f0d98c8897a667c535dcb
11,182
cc
C++
syzygy/zap_timestamp/zap_timestamp_unittest.cc
nzeh/syzygy
3573e3d458dbb4285753c28a7cb42ced739f9f55
[ "Apache-2.0" ]
343
2015-01-07T05:58:44.000Z
2022-03-15T14:55:21.000Z
syzygy/zap_timestamp/zap_timestamp_unittest.cc
nzeh/syzygy-nzeh
3757e53f850644721284073de318e218224dd411
[ "Apache-2.0" ]
61
2015-03-19T18:20:21.000Z
2019-10-23T12:58:23.000Z
syzygy/zap_timestamp/zap_timestamp_unittest.cc
nzeh/syzygy-nzeh
3757e53f850644721284073de318e218224dd411
[ "Apache-2.0" ]
66
2015-01-20T15:35:05.000Z
2021-11-25T16:49:41.000Z
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "syzygy/zap_timestamp/zap_timestamp.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "gtest/gtest.h" #include "syzygy/core/unittest_util.h" #include "syzygy/pe/unittest_util.h" namespace zap_timestamp { namespace { // We don't bother with having specific data for the 'Coverage' case. #define TEST_DATA_PREFIX_0 L"syzygy\\zap_timestamp\\test_data\\" #ifdef NDEBUG #define TEST_DATA_PREFIX_1 L"Release\\" #else #define TEST_DATA_PREFIX_1 L"Debug\\" #endif #define TEST_DATA_PREFIX TEST_DATA_PREFIX_0 TEST_DATA_PREFIX_1 struct RawPePdbPathPair { const wchar_t* pe_path; const wchar_t* pdb_path; }; RawPePdbPathPair kRawTestPaths[] = { { TEST_DATA_PREFIX L"copy0\\test_dll.dll", TEST_DATA_PREFIX L"copy0\\test_dll.pdb" }, { TEST_DATA_PREFIX L"copy1\\test_dll.dll", TEST_DATA_PREFIX L"copy1\\test_dll.pdb" }, { TEST_DATA_PREFIX L"copy2\\test_dll.dll", TEST_DATA_PREFIX L"copy2\\test_dll.pdb" } }; struct PePdbPathPair { base::FilePath pe_path; base::FilePath pdb_path; }; class ZapTimestampTest : public testing::Test { public: virtual void SetUp() override { testing::Test::SetUp(); temp_dir_.CreateUniqueTempDir(); // Get the full test data paths. for (size_t i = 0; i < arraysize(kRawTestPaths); ++i) { PePdbPathPair pair; pair.pe_path = testing::GetSrcRelativePath(kRawTestPaths[i].pe_path); pair.pdb_path = testing::GetSrcRelativePath(kRawTestPaths[i].pdb_path); test_paths_.push_back(pair); } temp_pe_path_ = temp_dir_.path().Append(L"test_dll.dll"); temp_pdb_path_ = temp_dir_.path().Append(L"test_dll.pdb"); } void CopyTestData(const base::FilePath& pe_path, const base::FilePath& pdb_path) { ASSERT_TRUE(base::CopyFile(pe_path, temp_pe_path_)); ASSERT_TRUE(base::CopyFile(pdb_path, temp_pdb_path_)); } void CopyTestData(size_t index) { ASSERT_GT(test_paths_.size(), index); ASSERT_NO_FATAL_FAILURE(CopyTestData( test_paths_[index].pe_path, test_paths_[index].pdb_path)); } void CopyNoPdbTestData() { base::FilePath pe_path = testing::GetSrcRelativePath( L"syzygy\\zap_timestamp\\test_data\\test_dll_no_pdb.dll"); temp_pe_path_ = temp_dir_.path().Append(L"test_dll_no_pdb.dll"); temp_pdb_path_.clear(); ASSERT_TRUE(base::CopyFileW(pe_path, temp_pe_path_)); } base::ScopedTempDir temp_dir_; std::vector<PePdbPathPair> test_paths_; base::FilePath temp_pe_path_; base::FilePath temp_pdb_path_; }; } // namespace TEST_F(ZapTimestampTest, InitFailsForNonExistentPath) { ZapTimestamp zap; zap.set_input_image(base::FilePath(L"nonexistent_pe_file.dll")); zap.set_overwrite(true); EXPECT_FALSE(zap.Init()); } TEST_F(ZapTimestampTest, InitFailsForMismatchedPeAndPdb) { ASSERT_NO_FATAL_FAILURE(CopyTestData( test_paths_[0].pe_path, test_paths_[1].pdb_path)); ZapTimestamp zap; zap.set_input_image(temp_pe_path_); zap.set_overwrite(true); EXPECT_FALSE(zap.Init()); } TEST_F(ZapTimestampTest, InitFailsWithMissingPdb) { ASSERT_NO_FATAL_FAILURE(CopyTestData(0)); ASSERT_TRUE(base::DeleteFile(temp_pdb_path_, false)); ZapTimestamp zap; zap.set_input_image(temp_pe_path_); zap.set_overwrite(true); EXPECT_FALSE(zap.Init()); } TEST_F(ZapTimestampTest, InitAutoFindPdb) { ASSERT_NO_FATAL_FAILURE(CopyTestData(0)); ZapTimestamp zap; zap.set_input_image(temp_pe_path_); zap.set_overwrite(true); EXPECT_TRUE(zap.Init()); EXPECT_EQ(temp_pdb_path_, zap.input_pdb()); } TEST_F(ZapTimestampTest, InitExplicitPdb) { ASSERT_NO_FATAL_FAILURE(CopyTestData(0)); ZapTimestamp zap; zap.set_input_image(temp_pe_path_); zap.set_input_pdb(temp_pdb_path_); zap.set_overwrite(true); EXPECT_TRUE(zap.Init()); } TEST_F(ZapTimestampTest, IsIdempotent) { // Zap the first set of the PE and PDB files. ASSERT_NO_FATAL_FAILURE(CopyTestData(0)); ZapTimestamp zap0; zap0.set_input_image(temp_pe_path_); zap0.set_overwrite(true); EXPECT_TRUE(zap0.Init()); EXPECT_EQ(temp_pdb_path_, zap0.output_pdb()); EXPECT_TRUE(zap0.Zap()); // Make a copy of the singly zapped files. base::FilePath pe_path_0 = temp_dir_.path().Append(L"test_dll_0.dll"); base::FilePath pdb_path_0 = temp_dir_.path().Append(L"test_dll_0.pdb"); ASSERT_TRUE(base::CopyFile(temp_pe_path_, pe_path_0)); ASSERT_TRUE(base::CopyFile(temp_pdb_path_, pdb_path_0)); // Zap them again. ZapTimestamp zap1; zap1.set_input_image(temp_pe_path_); zap1.set_overwrite(true); EXPECT_TRUE(zap1.Init()); EXPECT_EQ(temp_pdb_path_, zap1.output_pdb()); EXPECT_TRUE(zap1.Zap()); // The singly and doubly zapped files should be the same. EXPECT_TRUE(base::ContentsEqual(temp_pe_path_, pe_path_0)); EXPECT_TRUE(base::ContentsEqual(temp_pdb_path_, pdb_path_0)); } TEST_F(ZapTimestampTest, SucceedsInferPdb) { ASSERT_NO_FATAL_FAILURE(CopyTestData(0)); base::FilePath pe_path = temp_dir_.path().Append(L"test_dll.new.dll"); base::FilePath pdb_path = temp_dir_.path().Append(L"test_dll.new.dll.pdb"); // Zap the image. Let the PDB output be inferred. ZapTimestamp zap0; zap0.set_input_image(temp_pe_path_); zap0.set_output_image(pe_path); EXPECT_TRUE(zap0.Init()); EXPECT_TRUE(zap0.Zap()); EXPECT_TRUE(base::PathExists(pe_path)); EXPECT_TRUE(base::PathExists(pdb_path)); } TEST_F(ZapTimestampTest, SucceedsExplicitPdb) { ASSERT_NO_FATAL_FAILURE(CopyTestData(0)); base::FilePath pe_path = temp_dir_.path().Append(L"test_dll.new.dll"); base::FilePath pdb_path = temp_dir_.path().Append(L"test_dll.new.dll.pdb"); // Zap the image. Provide an explicit output PDB. ZapTimestamp zap0; zap0.set_input_image(temp_pe_path_); zap0.set_output_image(pe_path); zap0.set_output_pdb(pdb_path); EXPECT_TRUE(zap0.Init()); EXPECT_TRUE(zap0.Zap()); EXPECT_TRUE(base::PathExists(pe_path)); EXPECT_TRUE(base::PathExists(pdb_path)); } TEST_F(ZapTimestampTest, SucceedsDontWritePdb) { ASSERT_NO_FATAL_FAILURE(CopyTestData(0)); base::FilePath pe_path = temp_dir_.path().Append(L"test_dll.new.dll"); base::FilePath pdb_path = temp_dir_.path().Append(L"test_dll.new.dll.pdb"); // Zap the image. Let the PDB output be inferred. ZapTimestamp zap0; zap0.set_input_image(temp_pe_path_); zap0.set_output_image(pe_path); zap0.set_write_pdb(false); EXPECT_TRUE(zap0.Init()); EXPECT_TRUE(zap0.Zap()); EXPECT_TRUE(base::PathExists(pe_path)); EXPECT_FALSE(base::PathExists(pdb_path)); } TEST_F(ZapTimestampTest, SucceedsDontWriteImage) { ASSERT_NO_FATAL_FAILURE(CopyTestData(0)); base::FilePath pe_path = temp_dir_.path().Append(L"test_dll.new.dll"); base::FilePath pdb_path = temp_dir_.path().Append(L"test_dll.new.dll.pdb"); // Zap the image. Let the PDB output be inferred. ZapTimestamp zap0; zap0.set_input_image(temp_pe_path_); zap0.set_output_image(pe_path); zap0.set_write_image(false); EXPECT_TRUE(zap0.Init()); EXPECT_TRUE(zap0.Zap()); EXPECT_FALSE(base::PathExists(pe_path)); EXPECT_TRUE(base::PathExists(pdb_path)); } TEST_F(ZapTimestampTest, FailsBecauseWouldOverwritePe) { ASSERT_NO_FATAL_FAILURE(CopyTestData(0)); base::FilePath pe_path = temp_dir_.path().Append(L"test_dll.new.dll"); base::FilePath pdb_path = temp_dir_.path().Append(L"test_dll.new.dll.pdb"); base::WriteFile(pe_path, "h", 1); // Zap the image. Let the PDB output be inferred. ZapTimestamp zap0; zap0.set_input_image(temp_pe_path_); zap0.set_output_image(pe_path); EXPECT_FALSE(zap0.Init()); } TEST_F(ZapTimestampTest, FailsBecauseWouldOverwritePdb) { ASSERT_NO_FATAL_FAILURE(CopyTestData(0)); base::FilePath pe_path = temp_dir_.path().Append(L"test_dll.new.dll"); base::FilePath pdb_path = temp_dir_.path().Append(L"test_dll.new.dll.pdb"); base::WriteFile(pdb_path, "h", 1); // Zap the image. Let the PDB output be inferred. ZapTimestamp zap0; zap0.set_input_image(temp_pe_path_); zap0.set_output_image(pe_path); EXPECT_FALSE(zap0.Init()); } TEST_F(ZapTimestampTest, Succeeds) { // Zap the first set of the PE and PDB files. ASSERT_NO_FATAL_FAILURE(CopyTestData(0)); ZapTimestamp zap0; zap0.set_input_image(temp_pe_path_); zap0.set_overwrite(true); EXPECT_TRUE(zap0.Init()); EXPECT_EQ(temp_pdb_path_, zap0.input_pdb()); EXPECT_TRUE(zap0.Zap()); // Rename and move the PE and PDB file. base::FilePath pe_path_0 = temp_dir_.path().Append(L"test_dll_0.dll"); base::FilePath pdb_path_0 = temp_dir_.path().Append(L"test_dll_0.pdb"); ASSERT_TRUE(base::Move(temp_pe_path_, pe_path_0)); ASSERT_TRUE(base::Move(temp_pdb_path_, pdb_path_0)); // Zap the second set of the PE and PDB files. ASSERT_NO_FATAL_FAILURE(CopyTestData(1)); ZapTimestamp zap1; zap1.set_input_image(temp_pe_path_); zap1.set_input_pdb(temp_pdb_path_); zap1.set_overwrite(true); EXPECT_TRUE(zap1.Init()); EXPECT_TRUE(zap1.Zap()); // Rename and move the PE and PDB file. base::FilePath pe_path_1 = temp_dir_.path().Append(L"test_dll_1.dll"); base::FilePath pdb_path_1 = temp_dir_.path().Append(L"test_dll_1.pdb"); ASSERT_TRUE(base::Move(temp_pe_path_, pe_path_1)); ASSERT_TRUE(base::Move(temp_pdb_path_, pdb_path_1)); // Zap the third set of the PE and PDB files. ASSERT_NO_FATAL_FAILURE(CopyTestData(2)); ZapTimestamp zap2; zap2.set_input_image(temp_pe_path_); zap2.set_input_pdb(temp_pdb_path_); zap2.set_overwrite(true); EXPECT_TRUE(zap2.Init()); EXPECT_TRUE(zap2.Zap()); // The sets of zapped files should match. EXPECT_TRUE(base::ContentsEqual(temp_pe_path_, pe_path_0)); EXPECT_TRUE(base::ContentsEqual(temp_pe_path_, pe_path_1)); EXPECT_TRUE(base::ContentsEqual(temp_pdb_path_, pdb_path_0)); EXPECT_TRUE(base::ContentsEqual(temp_pdb_path_, pdb_path_1)); } TEST_F(ZapTimestampTest, IsIdempotentNoPdb) { // Zap the iage. ASSERT_NO_FATAL_FAILURE(CopyNoPdbTestData()); ZapTimestamp zap0; zap0.set_input_image(temp_pe_path_); zap0.set_overwrite(true); zap0.set_write_pdb(false); EXPECT_TRUE(zap0.Init()); EXPECT_TRUE(zap0.Zap()); // Make a copy of the singly zapped image. base::FilePath pe_path_0 = temp_dir_.path().Append(L"test_dll_no_pdb_0.dll"); ASSERT_TRUE(base::CopyFile(temp_pe_path_, pe_path_0)); // Zap it again. ZapTimestamp zap1; zap1.set_input_image(temp_pe_path_); zap1.set_overwrite(true); zap1.set_write_pdb(false); EXPECT_TRUE(zap1.Init()); EXPECT_TRUE(zap1.Zap()); // The singly and doubly zapped files should be the same. EXPECT_TRUE(base::ContentsEqual(temp_pe_path_, pe_path_0)); } } // namespace zap_timestamp
33.08284
79
0.746825
nzeh
31eaed72f7e10018a0e4cfabc9f0d5ebed075fa8
81
cxx
C++
test/itkEmptyTest.cxx
bloyl/DiffusionImagingTK
0516d32b7b0d41ed161134812746ef02aab000de
[ "Apache-2.0" ]
4
2016-01-09T19:02:28.000Z
2017-07-31T19:41:32.000Z
test/itkEmptyTest.cxx
bloyl/DiffusionImagingTK
0516d32b7b0d41ed161134812746ef02aab000de
[ "Apache-2.0" ]
null
null
null
test/itkEmptyTest.cxx
bloyl/DiffusionImagingTK
0516d32b7b0d41ed161134812746ef02aab000de
[ "Apache-2.0" ]
2
2016-08-06T00:58:26.000Z
2019-02-18T01:03:13.000Z
#include <cstdlib> int itkEmptyTest( int , char ** ) { return EXIT_SUCCESS; }
11.571429
33
0.666667
bloyl
31ed0285804421ecfccd2f47ebbd06ff33261f25
1,086
cpp
C++
LinkedList/C++/main.cpp
mairacanal/data_structures
e35e4473ceb743dd51012f1ada07390ae3ac11ea
[ "MIT" ]
1
2021-12-14T14:36:06.000Z
2021-12-14T14:36:06.000Z
LinkedList/C++/main.cpp
mairacanal/data_structures
e35e4473ceb743dd51012f1ada07390ae3ac11ea
[ "MIT" ]
null
null
null
LinkedList/C++/main.cpp
mairacanal/data_structures
e35e4473ceb743dd51012f1ada07390ae3ac11ea
[ "MIT" ]
null
null
null
#include <iostream> #include "LinkedList.hpp" #include "LinkedList.cpp" void print(const List<int> &list) { for (auto &element : list) { std::cout << element << " "; } std::cout << std::endl; } int main() { List<int> list; std::cout << list.is_empty() << std::endl; for (int i = 0; i < 20; i++) { list.push_front(i); } print(list); std::cout << list.is_empty() << std::endl; std::cout << list.size() << std::endl; std::cout << list.front() << std::endl; std::cout << list.back() << std::endl; list.clear(); std::cout << list.is_empty() << std::endl; for (int i = 0; i < 20; i++) { list.push_back(i); } print(list); std::cout << list[11] << std::endl; std::cout << list[18] << std::endl; for (int i = 0; i < 5; i++) { list.pop_back(); } print(list); for (int i = 0; i < 5; i++) { list.pop_front(); } print(list); list.remove(11); print(list); list.reverse(); print(list); return 0; }
14.876712
46
0.480663
mairacanal
31ef33265c56b7126138f4d0838d0ebae8ea6d53
6,025
cpp
C++
ui/renderer/yas_ui_renderer_dependency.cpp
objective-audio/ui
cabf854b290c8df8c7e2f22f0f026b32c4173208
[ "MIT" ]
2
2017-06-07T18:30:29.000Z
2019-04-29T07:18:53.000Z
ui/renderer/yas_ui_renderer_dependency.cpp
objective-audio/ui
cabf854b290c8df8c7e2f22f0f026b32c4173208
[ "MIT" ]
null
null
null
ui/renderer/yas_ui_renderer_dependency.cpp
objective-audio/ui
cabf854b290c8df8c7e2f22f0f026b32c4173208
[ "MIT" ]
null
null
null
// // yas_ui_renderer_dependency.cpp // #include "yas_ui_renderer_dependency.h" #include <cpp_utils/yas_fast_each.h> #include <cpp_utils/yas_stl_utils.h> using namespace yas; using namespace yas::ui; bool tree_updates::is_any_updated() const { return this->node_updates.flags.any() || this->mesh_updates.flags.any() || this->vertex_data_updates.flags.any() || this->index_data_updates.flags.any() || this->render_target_updates.flags.any() || this->effect_updates.flags.any(); } bool tree_updates::is_collider_updated() const { static node_updates_t const _node_collider_updates = { ui::node_update_reason::enabled, ui::node_update_reason::children, ui::node_update_reason::collider}; return this->node_updates.and_test(_node_collider_updates); } bool tree_updates::is_render_target_updated() const { return this->render_target_updates.flags.any() || this->effect_updates.flags.any(); } batch_building_type tree_updates::batch_building_type() const { static node_updates_t const _node_rebuild_updates = {ui::node_update_reason::mesh, ui::node_update_reason::enabled, ui::node_update_reason::children, ui::node_update_reason::batch}; static mesh_updates_t const _mesh_rebuild_updates = { ui::mesh_update_reason::texture, ui::mesh_update_reason::vertex_data, ui::mesh_update_reason::index_data}; static mesh_data_updates_t const _vertex_data_rebuild_updates = {ui::mesh_data_update_reason::data_count}; if (this->node_updates.and_test(_node_rebuild_updates) || this->mesh_updates.and_test(_mesh_rebuild_updates) || this->vertex_data_updates.and_test(_vertex_data_rebuild_updates) || this->index_data_updates.and_test(_vertex_data_rebuild_updates)) { return ui::batch_building_type::rebuild; } if (this->node_updates.flags.any() || this->mesh_updates.flags.any() || this->vertex_data_updates.flags.any() || this->index_data_updates.flags.any()) { return ui::batch_building_type::overwrite; } return ui::batch_building_type::none; } std::string yas::to_string(ui::node_update_reason const &reason) { switch (reason) { case ui::node_update_reason::geometry: return "geometry"; case ui::node_update_reason::mesh: return "mesh"; case ui::node_update_reason::collider: return "collider"; case ui::node_update_reason::enabled: return "enabled"; case ui::node_update_reason::batch: return "batch"; case ui::node_update_reason::render_target: return "render_target"; case ui::node_update_reason::children: return "children"; case ui::node_update_reason::count: return "count"; } } std::string yas::to_string(ui::batch_building_type const &type) { switch (type) { case ui::batch_building_type::rebuild: return "rebuild"; case ui::batch_building_type::overwrite: return "overwrite"; case ui::batch_building_type::none: return "none"; } } std::string yas::to_string(ui::mesh_data_update_reason const &reason) { switch (reason) { case ui::mesh_data_update_reason::data_content: return "data_content"; case ui::mesh_data_update_reason::data_count: return "data_count"; case ui::mesh_data_update_reason::render_buffer: return "render_buffer"; case ui::mesh_data_update_reason::count: return "count"; } } std::string yas::to_string(ui::mesh_update_reason const &reason) { switch (reason) { case ui::mesh_update_reason::vertex_data: return "vertex_data"; case ui::mesh_update_reason::index_data: return "index_data"; case ui::mesh_update_reason::texture: return "texture"; case ui::mesh_update_reason::primitive_type: return "primitive_type"; case ui::mesh_update_reason::color: return "color"; case ui::mesh_update_reason::use_mesh_color: return "use_mesh_color"; case ui::mesh_update_reason::matrix: return "matrix"; case ui::mesh_update_reason::count: return "count"; } } std::ostream &operator<<(std::ostream &os, yas::ui::node_update_reason const &reason) { os << to_string(reason); return os; } std::ostream &operator<<(std::ostream &os, yas::ui::batch_building_type const &type) { os << to_string(type); return os; } std::ostream &operator<<(std::ostream &os, yas::ui::mesh_data_update_reason const &reason) { os << to_string(reason); return os; } std::ostream &operator<<(std::ostream &os, yas::ui::mesh_update_reason const &reason) { os << to_string(reason); return os; } std::ostream &operator<<(std::ostream &os, yas::ui::effect_update_reason const &value) { os << to_string(value); return os; } std::ostream &operator<<(std::ostream &os, yas::ui::effect_updates_t const &value) { os << to_string(value); return os; } #pragma mark - std::string yas::to_string(ui::effect_update_reason const &reason) { switch (reason) { case ui::effect_update_reason::textures: return "textures"; case ui::effect_update_reason::handler: return "handler"; case ui::effect_update_reason::count: return "count"; } } std::string yas::to_string(ui::effect_updates_t const &updates) { std::vector<std::string> flag_texts; auto each = make_fast_each(static_cast<std::size_t>(ui::effect_update_reason::count)); while (yas_each_next(each)) { auto const value = static_cast<ui::effect_update_reason>(yas_each_index(each)); if (updates.test(value)) { flag_texts.emplace_back(to_string(value)); } } return joined(flag_texts, "|"); }
35.02907
119
0.657095
objective-audio
31f09ecfd0c802bfee60f9e5235832550f96f8ce
1,841
hpp
C++
multiview/multiview_cpp/src/im-gui/imgui-utils/single-window-sdl-app.hpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
5
2021-09-03T23:12:08.000Z
2022-03-04T21:43:32.000Z
multiview/multiview_cpp/src/im-gui/imgui-utils/single-window-sdl-app.hpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
3
2021-09-08T02:57:46.000Z
2022-02-26T05:33:02.000Z
multiview/multiview_cpp/src/im-gui/imgui-utils/single-window-sdl-app.hpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
2
2021-09-26T03:14:40.000Z
2022-01-26T06:42:52.000Z
#pragma once #include <SDL.h> #include "json/json.h" namespace perceive::gui { /// /// Serializable object that store window positioning /// struct WindowPositionData { Point2 position = {SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED}; Point2 size = {1280, 720}; // width/height Json::Value to_json() const noexcept; static WindowPositionData from_json(const Json::Value&) noexcept(false); }; /// /// Parameter block for creating a `SingleWindowApp` /// struct SingleWindowParams { string glsl_version = "#version 150"s; uint32_t sdl_init_flags = SDL_INIT_VIDEO | SDL_INIT_TIMER; string window_name = "Dear ImGui+SDL2+OpenGL3"s; WindowPositionData pos = {}; SDL_WindowFlags window_flags = SDL_WindowFlags( SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI); string imgui_ini_fname = ""s; // uses default if empty }; /// /// Initializes: SDL, OpenGL, Glew, ImGUI /// The destructor cleans up (destroys) SDL, etc. /// /// SDL uses a global event loop, (i.e., for all windows) /// and thus it makes sense to handle events elsewhere. /// struct SingleWindowApp { // Members SDL_Window* sdl_window = nullptr; SDL_GLContext gl_context = nullptr; // SDL_GLContext is an opaque pointer // Construction SingleWindowApp(SingleWindowParams p = {}) noexcept(false); SingleWindowApp(const SingleWindowApp&) = delete; SingleWindowApp(SingleWindowApp&&) = default; ~SingleWindowApp(); SingleWindowApp& operator=(const SingleWindowApp&) = delete; SingleWindowApp& operator=(SingleWindowApp&&) = default; uint32_t id() const noexcept; // SDL_GetWindowID std::pair<int, int> size() const noexcept; // width, height void gl_swap_window() const noexcept; // SDL_GL_SwapWindow }; } // namespace perceive::gui
27.893939
76
0.705052
prcvlabs
31f25ebc84f723d81883b742fb6a4ae198d3e15e
849
cpp
C++
Love-Babbar-450-In-CPPTest/10_stack_and_queues/06_check_expression_has_balanced_paranthesis_or_not.cpp
harshanu11/Love-Babbar-450-In-CSharp
0dc3bef3e66e30abbc04f7bbf21c7319b41803e1
[ "MIT" ]
null
null
null
Love-Babbar-450-In-CPPTest/10_stack_and_queues/06_check_expression_has_balanced_paranthesis_or_not.cpp
harshanu11/Love-Babbar-450-In-CSharp
0dc3bef3e66e30abbc04f7bbf21c7319b41803e1
[ "MIT" ]
null
null
null
Love-Babbar-450-In-CPPTest/10_stack_and_queues/06_check_expression_has_balanced_paranthesis_or_not.cpp
harshanu11/Love-Babbar-450-In-CSharp
0dc3bef3e66e30abbc04f7bbf21c7319b41803e1
[ "MIT" ]
null
null
null
///* // link: https://practice.geeksforgeeks.org/problems/parenthesis-checker2744/1 // // ref: 3_string/16_balanced_paranthesis.cpp //*/ // // //// ----------------------------------------------------------------------------------------------------------------------- // //bool ispar(string x) //{ // stack<char> s; // for (char c : x) { // if (c == '[' | c == '{' | c == '(') { // s.push(c); // } // else { // if (s.size() == 0) { // return false; // } // else if (c == ']' && s.top() == '[') s.pop(); // else if (c == '}' && s.top() == '{') s.pop(); // else if (c == ')' && s.top() == '(') s.pop(); // else { // return false; // } // } // } // return (s.size()) ? false : true; //}
29.275862
127
0.294464
harshanu11
31f66688d06acebc6976b2a4f2dbef9d2fb53d05
18,115
inl
C++
src/ripple/json/impl/json_internalmap.inl
Ziftr/rippled
0829ee9234338c1f7facc304a3f27eefa1c27daa
[ "BSL-1.0" ]
58
2015-01-07T09:10:59.000Z
2019-07-15T14:34:01.000Z
src/ripple/json/impl/json_internalmap.inl
Ziftr/rippled
0829ee9234338c1f7facc304a3f27eefa1c27daa
[ "BSL-1.0" ]
12
2015-01-02T00:01:45.000Z
2018-04-25T12:35:02.000Z
src/ripple/json/impl/json_internalmap.inl
Ziftr/rippled
0829ee9234338c1f7facc304a3f27eefa1c27daa
[ "BSL-1.0" ]
23
2015-01-04T00:13:27.000Z
2019-02-15T18:01:17.000Z
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2012, 2013 Ripple Labs Inc. 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. */ //============================================================================== // included by json_value.cpp // everything is within Json namespace // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // class ValueInternalMap // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// /** \internal MUST be safely initialized using memset( this, 0, sizeof(ValueInternalLink) ); * This optimization is used by the fast allocator. */ ValueInternalLink::ValueInternalLink () : previous_ ( 0 ) , next_ ( 0 ) { } ValueInternalLink::~ValueInternalLink () { for ( int index = 0; index < itemPerLink; ++index ) { if ( !items_[index].isItemAvailable () ) { if ( !items_[index].isMemberNameStatic () ) free ( keys_[index] ); } else break; } } ValueMapAllocator::~ValueMapAllocator () { } #ifdef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR class DefaultValueMapAllocator : public ValueMapAllocator { public: // overridden from ValueMapAllocator virtual ValueInternalMap* newMap () { return new ValueInternalMap (); } virtual ValueInternalMap* newMapCopy ( const ValueInternalMap& other ) { return new ValueInternalMap ( other ); } virtual void destructMap ( ValueInternalMap* map ) { delete map; } virtual ValueInternalLink* allocateMapBuckets ( unsigned int size ) { return new ValueInternalLink[size]; } virtual void releaseMapBuckets ( ValueInternalLink* links ) { delete [] links; } virtual ValueInternalLink* allocateMapLink () { return new ValueInternalLink (); } virtual void releaseMapLink ( ValueInternalLink* link ) { delete link; } }; #else /// @todo make this thread-safe (lock when accessign batch allocator) class DefaultValueMapAllocator : public ValueMapAllocator { public: // overridden from ValueMapAllocator virtual ValueInternalMap* newMap () { ValueInternalMap* map = mapsAllocator_.allocate (); new (map) ValueInternalMap (); // placement new return map; } virtual ValueInternalMap* newMapCopy ( const ValueInternalMap& other ) { ValueInternalMap* map = mapsAllocator_.allocate (); new (map) ValueInternalMap ( other ); // placement new return map; } virtual void destructMap ( ValueInternalMap* map ) { if ( map ) { map->~ValueInternalMap (); mapsAllocator_.release ( map ); } } virtual ValueInternalLink* allocateMapBuckets ( unsigned int size ) { return new ValueInternalLink[size]; } virtual void releaseMapBuckets ( ValueInternalLink* links ) { delete [] links; } virtual ValueInternalLink* allocateMapLink () { ValueInternalLink* link = linksAllocator_.allocate (); memset ( link, 0, sizeof (ValueInternalLink) ); return link; } virtual void releaseMapLink ( ValueInternalLink* link ) { link->~ValueInternalLink (); linksAllocator_.release ( link ); } private: BatchAllocator<ValueInternalMap, 1> mapsAllocator_; BatchAllocator<ValueInternalLink, 1> linksAllocator_; }; #endif static ValueMapAllocator*& mapAllocator () { static DefaultValueMapAllocator defaultAllocator; static ValueMapAllocator* mapAllocator = &defaultAllocator; return mapAllocator; } static struct DummyMapAllocatorInitializer { DummyMapAllocatorInitializer () { mapAllocator (); // ensure mapAllocator() statics are initialized before main(). } } dummyMapAllocatorInitializer; // h(K) = value * K >> w ; with w = 32 & K prime w.r.t. 2^32. /* use linked list hash map. buckets array is a container. linked list element contains 6 key/values. (memory = (16+4) * 6 + 4 = 124) value have extra state: valid, available, deleted */ ValueInternalMap::ValueInternalMap () : buckets_ ( 0 ) , tailLink_ ( 0 ) , bucketsSize_ ( 0 ) , itemCount_ ( 0 ) { } ValueInternalMap::ValueInternalMap ( const ValueInternalMap& other ) : buckets_ ( 0 ) , tailLink_ ( 0 ) , bucketsSize_ ( 0 ) , itemCount_ ( 0 ) { reserve ( other.itemCount_ ); IteratorState it; IteratorState itEnd; other.makeBeginIterator ( it ); other.makeEndIterator ( itEnd ); for ( ; !equals (it, itEnd); increment (it) ) { bool isStatic; const char* memberName = key ( it, isStatic ); const Value& aValue = value ( it ); resolveReference (memberName, isStatic) = aValue; } } ValueInternalMap& ValueInternalMap::operator = ( const ValueInternalMap& other ) { ValueInternalMap dummy ( other ); swap ( dummy ); return *this; } ValueInternalMap::~ValueInternalMap () { if ( buckets_ ) { for ( BucketIndex bucketIndex = 0; bucketIndex < bucketsSize_; ++bucketIndex ) { ValueInternalLink* link = buckets_[bucketIndex].next_; while ( link ) { ValueInternalLink* linkToRelease = link; link = link->next_; mapAllocator ()->releaseMapLink ( linkToRelease ); } } mapAllocator ()->releaseMapBuckets ( buckets_ ); } } void ValueInternalMap::swap ( ValueInternalMap& other ) { ValueInternalLink* tempBuckets = buckets_; buckets_ = other.buckets_; other.buckets_ = tempBuckets; ValueInternalLink* tempTailLink = tailLink_; tailLink_ = other.tailLink_; other.tailLink_ = tempTailLink; BucketIndex tempBucketsSize = bucketsSize_; bucketsSize_ = other.bucketsSize_; other.bucketsSize_ = tempBucketsSize; BucketIndex tempItemCount = itemCount_; itemCount_ = other.itemCount_; other.itemCount_ = tempItemCount; } void ValueInternalMap::clear () { ValueInternalMap dummy; swap ( dummy ); } ValueInternalMap::BucketIndex ValueInternalMap::size () const { return itemCount_; } bool ValueInternalMap::reserveDelta ( BucketIndex growth ) { return reserve ( itemCount_ + growth ); } bool ValueInternalMap::reserve ( BucketIndex newItemCount ) { if ( !buckets_ && newItemCount > 0 ) { buckets_ = mapAllocator ()->allocateMapBuckets ( 1 ); bucketsSize_ = 1; tailLink_ = &buckets_[0]; } // BucketIndex idealBucketCount = (newItemCount + ValueInternalLink::itemPerLink) / ValueInternalLink::itemPerLink; return true; } const Value* ValueInternalMap::find ( const char* key ) const { if ( !bucketsSize_ ) return 0; HashKey hashedKey = hash ( key ); BucketIndex bucketIndex = hashedKey % bucketsSize_; for ( const ValueInternalLink* current = &buckets_[bucketIndex]; current != 0; current = current->next_ ) { for ( BucketIndex index = 0; index < ValueInternalLink::itemPerLink; ++index ) { if ( current->items_[index].isItemAvailable () ) return 0; if ( strcmp ( key, current->keys_[index] ) == 0 ) return &current->items_[index]; } } return 0; } Value* ValueInternalMap::find ( const char* key ) { const ValueInternalMap* constThis = this; return const_cast<Value*> ( constThis->find ( key ) ); } Value& ValueInternalMap::resolveReference ( const char* key, bool isStatic ) { HashKey hashedKey = hash ( key ); if ( bucketsSize_ ) { BucketIndex bucketIndex = hashedKey % bucketsSize_; ValueInternalLink** previous = 0; BucketIndex index; for ( ValueInternalLink* current = &buckets_[bucketIndex]; current != 0; previous = &current->next_, current = current->next_ ) { for ( index = 0; index < ValueInternalLink::itemPerLink; ++index ) { if ( current->items_[index].isItemAvailable () ) return setNewItem ( key, isStatic, current, index ); if ( strcmp ( key, current->keys_[index] ) == 0 ) return current->items_[index]; } } } reserveDelta ( 1 ); return unsafeAdd ( key, isStatic, hashedKey ); } void ValueInternalMap::remove ( const char* key ) { HashKey hashedKey = hash ( key ); if ( !bucketsSize_ ) return; BucketIndex bucketIndex = hashedKey % bucketsSize_; for ( ValueInternalLink* link = &buckets_[bucketIndex]; link != 0; link = link->next_ ) { BucketIndex index; for ( index = 0; index < ValueInternalLink::itemPerLink; ++index ) { if ( link->items_[index].isItemAvailable () ) return; if ( strcmp ( key, link->keys_[index] ) == 0 ) { doActualRemove ( link, index, bucketIndex ); return; } } } } void ValueInternalMap::doActualRemove ( ValueInternalLink* link, BucketIndex index, BucketIndex bucketIndex ) { // find last item of the bucket and swap it with the 'removed' one. // set removed items flags to 'available'. // if last page only contains 'available' items, then desallocate it (it's empty) ValueInternalLink*& lastLink = getLastLinkInBucket ( index ); BucketIndex lastItemIndex = 1; // a link can never be empty, so start at 1 for ( ; lastItemIndex < ValueInternalLink::itemPerLink; ++lastItemIndex ) // may be optimized with dicotomic search { if ( lastLink->items_[lastItemIndex].isItemAvailable () ) break; } BucketIndex lastUsedIndex = lastItemIndex - 1; Value* valueToDelete = &link->items_[index]; Value* valueToPreserve = &lastLink->items_[lastUsedIndex]; if ( valueToDelete != valueToPreserve ) valueToDelete->swap ( *valueToPreserve ); if ( lastUsedIndex == 0 ) // page is now empty { // remove it from bucket linked list and delete it. ValueInternalLink* linkPreviousToLast = lastLink->previous_; if ( linkPreviousToLast != 0 ) // can not deleted bucket link. { mapAllocator ()->releaseMapLink ( lastLink ); linkPreviousToLast->next_ = 0; lastLink = linkPreviousToLast; } } else { Value dummy; valueToPreserve->swap ( dummy ); // restore deleted to default Value. valueToPreserve->setItemUsed ( false ); } --itemCount_; } ValueInternalLink*& ValueInternalMap::getLastLinkInBucket ( BucketIndex bucketIndex ) { if ( bucketIndex == bucketsSize_ - 1 ) return tailLink_; ValueInternalLink*& previous = buckets_[bucketIndex + 1].previous_; if ( !previous ) previous = &buckets_[bucketIndex]; return previous; } Value& ValueInternalMap::setNewItem ( const char* key, bool isStatic, ValueInternalLink* link, BucketIndex index ) { char* duplicatedKey = valueAllocator ()->makeMemberName ( key ); ++itemCount_; link->keys_[index] = duplicatedKey; link->items_[index].setItemUsed (); link->items_[index].setMemberNameIsStatic ( isStatic ); return link->items_[index]; // items already default constructed. } Value& ValueInternalMap::unsafeAdd ( const char* key, bool isStatic, HashKey hashedKey ) { JSON_ASSERT_MESSAGE ( bucketsSize_ > 0, "ValueInternalMap::unsafeAdd(): internal logic error." ); BucketIndex bucketIndex = hashedKey % bucketsSize_; ValueInternalLink*& previousLink = getLastLinkInBucket ( bucketIndex ); ValueInternalLink* link = previousLink; BucketIndex index; for ( index = 0; index < ValueInternalLink::itemPerLink; ++index ) { if ( link->items_[index].isItemAvailable () ) break; } if ( index == ValueInternalLink::itemPerLink ) // need to add a new page { ValueInternalLink* newLink = mapAllocator ()->allocateMapLink (); index = 0; link->next_ = newLink; previousLink = newLink; link = newLink; } return setNewItem ( key, isStatic, link, index ); } ValueInternalMap::HashKey ValueInternalMap::hash ( const char* key ) const { HashKey hash = 0; while ( *key ) hash += *key++ * 37; return hash; } int ValueInternalMap::compare ( const ValueInternalMap& other ) const { int sizeDiff ( itemCount_ - other.itemCount_ ); if ( sizeDiff != 0 ) return sizeDiff; // Strict order guaranty is required. Compare all keys FIRST, then compare values. IteratorState it; IteratorState itEnd; makeBeginIterator ( it ); makeEndIterator ( itEnd ); for ( ; !equals (it, itEnd); increment (it) ) { if ( !other.find ( key ( it ) ) ) return 1; } // All keys are equals, let's compare values makeBeginIterator ( it ); for ( ; !equals (it, itEnd); increment (it) ) { const Value* otherValue = other.find ( key ( it ) ); int valueDiff = value (it).compare ( *otherValue ); if ( valueDiff != 0 ) return valueDiff; } return 0; } void ValueInternalMap::makeBeginIterator ( IteratorState& it ) const { it.map_ = const_cast<ValueInternalMap*> ( this ); it.bucketIndex_ = 0; it.itemIndex_ = 0; it.link_ = buckets_; } void ValueInternalMap::makeEndIterator ( IteratorState& it ) const { it.map_ = const_cast<ValueInternalMap*> ( this ); it.bucketIndex_ = bucketsSize_; it.itemIndex_ = 0; it.link_ = 0; } bool ValueInternalMap::equals ( const IteratorState& x, const IteratorState& other ) { return x.map_ == other.map_ && x.bucketIndex_ == other.bucketIndex_ && x.link_ == other.link_ && x.itemIndex_ == other.itemIndex_; } void ValueInternalMap::incrementBucket ( IteratorState& iterator ) { ++iterator.bucketIndex_; JSON_ASSERT_MESSAGE ( iterator.bucketIndex_ <= iterator.map_->bucketsSize_, "ValueInternalMap::increment(): attempting to iterate beyond end." ); if ( iterator.bucketIndex_ == iterator.map_->bucketsSize_ ) iterator.link_ = 0; else iterator.link_ = & (iterator.map_->buckets_[iterator.bucketIndex_]); iterator.itemIndex_ = 0; } void ValueInternalMap::increment ( IteratorState& iterator ) { JSON_ASSERT_MESSAGE ( iterator.map_, "Attempting to iterator using invalid iterator." ); ++iterator.itemIndex_; if ( iterator.itemIndex_ == ValueInternalLink::itemPerLink ) { JSON_ASSERT_MESSAGE ( iterator.link_ != 0, "ValueInternalMap::increment(): attempting to iterate beyond end." ); iterator.link_ = iterator.link_->next_; if ( iterator.link_ == 0 ) incrementBucket ( iterator ); } else if ( iterator.link_->items_[iterator.itemIndex_].isItemAvailable () ) { incrementBucket ( iterator ); } } void ValueInternalMap::decrement ( IteratorState& iterator ) { if ( iterator.itemIndex_ == 0 ) { JSON_ASSERT_MESSAGE ( iterator.map_, "Attempting to iterate using invalid iterator." ); if ( iterator.link_ == &iterator.map_->buckets_[iterator.bucketIndex_] ) { JSON_ASSERT_MESSAGE ( iterator.bucketIndex_ > 0, "Attempting to iterate beyond beginning." ); -- (iterator.bucketIndex_); } iterator.link_ = iterator.link_->previous_; iterator.itemIndex_ = ValueInternalLink::itemPerLink - 1; } } const char* ValueInternalMap::key ( const IteratorState& iterator ) { JSON_ASSERT_MESSAGE ( iterator.link_, "Attempting to iterate using invalid iterator." ); return iterator.link_->keys_[iterator.itemIndex_]; } const char* ValueInternalMap::key ( const IteratorState& iterator, bool& isStatic ) { JSON_ASSERT_MESSAGE ( iterator.link_, "Attempting to iterate using invalid iterator." ); isStatic = iterator.link_->items_[iterator.itemIndex_].isMemberNameStatic (); return iterator.link_->keys_[iterator.itemIndex_]; } Value& ValueInternalMap::value ( const IteratorState& iterator ) { JSON_ASSERT_MESSAGE ( iterator.link_, "Attempting to iterate using invalid iterator." ); return iterator.link_->items_[iterator.itemIndex_]; } int ValueInternalMap::distance ( const IteratorState& x, const IteratorState& y ) { int offset = 0; IteratorState it = x; while ( !equals ( it, y ) ) increment ( it ); return offset; }
26.956845
121
0.608612
Ziftr
31f7762c913e8f4c3d96fdecc04b499d7810fd4d
690
cpp
C++
src/csapex_core/src/model/connectable_vector.cpp
ICRA-2018/csapex
8ee83b9166d0281a4923184cce67b4a55f273ea2
[ "BSD-3-Clause" ]
21
2016-09-02T15:33:25.000Z
2021-06-10T06:34:39.000Z
src/csapex_core/src/model/connectable_vector.cpp
ICRA-2018/csapex
8ee83b9166d0281a4923184cce67b4a55f273ea2
[ "BSD-3-Clause" ]
null
null
null
src/csapex_core/src/model/connectable_vector.cpp
ICRA-2018/csapex
8ee83b9166d0281a4923184cce67b4a55f273ea2
[ "BSD-3-Clause" ]
10
2016-10-12T00:55:17.000Z
2020-04-24T19:59:02.000Z
/// HEADER #include <csapex/model/connectable_vector.h> /// PROJECT #include <csapex/msg/input.h> #include <csapex/msg/output.h> #include <csapex/signal/event.h> #include <csapex/signal/slot.h> using namespace csapex; template <typename T> std::vector<ConnectorDescription> ConnectableVector<T>::getDescription() const { std::vector<ConnectorDescription> res; for (const std::shared_ptr<T>& c : *this) { res.push_back(c->getDescription()); } return res; } namespace csapex { template class ConnectableVector<Input>; template class ConnectableVector<Output>; template class ConnectableVector<Event>; template class ConnectableVector<Slot>; } // namespace csapex
23.793103
78
0.742029
ICRA-2018
31fa920c4e936e21b2a65498e4fe02eaebabea0b
180
hpp
C++
Contract/EOS/payout/backup/dawn/config.hpp
flyq/dapp-rosetta
0b66f1798c68cd23211105cca363ae1e8eca6876
[ "MIT" ]
21
2019-01-24T12:43:33.000Z
2021-12-20T02:03:22.000Z
Contract/EOS/payout/backup/dawn/config.hpp
flyq/dapp-rosetta
0b66f1798c68cd23211105cca363ae1e8eca6876
[ "MIT" ]
1
2021-12-19T18:15:15.000Z
2022-02-09T04:50:32.000Z
Contract/EOS/payout/backup/dawn/config.hpp
flyq/dapp-rosetta
0b66f1798c68cd23211105cca363ae1e8eca6876
[ "MIT" ]
13
2019-02-14T01:56:26.000Z
2020-09-25T02:52:18.000Z
#pragma once #define EOS_SYMBOL S(4, EOS) #define CTN_SYMBOL S(4, CTN) #define TOKEN_SYMBOL CTN_SYMBOL #define TOKEN_CONTRACT N(dacincubator) const uint128_t MAGNITUDE = 1ll<<32;
25.714286
38
0.783333
flyq
31fc2b6f8b6de5b495c159665d76f617211ff59f
525
cpp
C++
src/main/cpp/commands/IntakePneumaticCommand.cpp
GHawk1124/apex-rapid-react-2022
c5b0c6be47e577dbda91046cd0e6713a82100dc6
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/commands/IntakePneumaticCommand.cpp
GHawk1124/apex-rapid-react-2022
c5b0c6be47e577dbda91046cd0e6713a82100dc6
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/commands/IntakePneumaticCommand.cpp
GHawk1124/apex-rapid-react-2022
c5b0c6be47e577dbda91046cd0e6713a82100dc6
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. #include "commands/IntakePneumaticCommand.h" IntakePneumaticCommand::IntakePneumaticCommand(IntakeSubsystem* subsystem) : m_subsystem{subsystem} { AddRequirements({subsystem}); } void IntakePneumaticCommand::Execute() { m_subsystem->toggleSolenoid(); } bool IntakePneumaticCommand::IsFinished() { return true; }
27.631579
74
0.773333
GHawk1124
ee02766ed6384328bfdae557ed0707e100be17e3
1,677
cpp
C++
src/api/systeminfo.cpp
CommitteeOfZero/noidget
1ba0b37f7552c1659a8a7c8dd62893c9eece702a
[ "MIT" ]
null
null
null
src/api/systeminfo.cpp
CommitteeOfZero/noidget
1ba0b37f7552c1659a8a7c8dd62893c9eece702a
[ "MIT" ]
null
null
null
src/api/systeminfo.cpp
CommitteeOfZero/noidget
1ba0b37f7552c1659a8a7c8dd62893c9eece702a
[ "MIT" ]
null
null
null
#include "systeminfo.h" #include "apihost.h" #include <api/exception.h> #include <QScriptValue> #include <QScriptValueList> #include <QProcessEnvironment> namespace api { SystemInfo::SystemInfo(ApiHost* parent) : QObject(parent) {} SystemInfo::~SystemInfo() {} void SystemInfo::setupScriptObject(QScriptValue& o) { ApiHost::registerEnum<util::SystemInfo::OsFamily>(o); } /*^jsdoc * Platform the program is currently running on. * @method platform * @memberof ng.systemInfo * @static * @returns {ng.systemInfo.OsFamily} ^jsdoc*/ util::SystemInfo::OsFamily SystemInfo::platform() const { return util::SystemInfo::platform(); } /*^jsdoc * Is the installer a Windows build running under Wine? * @method isWine * @memberof ng.systemInfo * @static * @returns {boolean} ^jsdoc*/ bool SystemInfo::isWine() const { return util::SystemInfo::isWine(); } /*^jsdoc * Is a process with the given name running (besides the installer application itself)? * * `processName` is **case sensitive**. * * @method isProcessRunning * @memberof ng.systemInfo * @static * @param {string} processName * @returns {boolean} ^jsdoc*/ bool SystemInfo::isProcessRunning(const QString& processName) const { return util::SystemInfo::isProcessRunning(processName); } /*^jsdoc * Get an environment variable * * Note we also have such functionality in {@link ng.fs.Fs#expandedPath} * * @method getEnv * @memberof ng.systemInfo * @static * @param {string} name * @returns {string} Value (empty if not set) ^jsdoc*/ QString SystemInfo::getEnv(const QString& name) const { return QProcessEnvironment::systemEnvironment().value(name); } } // namespace api
24.661765
87
0.717352
CommitteeOfZero
ee0399eb1bd7dd79a2afbc07d33d6c4e41bcf5d8
9,631
cpp
C++
QueryEngine/QueryPhysicalInputsCollector.cpp
intel-go/omniscidb
86068a229beddf7b117febcacdbd6b60a0279282
[ "Apache-2.0" ]
2
2020-03-04T12:01:10.000Z
2020-07-24T15:12:55.000Z
QueryEngine/QueryPhysicalInputsCollector.cpp
intel-go/omniscidb
86068a229beddf7b117febcacdbd6b60a0279282
[ "Apache-2.0" ]
18
2019-11-20T11:11:19.000Z
2020-08-27T13:21:12.000Z
QueryEngine/QueryPhysicalInputsCollector.cpp
intel-go/omniscidb
86068a229beddf7b117febcacdbd6b60a0279282
[ "Apache-2.0" ]
1
2020-04-04T06:25:32.000Z
2020-04-04T06:25:32.000Z
/* * Copyright 2017 MapD Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "QueryPhysicalInputsCollector.h" #include "RelAlgDagBuilder.h" #include "RelAlgVisitor.h" #include "RexVisitor.h" #include "Visitors/RelRexDagVisitor.h" #include "SchemaMgr/ColumnInfo.h" namespace { using InputColDescriptorSet = std::unordered_set<InputColDescriptor>; template <typename RexVisitor, typename ResultType> class RelAlgPhysicalInputsVisitor : public RelAlgVisitor<ResultType> { public: RelAlgPhysicalInputsVisitor() {} ResultType visitCompound(const RelCompound* compound) const override { ResultType result; for (size_t i = 0; i < compound->getScalarSourcesSize(); ++i) { const auto rex = compound->getScalarSource(i); CHECK(rex); RexVisitor visitor; const auto rex_phys_inputs = visitor.visit(rex); result.insert(rex_phys_inputs.begin(), rex_phys_inputs.end()); } const auto filter = compound->getFilterExpr(); if (filter) { RexVisitor visitor; const auto filter_phys_inputs = visitor.visit(filter); result.insert(filter_phys_inputs.begin(), filter_phys_inputs.end()); } return result; } ResultType visitFilter(const RelFilter* filter) const override { const auto condition = filter->getCondition(); CHECK(condition); RexVisitor visitor; return visitor.visit(condition); } ResultType visitJoin(const RelJoin* join) const override { const auto condition = join->getCondition(); if (!condition) { return ResultType{}; } RexVisitor visitor; return visitor.visit(condition); } ResultType visitLeftDeepInnerJoin( const RelLeftDeepInnerJoin* left_deep_inner_join) const override { ResultType result; const auto condition = left_deep_inner_join->getInnerCondition(); RexVisitor visitor; if (condition) { result = visitor.visit(condition); } CHECK_GE(left_deep_inner_join->inputCount(), size_t(2)); for (size_t nesting_level = 1; nesting_level <= left_deep_inner_join->inputCount() - 1; ++nesting_level) { const auto outer_condition = left_deep_inner_join->getOuterCondition(nesting_level); if (outer_condition) { const auto outer_result = visitor.visit(outer_condition); result.insert(outer_result.begin(), outer_result.end()); } } return result; } ResultType visitProject(const RelProject* project) const override { ResultType result; for (size_t i = 0; i < project->size(); ++i) { const auto rex = project->getProjectAt(i); CHECK(rex); RexVisitor visitor; const auto rex_phys_inputs = visitor.visit(rex); result.insert(rex_phys_inputs.begin(), rex_phys_inputs.end()); } return result; } ResultType visitSort(const RelSort* sort) const override { CHECK_EQ(sort->inputCount(), size_t(1)); return this->visit(sort->getInput(0)); } protected: ResultType aggregateResult(const ResultType& aggregate, const ResultType& next_result) const override { auto result = aggregate; result.insert(next_result.begin(), next_result.end()); return result; } }; template <typename Derived, typename ResultType> class RexInputVisitorBase : public RexVisitor<ResultType> { public: RexInputVisitorBase() {} ResultType visitSubQuery(const RexSubQuery* subquery) const override { const auto ra = subquery->getRelAlg(); CHECK(ra); RelAlgPhysicalInputsVisitor<Derived, ResultType> visitor; return visitor.visit(ra); } ResultType visitOperator(const RexOperator* oper) const override { ResultType result; if (auto window_oper = dynamic_cast<const RexWindowFunctionOperator*>(oper)) { for (const auto& partition_key : window_oper->getPartitionKeys()) { if (auto input = dynamic_cast<const RexInput*>(partition_key.get())) { const auto source_node = input->getSourceNode(); if (auto filter_node = dynamic_cast<const RelFilter*>(source_node)) { // Partitions utilize string dictionary translation in the hash join framework // if the partition key is a dictionary encoded string. Ensure we reach the // source for all partition keys, so we can access string dictionaries for the // partition keys while we build the partition (hash) table CHECK_EQ(filter_node->inputCount(), size_t(1)); const auto parent_node = filter_node->getInput(0); const auto node_inputs = get_node_output(parent_node); CHECK_LT(input->getIndex(), node_inputs.size()); result = aggregateResult(result, this->visitInput(&node_inputs[input->getIndex()])); } result = aggregateResult(result, this->visit(input)); } } } for (size_t i = 0; i < oper->size(); i++) { result = aggregateResult(result, this->visit(oper->getOperand(i))); } return result; } protected: ResultType aggregateResult(const ResultType& aggregate, const ResultType& next_result) const override { auto result = aggregate; result.insert(next_result.begin(), next_result.end()); return result; } }; class RexPhysicalInputsVisitor : public RexInputVisitorBase<RexPhysicalInputsVisitor, InputColDescriptorSet> { public: RexPhysicalInputsVisitor() {} InputColDescriptorSet visitInput(const RexInput* input) const override { const auto source_ra = input->getSourceNode(); const auto scan_ra = dynamic_cast<const RelScan*>(source_ra); if (!scan_ra) { const auto join_ra = dynamic_cast<const RelJoin*>(source_ra); if (join_ra) { const auto node_inputs = get_node_output(join_ra); CHECK_LT(input->getIndex(), node_inputs.size()); return visitInput(&node_inputs[input->getIndex()]); } return InputColDescriptorSet{}; } auto col_info = scan_ra->getColumnInfoBySpi(input->getIndex() + 1); CHECK_GT(col_info->table_id, 0); return {{col_info, 0}}; } }; template <typename RelAlgVisitor, typename ResultType> class RexSubqueryVisitorBase : public RexVisitor<ResultType> { public: RexSubqueryVisitorBase() {} ResultType visitSubQuery(const RexSubQuery* subquery) const override { const auto ra = subquery->getRelAlg(); CHECK(ra); RelAlgVisitor visitor; return visitor.visit(ra); } protected: ResultType aggregateResult(const ResultType& aggregate, const ResultType& next_result) const override { auto result = aggregate; result.insert(next_result.begin(), next_result.end()); return result; } }; class RelAlgPhysicalColumnInfosVisitor : public RelAlgPhysicalInputsVisitor< RexSubqueryVisitorBase<RelAlgPhysicalColumnInfosVisitor, ColumnInfoMap>, ColumnInfoMap> { public: RelAlgPhysicalColumnInfosVisitor() {} ColumnInfoMap visitScan(const RelScan* scan) const override { ColumnInfoMap res; for (size_t col_idx = 0; col_idx < scan->size(); ++col_idx) { auto col_info = scan->getColumnInfoBySpi(col_idx + 1); res.insert({*col_info, col_info}); } return res; } }; class RelAlgPhysicalTableInputsVisitor : public RelRexDagVisitor { public: RelAlgPhysicalTableInputsVisitor() {} using RelRexDagVisitor::visit; using TableIds = std::unordered_set<std::pair<int, int>>; static TableIds getTableIds(RelAlgNode const* node) { RelAlgPhysicalTableInputsVisitor visitor; visitor.visit(node); return std::move(visitor.table_ids_); } private: TableIds table_ids_; void visit(RelScan const* scan) override { table_ids_.insert({scan->getDatabaseId(), scan->getTableId()}); } }; class RelAlgPhysicalTableInfosVisitor : public RelAlgPhysicalInputsVisitor< RexSubqueryVisitorBase<RelAlgPhysicalTableInfosVisitor, TableInfoMap>, TableInfoMap> { public: RelAlgPhysicalTableInfosVisitor() {} TableInfoMap visitScan(const RelScan* scan) const override { TableInfoMap res; auto info = scan->getTableInfo(); res.insert(std::make_pair(TableRef(info->db_id, info->table_id), info)); return res; } }; } // namespace std::unordered_set<InputColDescriptor> get_physical_inputs(const RelAlgNode* ra) { RelAlgPhysicalInputsVisitor<RexPhysicalInputsVisitor, InputColDescriptorSet> phys_inputs_visitor; return phys_inputs_visitor.visit(ra); } std::unordered_set<std::pair<int, int>> get_physical_table_inputs(const RelAlgNode* ra) { return RelAlgPhysicalTableInputsVisitor::getTableIds(ra); } ColumnInfoMap get_physical_column_infos(const RelAlgNode* ra) { RelAlgPhysicalColumnInfosVisitor visitor; return visitor.visit(ra); } TableInfoMap get_physical_table_infos(const RelAlgNode* ra) { RelAlgPhysicalTableInfosVisitor visitor; return visitor.visit(ra); } std::ostream& operator<<(std::ostream& os, PhysicalInput const& physical_input) { return os << '(' << physical_input.col_id << ',' << physical_input.table_id << ')'; }
33.210345
90
0.702108
intel-go
ee07604693912d01e39210b9cd403747b98e8ec8
546
cpp
C++
problems/cf_1453_b.cpp
datasakura/informatika
71272271931b610f89eaf85ab89c199758d4a032
[ "MIT" ]
null
null
null
problems/cf_1453_b.cpp
datasakura/informatika
71272271931b610f89eaf85ab89c199758d4a032
[ "MIT" ]
null
null
null
problems/cf_1453_b.cpp
datasakura/informatika
71272271931b610f89eaf85ab89c199758d4a032
[ "MIT" ]
1
2020-10-01T06:23:52.000Z
2020-10-01T06:23:52.000Z
#include <iostream> #include <vector> using namespace std; int main() { int tests; cin >> tests; while (tests--) { int n; cin >> n; vector<int> a(n); for (int& i : a) cin >> i; long long ans0 = 0; for (int i = 1; i < n; i++) ans0 += abs(a[i] - a[i - 1]); long long ans = ans0 - max(abs(a[1] - a[0]), abs(a[n - 1] - a[n - 2])); for (int i = 2; i < n; i++) { ans = min(ans, ans0 - abs(a[i - 0] - a[i - 1]) - abs(a[i - 1] - a[i - 2]) + abs(a[i - 0] - a[i - 2])); } cout << ans << endl; } return 0; }
18.827586
73
0.454212
datasakura
ee0c62cf6e3dc93ec85c02d35a6db9ea93175f5f
370
cpp
C++
codes/HDU/hdu4969.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu4969.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu4969.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> using namespace std; int main () { int cas; double v1, v2, r, d; scanf("%d", &cas); while (cas--) { scanf("%lf%lf%lf%lf", &v1, &v2, &r, &d); double t = r / v1 * asin(v1 / v2); double l = t * v2; printf("%s\n", l > d ? "Why give up treatment" : "Wake up to code"); } return 0; }
17.619048
70
0.562162
JeraKrs
ee0d9539675497b50af4d0b64a5cc3e2cff70c52
32,910
cxx
C++
utils/examples/sequences/Sequences.cxx
eProsima/Non-Intrusive-DDS-Recorder
94ef1dba8cca868c173e3d92ba383f9833d15389
[ "Apache-2.0" ]
7
2019-06-04T12:45:01.000Z
2021-09-27T16:20:35.000Z
utils/examples/sequences/Sequences.cxx
eProsima/Non-Intrusive-DDS-Recorder
94ef1dba8cca868c173e3d92ba383f9833d15389
[ "Apache-2.0" ]
5
2020-12-09T16:40:47.000Z
2021-11-22T15:37:59.000Z
utils/examples/sequences/Sequences.cxx
eProsima/Non-Intrusive-DDS-Recorder
94ef1dba8cca868c173e3d92ba383f9833d15389
[ "Apache-2.0" ]
5
2019-04-04T06:13:36.000Z
2021-10-18T07:47:23.000Z
/* WARNING: THIS FILE IS AUTO-GENERATED. DO NOT MODIFY. This file was generated from Sequences.idl using "rtiddsgen". The rtiddsgen tool is part of the RTI Data Distribution Service distribution. For more information, type 'rtiddsgen -help' at a command shell or consult the RTI Data Distribution Service manual. */ #ifndef NDDS_STANDALONE_TYPE #ifdef __cplusplus #ifndef ndds_cpp_h #include "ndds/ndds_cpp.h" #endif #ifndef dds_c_log_impl_h #include "dds_c/dds_c_log_impl.h" #endif #else #ifndef ndds_c_h #include "ndds/ndds_c.h" #endif #endif #ifndef cdr_type_h #include "cdr/cdr_type.h" #endif #ifndef osapi_heap_h #include "osapi/osapi_heap.h" #endif #else #include "ndds_standalone_type.h" #endif #ifndef Sequences_h #include "Sequences.h" #endif /* ========================================================================= */ const char *InsideTYPENAME = "Inside"; DDS_TypeCode* Inside_get_typecode() { static RTIBool is_initialized = RTI_FALSE; static DDS_TypeCode Inside_g_tc_seoc_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Inside_g_tc_sesh_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Inside_g_tc_seush_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Inside_g_tc_selo_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Inside_g_tc_seulo_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Inside_g_tc_selolo_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Inside_g_tc_seulolo_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Inside_g_tc_sech_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Inside_g_tc_sefl_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Inside_g_tc_sedl_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode_Member Inside_g_tc_members[11]= { { (char *)"count",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"seoc",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"sesh",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"seush",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"selo",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"seulo",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"selolo",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"seulolo",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"sech",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"sefl",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"sedl",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ } }; static DDS_TypeCode Inside_g_tc = {{ DDS_TK_STRUCT,/* Kind */ DDS_BOOLEAN_FALSE, /* Ignored */ -1,/* Ignored */ (char *)"Inside", /* Name */ NULL, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ 11, /* Number of members */ Inside_g_tc_members, /* Members */ DDS_VM_NONE /* Ignored */ }}; /* Type code for Inside*/ if (is_initialized) { return &Inside_g_tc; } Inside_g_tc_seoc_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_octet; Inside_g_tc_sesh_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_short; Inside_g_tc_seush_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_ushort; Inside_g_tc_selo_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_long; Inside_g_tc_seulo_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_ulong; Inside_g_tc_selolo_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_longlong; Inside_g_tc_seulolo_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_ulonglong; Inside_g_tc_sech_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_char; Inside_g_tc_sefl_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_float; Inside_g_tc_sedl_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_double; Inside_g_tc_members[0]._representation._typeCode = (RTICdrTypeCode *)&DDS_g_tc_short; Inside_g_tc_members[1]._representation._typeCode = (RTICdrTypeCode *)&Inside_g_tc_seoc_sequence; Inside_g_tc_members[2]._representation._typeCode = (RTICdrTypeCode *)&Inside_g_tc_sesh_sequence; Inside_g_tc_members[3]._representation._typeCode = (RTICdrTypeCode *)&Inside_g_tc_seush_sequence; Inside_g_tc_members[4]._representation._typeCode = (RTICdrTypeCode *)&Inside_g_tc_selo_sequence; Inside_g_tc_members[5]._representation._typeCode = (RTICdrTypeCode *)&Inside_g_tc_seulo_sequence; Inside_g_tc_members[6]._representation._typeCode = (RTICdrTypeCode *)&Inside_g_tc_selolo_sequence; Inside_g_tc_members[7]._representation._typeCode = (RTICdrTypeCode *)&Inside_g_tc_seulolo_sequence; Inside_g_tc_members[8]._representation._typeCode = (RTICdrTypeCode *)&Inside_g_tc_sech_sequence; Inside_g_tc_members[9]._representation._typeCode = (RTICdrTypeCode *)&Inside_g_tc_sefl_sequence; Inside_g_tc_members[10]._representation._typeCode = (RTICdrTypeCode *)&Inside_g_tc_sedl_sequence; is_initialized = RTI_TRUE; return &Inside_g_tc; } RTIBool Inside_initialize( Inside* sample) { return Inside_initialize_ex(sample,RTI_TRUE); } RTIBool Inside_initialize_ex( Inside* sample,RTIBool allocatePointers) { void* buffer; buffer = NULL; if (!RTICdrType_initShort(&sample->count)) { return RTI_FALSE; } DDS_OctetSeq_initialize(&sample->seoc); if (!DDS_OctetSeq_set_maximum(&sample->seoc, (100))) { return RTI_FALSE; } DDS_ShortSeq_initialize(&sample->sesh); if (!DDS_ShortSeq_set_maximum(&sample->sesh, (100))) { return RTI_FALSE; } DDS_UnsignedShortSeq_initialize(&sample->seush); if (!DDS_UnsignedShortSeq_set_maximum(&sample->seush, (100))) { return RTI_FALSE; } DDS_LongSeq_initialize(&sample->selo); if (!DDS_LongSeq_set_maximum(&sample->selo, (100))) { return RTI_FALSE; } DDS_UnsignedLongSeq_initialize(&sample->seulo); if (!DDS_UnsignedLongSeq_set_maximum(&sample->seulo, (100))) { return RTI_FALSE; } DDS_LongLongSeq_initialize(&sample->selolo); if (!DDS_LongLongSeq_set_maximum(&sample->selolo, (100))) { return RTI_FALSE; } DDS_UnsignedLongLongSeq_initialize(&sample->seulolo); if (!DDS_UnsignedLongLongSeq_set_maximum(&sample->seulolo, (100))) { return RTI_FALSE; } DDS_CharSeq_initialize(&sample->sech); if (!DDS_CharSeq_set_maximum(&sample->sech, (100))) { return RTI_FALSE; } DDS_FloatSeq_initialize(&sample->sefl); if (!DDS_FloatSeq_set_maximum(&sample->sefl, (100))) { return RTI_FALSE; } DDS_DoubleSeq_initialize(&sample->sedl); if (!DDS_DoubleSeq_set_maximum(&sample->sedl, (100))) { return RTI_FALSE; } return RTI_TRUE; } void Inside_finalize( Inside* sample) { Inside_finalize_ex(sample,RTI_TRUE); } void Inside_finalize_ex( Inside* sample,RTIBool deletePointers) { DDS_OctetSeq_finalize(&sample->seoc); DDS_ShortSeq_finalize(&sample->sesh); DDS_UnsignedShortSeq_finalize(&sample->seush); DDS_LongSeq_finalize(&sample->selo); DDS_UnsignedLongSeq_finalize(&sample->seulo); DDS_LongLongSeq_finalize(&sample->selolo); DDS_UnsignedLongLongSeq_finalize(&sample->seulolo); DDS_CharSeq_finalize(&sample->sech); DDS_FloatSeq_finalize(&sample->sefl); DDS_DoubleSeq_finalize(&sample->sedl); } RTIBool Inside_copy( Inside* dst, const Inside* src) { if (!RTICdrType_copyShort( &dst->count, &src->count)) { return RTI_FALSE; } if (!DDS_OctetSeq_copy_no_alloc(&dst->seoc, &src->seoc)) { return RTI_FALSE; } if (!DDS_ShortSeq_copy_no_alloc(&dst->sesh, &src->sesh)) { return RTI_FALSE; } if (!DDS_UnsignedShortSeq_copy_no_alloc(&dst->seush, &src->seush)) { return RTI_FALSE; } if (!DDS_LongSeq_copy_no_alloc(&dst->selo, &src->selo)) { return RTI_FALSE; } if (!DDS_UnsignedLongSeq_copy_no_alloc(&dst->seulo, &src->seulo)) { return RTI_FALSE; } if (!DDS_LongLongSeq_copy_no_alloc(&dst->selolo, &src->selolo)) { return RTI_FALSE; } if (!DDS_UnsignedLongLongSeq_copy_no_alloc(&dst->seulolo, &src->seulolo)) { return RTI_FALSE; } if (!DDS_CharSeq_copy_no_alloc(&dst->sech, &src->sech)) { return RTI_FALSE; } if (!DDS_FloatSeq_copy_no_alloc(&dst->sefl, &src->sefl)) { return RTI_FALSE; } if (!DDS_DoubleSeq_copy_no_alloc(&dst->sedl, &src->sedl)) { return RTI_FALSE; } return RTI_TRUE; } /** * <<IMPLEMENTATION>> * * Defines: TSeq, T * * Configure and implement 'Inside' sequence class. */ #define T Inside #define TSeq InsideSeq #define T_initialize_ex Inside_initialize_ex #define T_finalize_ex Inside_finalize_ex #define T_copy Inside_copy #ifndef NDDS_STANDALONE_TYPE #include "dds_c/generic/dds_c_sequence_TSeq.gen" #ifdef __cplusplus #include "dds_cpp/generic/dds_cpp_sequence_TSeq.gen" #endif #else #include "dds_c_sequence_TSeq.gen" #ifdef __cplusplus #include "dds_cpp_sequence_TSeq.gen" #endif #endif #undef T_copy #undef T_finalize_ex #undef T_initialize_ex #undef TSeq #undef T /* ========================================================================= */ const char *SequencesTYPENAME = "Sequences"; DDS_TypeCode* Sequences_get_typecode() { static RTIBool is_initialized = RTI_FALSE; static DDS_TypeCode Sequences_g_tc_message_string = DDS_INITIALIZE_STRING_TYPECODE(255); static DDS_TypeCode Sequences_g_tc_seoc_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Sequences_g_tc_sesh_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Sequences_g_tc_seush_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Sequences_g_tc_selo_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Sequences_g_tc_seulo_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Sequences_g_tc_selolo_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Sequences_g_tc_seulolo_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Sequences_g_tc_sech_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Sequences_g_tc_sefl_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode Sequences_g_tc_sedl_sequence = DDS_INITIALIZE_SEQUENCE_TYPECODE(100,NULL); static DDS_TypeCode_Member Sequences_g_tc_members[12]= { { (char *)"message",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"seoc",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"sesh",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"seush",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"selo",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"seulo",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"selolo",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"seulolo",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"sech",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"sefl",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"sedl",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ }, { (char *)"ins",/* Member name */ { 0,/* Representation ID */ DDS_BOOLEAN_FALSE,/* Is a pointer? */ -1, /* Bitfield bits */ NULL/* Member type code is assigned later */ }, 0, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ DDS_BOOLEAN_FALSE, /* Is a key? */ DDS_PRIVATE_MEMBER,/* Ignored */ 0,/* Ignored */ NULL/* Ignored */ } }; static DDS_TypeCode Sequences_g_tc = {{ DDS_TK_STRUCT,/* Kind */ DDS_BOOLEAN_FALSE, /* Ignored */ -1,/* Ignored */ (char *)"Sequences", /* Name */ NULL, /* Ignored */ 0, /* Ignored */ 0, /* Ignored */ NULL, /* Ignored */ 12, /* Number of members */ Sequences_g_tc_members, /* Members */ DDS_VM_NONE /* Ignored */ }}; /* Type code for Sequences*/ if (is_initialized) { return &Sequences_g_tc; } Sequences_g_tc_seoc_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_octet; Sequences_g_tc_sesh_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_short; Sequences_g_tc_seush_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_ushort; Sequences_g_tc_selo_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_long; Sequences_g_tc_seulo_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_ulong; Sequences_g_tc_selolo_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_longlong; Sequences_g_tc_seulolo_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_ulonglong; Sequences_g_tc_sech_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_char; Sequences_g_tc_sefl_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_float; Sequences_g_tc_sedl_sequence._data._typeCode = (RTICdrTypeCode *)&DDS_g_tc_double; Sequences_g_tc_members[0]._representation._typeCode = (RTICdrTypeCode *)&Sequences_g_tc_message_string; Sequences_g_tc_members[1]._representation._typeCode = (RTICdrTypeCode *)&Sequences_g_tc_seoc_sequence; Sequences_g_tc_members[2]._representation._typeCode = (RTICdrTypeCode *)&Sequences_g_tc_sesh_sequence; Sequences_g_tc_members[3]._representation._typeCode = (RTICdrTypeCode *)&Sequences_g_tc_seush_sequence; Sequences_g_tc_members[4]._representation._typeCode = (RTICdrTypeCode *)&Sequences_g_tc_selo_sequence; Sequences_g_tc_members[5]._representation._typeCode = (RTICdrTypeCode *)&Sequences_g_tc_seulo_sequence; Sequences_g_tc_members[6]._representation._typeCode = (RTICdrTypeCode *)&Sequences_g_tc_selolo_sequence; Sequences_g_tc_members[7]._representation._typeCode = (RTICdrTypeCode *)&Sequences_g_tc_seulolo_sequence; Sequences_g_tc_members[8]._representation._typeCode = (RTICdrTypeCode *)&Sequences_g_tc_sech_sequence; Sequences_g_tc_members[9]._representation._typeCode = (RTICdrTypeCode *)&Sequences_g_tc_sefl_sequence; Sequences_g_tc_members[10]._representation._typeCode = (RTICdrTypeCode *)&Sequences_g_tc_sedl_sequence; Sequences_g_tc_members[11]._representation._typeCode = (RTICdrTypeCode *)Inside_get_typecode(); is_initialized = RTI_TRUE; return &Sequences_g_tc; } RTIBool Sequences_initialize( Sequences* sample) { return Sequences_initialize_ex(sample,RTI_TRUE); } RTIBool Sequences_initialize_ex( Sequences* sample,RTIBool allocatePointers) { void* buffer; buffer = NULL; sample->message = DDS_String_alloc((255)); if (sample->message == NULL) { return RTI_FALSE; } DDS_OctetSeq_initialize(&sample->seoc); if (!DDS_OctetSeq_set_maximum(&sample->seoc, (100))) { return RTI_FALSE; } DDS_ShortSeq_initialize(&sample->sesh); if (!DDS_ShortSeq_set_maximum(&sample->sesh, (100))) { return RTI_FALSE; } DDS_UnsignedShortSeq_initialize(&sample->seush); if (!DDS_UnsignedShortSeq_set_maximum(&sample->seush, (100))) { return RTI_FALSE; } DDS_LongSeq_initialize(&sample->selo); if (!DDS_LongSeq_set_maximum(&sample->selo, (100))) { return RTI_FALSE; } DDS_UnsignedLongSeq_initialize(&sample->seulo); if (!DDS_UnsignedLongSeq_set_maximum(&sample->seulo, (100))) { return RTI_FALSE; } DDS_LongLongSeq_initialize(&sample->selolo); if (!DDS_LongLongSeq_set_maximum(&sample->selolo, (100))) { return RTI_FALSE; } DDS_UnsignedLongLongSeq_initialize(&sample->seulolo); if (!DDS_UnsignedLongLongSeq_set_maximum(&sample->seulolo, (100))) { return RTI_FALSE; } DDS_CharSeq_initialize(&sample->sech); if (!DDS_CharSeq_set_maximum(&sample->sech, (100))) { return RTI_FALSE; } DDS_FloatSeq_initialize(&sample->sefl); if (!DDS_FloatSeq_set_maximum(&sample->sefl, (100))) { return RTI_FALSE; } DDS_DoubleSeq_initialize(&sample->sedl); if (!DDS_DoubleSeq_set_maximum(&sample->sedl, (100))) { return RTI_FALSE; } if (!Inside_initialize_ex(&sample->ins,allocatePointers)) { return RTI_FALSE; } return RTI_TRUE; } void Sequences_finalize( Sequences* sample) { Sequences_finalize_ex(sample,RTI_TRUE); } void Sequences_finalize_ex( Sequences* sample,RTIBool deletePointers) { DDS_String_free(sample->message); DDS_OctetSeq_finalize(&sample->seoc); DDS_ShortSeq_finalize(&sample->sesh); DDS_UnsignedShortSeq_finalize(&sample->seush); DDS_LongSeq_finalize(&sample->selo); DDS_UnsignedLongSeq_finalize(&sample->seulo); DDS_LongLongSeq_finalize(&sample->selolo); DDS_UnsignedLongLongSeq_finalize(&sample->seulolo); DDS_CharSeq_finalize(&sample->sech); DDS_FloatSeq_finalize(&sample->sefl); DDS_DoubleSeq_finalize(&sample->sedl); Inside_finalize_ex(&sample->ins,deletePointers); } RTIBool Sequences_copy( Sequences* dst, const Sequences* src) { if (!RTICdrType_copyString( dst->message, src->message, (255) + 1)) { return RTI_FALSE; } if (!DDS_OctetSeq_copy_no_alloc(&dst->seoc, &src->seoc)) { return RTI_FALSE; } if (!DDS_ShortSeq_copy_no_alloc(&dst->sesh, &src->sesh)) { return RTI_FALSE; } if (!DDS_UnsignedShortSeq_copy_no_alloc(&dst->seush, &src->seush)) { return RTI_FALSE; } if (!DDS_LongSeq_copy_no_alloc(&dst->selo, &src->selo)) { return RTI_FALSE; } if (!DDS_UnsignedLongSeq_copy_no_alloc(&dst->seulo, &src->seulo)) { return RTI_FALSE; } if (!DDS_LongLongSeq_copy_no_alloc(&dst->selolo, &src->selolo)) { return RTI_FALSE; } if (!DDS_UnsignedLongLongSeq_copy_no_alloc(&dst->seulolo, &src->seulolo)) { return RTI_FALSE; } if (!DDS_CharSeq_copy_no_alloc(&dst->sech, &src->sech)) { return RTI_FALSE; } if (!DDS_FloatSeq_copy_no_alloc(&dst->sefl, &src->sefl)) { return RTI_FALSE; } if (!DDS_DoubleSeq_copy_no_alloc(&dst->sedl, &src->sedl)) { return RTI_FALSE; } if (!Inside_copy( &dst->ins, &src->ins)) { return RTI_FALSE; } return RTI_TRUE; } /** * <<IMPLEMENTATION>> * * Defines: TSeq, T * * Configure and implement 'Sequences' sequence class. */ #define T Sequences #define TSeq SequencesSeq #define T_initialize_ex Sequences_initialize_ex #define T_finalize_ex Sequences_finalize_ex #define T_copy Sequences_copy #ifndef NDDS_STANDALONE_TYPE #include "dds_c/generic/dds_c_sequence_TSeq.gen" #ifdef __cplusplus #include "dds_cpp/generic/dds_cpp_sequence_TSeq.gen" #endif #else #include "dds_c_sequence_TSeq.gen" #ifdef __cplusplus #include "dds_cpp_sequence_TSeq.gen" #endif #endif #undef T_copy #undef T_finalize_ex #undef T_initialize_ex #undef TSeq #undef T
32.076023
109
0.527803
eProsima
ee153f9c0c41b83f72f69abc8d043bd57c568509
6,206
hpp
C++
packages/monte_carlo/core/src/MonteCarlo_SimulationPhotonProperties.hpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/monte_carlo/core/src/MonteCarlo_SimulationPhotonProperties.hpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/monte_carlo/core/src/MonteCarlo_SimulationPhotonProperties.hpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_SimulationPhotonProperties.hpp //! \author Alex Robinson, Luke Kersting //! \brief Simulation photon properties class decl. //! //---------------------------------------------------------------------------// #ifndef MONTE_CARLO_SIMULATION_PHOTON_PROPERTIES_HPP #define MONTE_CARLO_SIMULATION_PHOTON_PROPERTIES_HPP // FRENSIE Includes #include "MonteCarlo_ParticleModeType.hpp" #include "MonteCarlo_IncoherentModelType.hpp" namespace MonteCarlo{ /*! The simulation properties class * \todo Modify XML parser to handle all options in this class. Use this class * in all parts of code that require runtime configuration. */ class SimulationPhotonProperties { public: //! Set the minimum photon energy (MeV) static void setMinPhotonEnergy( const double energy ); //! Return the minimum photon energy (MeV) static double getMinPhotonEnergy(); //! Return the absolute minimum photon energy (MeV) static double getAbsoluteMinPhotonEnergy(); //! Set the maximum photon energy (MeV) static void setMaxPhotonEnergy( const double energy ); //! Return the maximum photon energy (MeV) static double getMaxPhotonEnergy(); //! Return the absolute maximum photon energy (MeV) static double getAbsoluteMaxPhotonEnergy(); //! Set the Kahn sampling cutoff energy (MeV) static void setKahnSamplingCutoffEnergy( const double energy ); //! Return the Kahn sampling cutoff energy (MeV) static double getKahnSamplingCutoffEnergy(); //! Return the absolute min Kahn sampling cutoff energy (MeV) static double getAbsoluteMinKahnSamplingCutoffEnergy(); //! Set the number of photon hash grid bins static void setNumberOfPhotonHashGridBins( const unsigned bins ); //! Get the number of photon hash grid bins static unsigned getNumberOfPhotonHashGridBins(); //! Set the incoherent model type static void setIncoherentModelType( const IncoherentModelType model ); //! Return the incohernt model static IncoherentModelType getIncoherentModelType(); //! Set atomic relaxation mode to off (on by default) static void setAtomicRelaxationModeOff(); //! Return if atomic relaxation mode is on static bool isAtomicRelaxationModeOn(); //! Set detailed pair production mode to on (off by default) static void setDetailedPairProductionModeOn(); //! Return if detailed pair production mode is on static bool isDetailedPairProductionModeOn(); //! Set photonuclear interaction mode to on (off by default) static void setPhotonuclearInteractionModeOn(); //! Return if photonuclear interaction mode is on static bool isPhotonuclearInteractionModeOn(); private: // The absolute minimum photon energy (MeV) static const double absolute_min_photon_energy; // The minimum photon energy (MeV) static double min_photon_energy; // The maximum photon energy (MeV) static double max_photon_energy; // The absolute maximum photon energy static const double absolute_max_photon_energy; // The Kahn sampling cutoff energy (MeV) static double kahn_sampling_cutoff_energy; // The absolute min Kahn sampling cutoff energy (MeV) static const double absolute_min_kahn_sampling_cutoff_energy; // The number of photon hash grid bins static unsigned num_photon_hash_grid_bins; // The incoherent model static IncoherentModelType incoherent_model_type; // The atomic relaxation mode (true = on - default, false = off) static bool atomic_relaxation_mode_on; // The detailed pair production mode (true = on, false = off - default) static bool detailed_pair_production_mode_on; // The photonuclear interaction mode (true = on, false = off - default) static bool photonuclear_interaction_mode_on; }; // Return the minimum photon energy (MeV) inline double SimulationPhotonProperties::getMinPhotonEnergy() { return SimulationPhotonProperties::min_photon_energy; } // Return the absolute minimum photon energy (MeV) inline double SimulationPhotonProperties::getAbsoluteMinPhotonEnergy() { return SimulationPhotonProperties::absolute_min_photon_energy; } // Return the maximum photon energy (MeV) - cannot be set at runtime inline double SimulationPhotonProperties::getMaxPhotonEnergy() { return SimulationPhotonProperties::max_photon_energy; } // Return the absolute maximum photon energy (MeV) inline double SimulationPhotonProperties::getAbsoluteMaxPhotonEnergy() { return SimulationPhotonProperties::absolute_max_photon_energy; } // Return the Kahn sampling cutoff energy (MeV) inline double SimulationPhotonProperties::getKahnSamplingCutoffEnergy() { return SimulationPhotonProperties::kahn_sampling_cutoff_energy; } // Return the absolute min Kahn sampling cutoff energy (MeV) inline double SimulationPhotonProperties::getAbsoluteMinKahnSamplingCutoffEnergy() { return SimulationPhotonProperties::absolute_min_kahn_sampling_cutoff_energy; } // Get the number of photon hash grid bins inline unsigned SimulationPhotonProperties::getNumberOfPhotonHashGridBins() { return SimulationPhotonProperties::num_photon_hash_grid_bins; } // Return the incohernt model inline IncoherentModelType SimulationPhotonProperties::getIncoherentModelType() { return SimulationPhotonProperties::incoherent_model_type; } // Return if atomic relaxation mode is on inline bool SimulationPhotonProperties::isAtomicRelaxationModeOn() { return SimulationPhotonProperties::atomic_relaxation_mode_on; } // Return if detailed pair production mode is on inline bool SimulationPhotonProperties::isDetailedPairProductionModeOn() { return SimulationPhotonProperties::detailed_pair_production_mode_on; } // Return if photonuclear interaction mode is on inline bool SimulationPhotonProperties::isPhotonuclearInteractionModeOn() { return SimulationPhotonProperties::photonuclear_interaction_mode_on; } } // end MonteCarlo namespace #endif // end MONTE_CARLO_SIMULATION_PHOTON_PROPERTIES_HPP //---------------------------------------------------------------------------// // end MonteCarlo_SimulationPhotonProperties.cpp //---------------------------------------------------------------------------//
32.15544
82
0.753626
lkersting
ee16e13195ca2c8b41142afcf549e62fc88c8c89
1,184
cpp
C++
mr/iza810/raspi_utility/src/pigpiod.cpp
Kitasola/robocon_2019b
43acfa88fb49ddeb7ec9e15976854936a71e92b6
[ "MIT" ]
5
2020-01-24T08:05:01.000Z
2020-08-03T04:51:52.000Z
mr/iza810/raspi_utility/src/pigpiod.cpp
Kitasola/robocon_2019b
43acfa88fb49ddeb7ec9e15976854936a71e92b6
[ "MIT" ]
null
null
null
mr/iza810/raspi_utility/src/pigpiod.cpp
Kitasola/robocon_2019b
43acfa88fb49ddeb7ec9e15976854936a71e92b6
[ "MIT" ]
1
2020-07-15T05:43:48.000Z
2020-07-15T05:43:48.000Z
#include "../include/pigpiod.hpp" #include <pigpiod_if2.h> using namespace arrc_raspi; Pigpiod::Pigpiod() { gpio_handle_ = pigpio_start(const_cast<char *>(PIGPIOD_HOST), const_cast<char *>(PIGPIOD_PORT)); } void Pigpiod::write(int pin, int level) { gpio_write(gpio_handle_, pin, level); } int Pigpiod::read(int pin) { return gpio_read(gpio_handle_, pin); } void Pigpiod::set(int pin, int mode, int init) { if (mode == IN) { set_mode(gpio_handle_, pin, PI_INPUT); if (init == PULL_UP) { set_pull_up_down(gpio_handle_, pin, PI_PUD_UP); } else if (init == PULL_DOWN) { set_pull_up_down(gpio_handle_, pin, PI_PUD_DOWN); } else if (init == PULL_OFF) { set_pull_up_down(gpio_handle_, pin, PI_PUD_OFF); } } else if (mode == OUT) { set_mode(gpio_handle_, pin, PI_OUTPUT); gpio_write(gpio_handle_, pin, init); } } int Pigpiod::checkHandle() { return gpio_handle_; } bool Pigpiod::checkInit() { if (gpio_handle_ < 0) { return false; } else { return true; } } void Pigpiod::delay(double micro_sec) { time_sleep(micro_sec / 1000000); } Pigpiod::~Pigpiod() { pigpio_stop(gpio_handle_); }
25.73913
74
0.658784
Kitasola
ee1720e3abc174fbafa147712c6922cb2fc017fc
258
cpp
C++
cpac/codeforces/600/cards.cpp
abhinavsri360/Allcodes
0dfc3367ecc1df58f502f20ff3d732c49c62f140
[ "MIT" ]
5
2020-07-17T04:52:09.000Z
2022-02-15T19:53:09.000Z
cpac/codeforces/600/cards.cpp
abhinavsri360/Allcodes
0dfc3367ecc1df58f502f20ff3d732c49c62f140
[ "MIT" ]
null
null
null
cpac/codeforces/600/cards.cpp
abhinavsri360/Allcodes
0dfc3367ecc1df58f502f20ff3d732c49c62f140
[ "MIT" ]
1
2022-02-15T19:53:16.000Z
2022-02-15T19:53:16.000Z
#include<iostream> using namespace std; int main() { int num,z=0,n=0; string s; cin>>num; cin>>s; for(int i=0;i<num;i++) { if(s[i]=='z') z++; if(s[i]=='n') n++; } while(n--) cout<<"1 "; while(z--) cout<<"0 "; cout<<endl; return 0; }
11.217391
23
0.496124
abhinavsri360
ee177fb15c59539378488a0a5845cefac26bb674
870
cpp
C++
octree/tools/octree_samples.cpp
pauldinh/O-CNN
fecefd92b559bdfe94a3983b2b010645167c41a1
[ "MIT" ]
299
2019-05-27T02:18:56.000Z
2022-03-31T15:29:20.000Z
octree/tools/octree_samples.cpp
pauldinh/O-CNN
fecefd92b559bdfe94a3983b2b010645167c41a1
[ "MIT" ]
100
2019-05-07T03:17:01.000Z
2022-03-30T09:02:04.000Z
octree/tools/octree_samples.cpp
pauldinh/O-CNN
fecefd92b559bdfe94a3983b2b010645167c41a1
[ "MIT" ]
84
2019-05-17T17:44:06.000Z
2022-02-14T04:32:02.000Z
#include <iostream> #include <fstream> #include "octree_samples.h" #include "filenames.h" #include "cmd_flags.h" DEFINE_string(output_path, kRequired, ".", "The output path"); using std::cout; int main(int argc, char* argv[]) { bool succ = cflags::ParseCmd(argc, argv); if (!succ) { cflags::PrintHelpInfo("\nUsage: octree_samples.exe"); return 0; } string output_path = FLAGS_output_path; if (output_path != ".") mkdir(output_path); output_path += "/"; for (int i = 1; i < 7; i++) { string filename = "octree_" + std::to_string(i); size_t size = 0; const char* ptr = (const char*)octree::get_one_octree(filename.c_str(), &size); std::ofstream outfile(output_path + filename + ".octree", std::ios::binary); outfile.write(ptr, size); outfile.close(); cout << "Save: " << filename << std::endl; } return 0; }
22.894737
83
0.636782
pauldinh
ee1994105c0e9e1d3518b9991e8e425f342516be
1,313
cpp
C++
designpattern/AbstractFactory.cpp
armsword/CppSkills
162a83f78d3d2c8607559e03d683c90d3198cab1
[ "MIT" ]
1
2015-04-29T14:32:38.000Z
2015-04-29T14:32:38.000Z
designpattern/AbstractFactory.cpp
armsword/CppSkills
162a83f78d3d2c8607559e03d683c90d3198cab1
[ "MIT" ]
null
null
null
designpattern/AbstractFactory.cpp
armsword/CppSkills
162a83f78d3d2c8607559e03d683c90d3198cab1
[ "MIT" ]
null
null
null
/* 工厂方法模式也有缺点,每增加一种产品,就需要增加一个对象的工厂。如果这家公司发展迅速,推出了很多新的处理器核,那么就要新开设相应的新工厂。在C++实现中,就是要定义一个个的工厂类。显然,相比简单工厂模式,工厂方法模式需要更多的类定义。 */ /* 既然有了简单工厂模式和工厂方法模式,为什么还要有抽象工厂模式呢?它到底有什么作用呢?还是举例子,这家公司的技术不断进步,不仅可以生产单核处理器,也能生产多喝处理器。现在简单工厂模式和工厂方法模式都鞭长莫及。抽象工厂模式登场了。它的定义为提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的类。 */ // 单核 class SingleCore { public: virtual void Show() = 0; }; class SingleCoreA : public SingleCore { public: void Show() {cout << "Single Core A"<<endl;} }; class SingleCoreB : public SingleCore { public: void Show() {cout << "Single Core B"<<endl;} }; // 多核 class MultiCore { public: virtual void Show() = 0; }; class MultiCoreA : public MultiCore { public: void Show() {cout<<"Multi Core A"<<endl;} }; class MultiCoreB : public MultiCore { public: void Show() {cout<<"Multi Core B"<<endl;} }; // 工厂 class CoreFactory { public: virtual SingleCore* CreateSingleCore() = 0; virtual MultiCore* CreateMultiCore() = 0; }; // 工厂A,专门用来生产A型号的处理器 class FactoryA : public CoreFactory { public: SingleCore* CreateSingleCore() {return new SingleCoreA();} MultiCore* CreateMultiCore() {return new MultiCoreA();} }; // 工厂B,专门用来生产B型号的处理器 class FactoryB : public CoreFactory { public: SingleCore* CreateSingleCore() {return new SingleCoreB();} MultiCore* CreateMultiCore() {return new MultiCoreB();} };
19.308824
156
0.722011
armsword
ee1b41e2b6c7a61390118b514e29f7220f8dade9
4,301
hpp
C++
src/vlGraphics/DistanceLODEvaluator.hpp
pasenau/VisualizationLibrary
2fcf1808475aebd4862f40377754be62a7f77a52
[ "BSD-2-Clause" ]
1
2017-06-29T18:25:11.000Z
2017-06-29T18:25:11.000Z
src/vlGraphics/DistanceLODEvaluator.hpp
pasenau/VisualizationLibrary
2fcf1808475aebd4862f40377754be62a7f77a52
[ "BSD-2-Clause" ]
null
null
null
src/vlGraphics/DistanceLODEvaluator.hpp
pasenau/VisualizationLibrary
2fcf1808475aebd4862f40377754be62a7f77a52
[ "BSD-2-Clause" ]
1
2021-01-01T10:43:33.000Z
2021-01-01T10:43:33.000Z
/**************************************************************************************/ /* */ /* Visualization Library */ /* http://visualizationlibrary.org */ /* */ /* Copyright (c) 2005-2017, Michele Bosi */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or without modification, */ /* are permitted provided that the following conditions are met: */ /* */ /* - Redistributions of source code must retain the above copyright notice, this */ /* list of conditions and the following disclaimer. */ /* */ /* - Redistributions in binary form must reproduce the above copyright notice, this */ /* list of conditions and the following disclaimer in the documentation and/or */ /* other materials provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */ /* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */ /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ /* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */ /* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ /* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */ /* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ /* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */ /* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* */ /**************************************************************************************/ #ifndef DistanceLODEvaluator_INCLUDE_ONCE #define DistanceLODEvaluator_INCLUDE_ONCE #include <vlGraphics/Actor.hpp> namespace vl { //----------------------------------------------------------------------------- // DistanceLODEvaluator //----------------------------------------------------------------------------- /** * A LODEvaluator that computes the appropriate LOD based on the distance of an * Actor from the Camera. * * \sa * - LODEvaluator * - PixelLODEvaluator */ class DistanceLODEvaluator: public LODEvaluator { VL_INSTRUMENT_CLASS(vl::DistanceLODEvaluator, LODEvaluator) public: DistanceLODEvaluator() { VL_DEBUG_SET_OBJECT_NAME() } virtual int evaluate(Actor* actor, Camera* camera) { if (mDistanceRangeSet.empty()) return 0; vec3 center = actor->transform() ? actor->transform()->worldMatrix() * actor->lod(0)->boundingBox().center() : actor->lod(0)->boundingBox().center(); double dist = (camera->modelingMatrix().getT() - center).length(); // we assume the distances are sorted in increasing order int i=0; for(; i<(int)mDistanceRangeSet.size(); ++i) { if (dist<mDistanceRangeSet[i]) return i; } return i; // == mDistanceRangeSet.size() } const std::vector<double>& distanceRangeSet() const { return mDistanceRangeSet; } std::vector<double>& distanceRangeSet() { return mDistanceRangeSet; } protected: std::vector<double> mDistanceRangeSet; }; } #endif
48.875
156
0.468961
pasenau
ee20b682b8f25b046392f2c9b9af85d4dc7e456b
2,915
cpp
C++
get.cpp
badabum007/FTPdog
67248a106b2a5abaf3ca8d147cb5db2745edcffe
[ "MIT" ]
null
null
null
get.cpp
badabum007/FTPdog
67248a106b2a5abaf3ca8d147cb5db2745edcffe
[ "MIT" ]
null
null
null
get.cpp
badabum007/FTPdog
67248a106b2a5abaf3ca8d147cb5db2745edcffe
[ "MIT" ]
null
null
null
#include "get.hpp" #include <curl/curl.h> #include <fstream> #include <unistd.h> #include <cstdlib> #include <vector> using namespace std; get::get(string t_url, string t_name, string t_pass, CURL* t_curl, string startdir) { curl = t_curl; ftpurl = t_url; login = t_name; password = t_pass; path = startdir; } get::~get() { } size_t get::my_fwrite(void* buffer, size_t size, size_t nmemb, void* stream) { struct FtpFile* out = (struct FtpFile*)stream; if(out && !out->stream) { // open file for writing out->stream = fopen(out->filename, "wb"); if(!out->stream) return -1; // failure, can't open file to write } return fwrite(buffer, size, nmemb, out->stream); } void get::get_wd() { fstream user_wd; string temp = path + "user_working_directory", command = "pwd > " + temp; user_wd.open(temp.c_str(), ios::trunc | ios::out | ios::in); system(command.c_str()); user_wd.seekg(0); // reading path to string getline(user_wd, user_work_dir); user_wd.close(); } void get::download(string filename) { string absolute_filename = user_work_dir + "/" + filename; string fileurl = ftpurl + filename; // name to store the file as if successful struct FtpFile ftpfile = { absolute_filename.c_str(), NULL }; if(curl) { if(login != "\0" && login != "\n") { curl_easy_setopt(curl, CURLOPT_USERNAME, login.c_str()); curl_easy_setopt(curl, CURLOPT_PASSWORD, password.c_str()); } curl_easy_setopt(curl, CURLOPT_URL, fileurl.c_str()); // Define our callback to get called when there's data to be written curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_fwrite); // Set a pointer to our struct to pass to the callback curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ftpfile); curl_easy_setopt(curl, CURLOPT_DIRLISTONLY, 0L); res = curl_easy_perform(curl); if(CURLE_OK != res) { // we failed fprintf(stderr, "curl told us %d\n", res); } else { ofstream test; test.open(filename.c_str()); if(!test.is_open()) { test.close(); string temp = "touch " + filename; system(temp.c_str()); } else test.close(); } } if(ftpfile.stream) fclose(ftpfile.stream); // close the local file } void get::mainfunc() { get_wd(); // saving path to current user local directory to file cout << "Enter filenames:" << endl; vector<string> list; string filename; cin.ignore(INT_MAX,'\n'); while(true) { cin.clear(); getline(cin, filename); if(filename!="") list.push_back(filename); else break; } for(unsigned int i = 0; i < list.size(); i++) download(list[i]); }
28.578431
83
0.587993
badabum007
ee287f5ae3ab742040624493674c679caad52664
170
cpp
C++
yingying_delphi/Delphicpp_v8.4.2_Linux/src/solver/solver_fastSOR_validateInput.cpp
caixiuhong/Develop-MCCE
31df6d22b8aac9a10c1e5c7809913b63ba83d23b
[ "MIT" ]
null
null
null
yingying_delphi/Delphicpp_v8.4.2_Linux/src/solver/solver_fastSOR_validateInput.cpp
caixiuhong/Develop-MCCE
31df6d22b8aac9a10c1e5c7809913b63ba83d23b
[ "MIT" ]
36
2019-06-03T20:30:45.000Z
2020-04-17T19:17:26.000Z
yingying_delphi/Delphicpp_v8.4.2_Linux/src/solver/solver_fastSOR_validateInput.cpp
caixiuhong/Develop-MCCE
31df6d22b8aac9a10c1e5c7809913b63ba83d23b
[ "MIT" ]
6
2019-06-03T16:56:43.000Z
2020-01-09T03:32:31.000Z
/* * solver_fastSOR_validateInput.cpp * * Created on: Feb 16, 2014 * Author: chuan */ #include "solver_fastSOR.h" void CDelphiFastSOR::validateInput() { }
12.142857
37
0.664706
caixiuhong
ee2c4a08c044cded2c9bd8d6a0a2fadb397e35ba
9,547
cpp
C++
src/frontends/lean/operator_info.cpp
codyroux/lean0.1
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
[ "Apache-2.0" ]
1
2019-06-08T15:02:03.000Z
2019-06-08T15:02:03.000Z
src/frontends/lean/operator_info.cpp
codyroux/lean0.1
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
[ "Apache-2.0" ]
null
null
null
src/frontends/lean/operator_info.cpp
codyroux/lean0.1
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "util/rc.h" #include "library/io_state_stream.h" #include "frontends/lean/operator_info.h" #include "frontends/lean/frontend.h" namespace lean { /** \brief Actual implementation of operator_info */ struct operator_info::imp { void dealloc() { delete this; } MK_LEAN_RC(); fixity m_fixity; unsigned m_precedence; list<name> m_op_parts; // operator parts, > 1 only if the operator is mixfix. list<expr> m_exprs; // possible interpretations for the operator. imp(name const & op, fixity f, unsigned p): m_rc(1), m_fixity(f), m_precedence(p), m_op_parts(cons(op, list<name>())) {} imp(unsigned num_parts, name const * parts, fixity f, unsigned p): m_rc(1), m_fixity(f), m_precedence(p), m_op_parts(to_list<name const *>(parts, parts + num_parts)) { lean_assert(num_parts > 0); } imp(imp const & s): m_rc(1), m_fixity(s.m_fixity), m_precedence(s.m_precedence), m_op_parts(s.m_op_parts), m_exprs(s.m_exprs) { } bool is_eq(imp const & other) const { return m_fixity == other.m_fixity && m_precedence == other.m_precedence && m_op_parts == other.m_op_parts; } }; operator_info::operator_info(imp * p):m_ptr(p) {} operator_info::operator_info(operator_info const & info):m_ptr(info.m_ptr) { if (m_ptr) m_ptr->inc_ref(); } operator_info::operator_info(operator_info && info):m_ptr(info.m_ptr) { info.m_ptr = nullptr; } operator_info::~operator_info() { if (m_ptr) m_ptr->dec_ref(); } operator_info & operator_info::operator=(operator_info const & s) { LEAN_COPY_REF(s); } operator_info & operator_info::operator=(operator_info && s) { LEAN_MOVE_REF(s); } void operator_info::add_expr(expr const & d) { lean_assert(m_ptr); m_ptr->m_exprs = cons(d, m_ptr->m_exprs); } bool operator_info::is_overloaded() const { return m_ptr && !is_nil(m_ptr->m_exprs) && !is_nil(cdr(m_ptr->m_exprs)); } list<expr> const & operator_info::get_denotations() const { lean_assert(m_ptr); return m_ptr->m_exprs; } fixity operator_info::get_fixity() const { lean_assert(m_ptr); return m_ptr->m_fixity; } unsigned operator_info::get_precedence() const { lean_assert(m_ptr); return m_ptr->m_precedence; } name const & operator_info::get_op_name() const { lean_assert(m_ptr); return car(m_ptr->m_op_parts); } list<name> const & operator_info::get_op_name_parts() const { lean_assert(m_ptr); return m_ptr->m_op_parts; } bool operator_info::is_safe_ascii() const { auto l = get_op_name_parts(); return std::all_of(l.begin(), l.end(), [](name const & p) { return p.is_safe_ascii(); }); } operator_info operator_info::copy() const { return operator_info(new imp(*m_ptr)); } bool operator==(operator_info const & op1, operator_info const & op2) { if ((op1.m_ptr == nullptr) != (op2.m_ptr == nullptr)) return false; if (op1.m_ptr) return op1.m_ptr->is_eq(*(op2.m_ptr)); else return true; } operator_info infix(name const & op, unsigned precedence) { return operator_info(new operator_info::imp(op, fixity::Infix, precedence)); } operator_info infixr(name const & op, unsigned precedence) { return operator_info(new operator_info::imp(op, fixity::Infixr, precedence)); } operator_info infixl(name const & op, unsigned precedence) { return operator_info(new operator_info::imp(op, fixity::Infixl, precedence)); } operator_info prefix(name const & op, unsigned precedence) { return operator_info(new operator_info::imp(op, fixity::Prefix, precedence)); } operator_info postfix(name const & op, unsigned precedence) { return operator_info(new operator_info::imp(op, fixity::Postfix, precedence)); } operator_info mixfixl(unsigned num_parts, name const * parts, unsigned precedence) { lean_assert(num_parts > 1); return operator_info(new operator_info::imp(num_parts, parts, fixity::Mixfixl, precedence)); } operator_info mixfixr(unsigned num_parts, name const * parts, unsigned precedence) { lean_assert(num_parts > 1); return operator_info(new operator_info::imp(num_parts, parts, fixity::Mixfixr, precedence)); } operator_info mixfixc(unsigned num_parts, name const * parts, unsigned precedence) { lean_assert(num_parts > 1); return operator_info(new operator_info::imp(num_parts, parts, fixity::Mixfixc, precedence)); } operator_info mixfixo(unsigned num_parts, name const * parts, unsigned precedence) { lean_assert(num_parts > 1); return operator_info(new operator_info::imp(num_parts, parts, fixity::Mixfixo, precedence)); } char const * to_string(fixity f) { switch (f) { case fixity::Infix: return "infix"; case fixity::Infixl: return "infixl"; case fixity::Infixr: return "infixr"; case fixity::Prefix: return "prefix"; case fixity::Postfix: return "postfix"; case fixity::Mixfixl: return "mixfixl"; case fixity::Mixfixr: return "mixfixr"; case fixity::Mixfixc: return "mixfixc"; case fixity::Mixfixo: return "mixfixo"; } lean_unreachable(); // LCOV_EXCL_LINE } format pp(operator_info const & o) { format r; switch (o.get_fixity()) { case fixity::Infix: case fixity::Infixl: case fixity::Infixr: r = highlight_command(format(to_string(o.get_fixity()))); if (o.get_precedence() > 1) r += format{space(), format(o.get_precedence())}; r += format{space(), format(o.get_op_name())}; return r; case fixity::Prefix: case fixity::Postfix: case fixity::Mixfixl: case fixity::Mixfixr: case fixity::Mixfixc: case fixity::Mixfixo: r = highlight_command(format("notation")); if (o.get_precedence() > 1) r += format{space(), format(o.get_precedence())}; switch (o.get_fixity()) { case fixity::Prefix: r += format{space(), format(o.get_op_name()), space(), format("_")}; return r; case fixity::Postfix: r += format{space(), format("_"), space(), format(o.get_op_name())}; return r; case fixity::Mixfixl: for (auto p : o.get_op_name_parts()) r += format{space(), format(p), space(), format("_")}; return r; case fixity::Mixfixr: for (auto p : o.get_op_name_parts()) r += format{space(), format("_"), space(), format(p)}; return r; case fixity::Mixfixc: { auto parts = o.get_op_name_parts(); r += format{space(), format(head(parts))}; for (auto p : tail(parts)) r += format{space(), format("_"), space(), format(p)}; return r; } case fixity::Mixfixo: for (auto p : o.get_op_name_parts()) r += format{space(), format("_"), space(), format(p)}; r += format{space(), format("_")}; return r; default: lean_unreachable(); // LCOV_EXCL_LINE } } lean_unreachable(); // LCOV_EXCL_LINE } char const * notation_declaration::keyword() const { return to_string(m_op.get_fixity()); } void notation_declaration::write(serializer & s) const { auto parts = m_op.get_op_name_parts(); s << "Notation" << length(parts); for (auto n : parts) s << n; s << static_cast<char>(m_op.get_fixity()) << m_op.get_precedence() << m_expr; } static void read_notation(environment const & env, io_state const & ios, deserializer & d) { buffer<name> parts; unsigned num = d.read_unsigned(); for (unsigned i = 0; i < num; i++) parts.push_back(read_name(d)); fixity fx = static_cast<fixity>(d.read_char()); unsigned p = d.read_unsigned(); expr e = read_expr(d); switch (fx) { case fixity::Infix: lean_assert(parts.size() == 1); add_infix(env, ios, parts[0], p, e); return; case fixity::Infixl: lean_assert(parts.size() == 1); add_infixl(env, ios, parts[0], p, e); return; case fixity::Infixr: lean_assert(parts.size() == 1); add_infixr(env, ios, parts[0], p, e); return; case fixity::Prefix: lean_assert(parts.size() == 1); add_prefix(env, ios, parts[0], p, e); return; case fixity::Postfix: lean_assert(parts.size() == 1); add_postfix(env, ios, parts[0], p, e); return; case fixity::Mixfixl: add_mixfixl(env, ios, parts.size(), parts.data(), p, e); return; case fixity::Mixfixr: add_mixfixr(env, ios, parts.size(), parts.data(), p, e); return; case fixity::Mixfixc: add_mixfixc(env, ios, parts.size(), parts.data(), p, e); return; case fixity::Mixfixo: add_mixfixo(env, ios, parts.size(), parts.data(), p, e); return; } } static object_cell::register_deserializer_fn notation_ds("Notation", read_notation); std::ostream & operator<<(std::ostream & out, operator_info const & o) { out << pp(o); return out; } io_state_stream const & operator<<(io_state_stream const & out, operator_info const & o) { out.get_stream() << mk_pair(pp(o), out.get_options()); return out; } char const * alias_declaration::keyword() const { return "alias"; } void alias_declaration::write(serializer & s) const { s << "alias" << m_name << m_expr; } static void read_alias(environment const & env, io_state const &, deserializer & d) { name n = read_name(d); expr e = read_expr(d); add_alias(env, n, e); } static object_cell::register_deserializer_fn add_alias_ds("alias", read_alias); }
41.150862
124
0.658531
codyroux
0c51d2a1d63b908814608fbc235f72dc6ee76ca5
19,081
cpp
C++
controller-gui/src/main.cpp
abathur8bit/chessbox
6166dd9887d89c70289e3965af58aa8bbf8e23a8
[ "Apache-2.0" ]
2
2021-01-02T07:07:26.000Z
2021-01-13T00:18:18.000Z
controller-gui/src/main.cpp
abathur8bit/chessbox
6166dd9887d89c70289e3965af58aa8bbf8e23a8
[ "Apache-2.0" ]
null
null
null
controller-gui/src/main.cpp
abathur8bit/chessbox
6166dd9887d89c70289e3965af58aa8bbf8e23a8
[ "Apache-2.0" ]
1
2021-01-13T00:18:25.000Z
2021-01-13T00:18:25.000Z
/* ***************************************************************************** * Created by Lee Patterson 12/19/2020 * * Copyright 2019 Lee Patterson <https://github.com/abathur8bit> * * You may use and modify at will. Please credit me in the source. * * 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. * ******************************************************************************/ //-e "C:\Program Files\tarrasch-v3.12b-g\Engines\stockfish_8_x64.exe" -h 192.168.1.54 //-e "C:/Program Files (x86)/ShredderChess/Deep Shredder 13/EngineDeepShredder13UCIx64.exe" -h 192.168.1.54 #include <stdio.h> #include <string.h> #include <algorithm> #include <list> #include <stdlib.h> #include <SDL.h> #include <time.h> #include <SDL_image.h> #include "Sprite.h" #include "Button.h" #include "Board.h" #include "UIGroup.h" #include "thc.h" #include "Label.h" #include "MovesPanel.h" #include "Connector.h" #include "chessaction.hpp" #include "json.hpp" #include "ControllerGUI.h" #include "Dialog.h" #include "TextField.h" #include "FontManager.h" using namespace std; using namespace nlohmann; //trying this char buffer[1024]; const int SCREEN_WIDTH = 480; const int SCREEN_HEIGHT = 800; int counter=0; //#define NUM_MOVES 16 SDL_Window* window=NULL; SDL_Renderer* renderer=NULL; bool invalidated = true; list<Component*> uistuff; UIGroup buttonGroup("buttons",0,670,280,130); //UIGroup movesGroup("moves",480-200,480,200,800-320); char host[80]="127.0.0.1"; unsigned short port=9999; Connector connector; bool attemptConnect=true; bool running=false; Board board(0,0,480,480); MovesPanel* movesPanel; Sprite logo("logo"); Sprite movesBG("moves-bg1"); Label* blackClockText; Label* whiteClockText; int gameMovesIndex=0; const char* gameMoves[] = { "d4","d5", "c4","c6", "Nf3","Nf6", "Nc3","e6", "Bg5","h6", "Bxf6","Qxf6", "e3","Nd7", "Rc1","g6", "Be2","Bg7", "cxd5","exd5", "b4","a6", "a4","O-O", "b5","axb5", "axb5","Qd6", "O-O","Nb6", "Qb3","Rb8", "Nd1","Bf5", "Nb2","Rfc8", "Nd3","Bxd3", "Qxd3","c5", "dxc5","Rxc5", "h4","Na4", "h5","Rbc8", "Rxc5","Nxc5", "Qc2","gxh5", "Nd4","Qg6", "Nf5","Bf8", "Rd1","Qe6", "Rc1","Nb3", "Qxc8","Nxc1", "Qxc1","Qxf5", "Qc7","Qb1+", "Bf1","d4", "exd4","Qd1", "Qe5","Bg7", "Qe8+","Bf8", "Qd8","Kg7", "Qd5","b6", "Qe5+","Kg8", "Qf6","Bg7", "Qxb6","Bxd4", "Qxh6","Qg4", "Qd6","Qd1", "Qd8+","Kh7", "Qc7","Kg7", "b6","Qg4", "b7","Qh4", "g3","Qf6", "Qc2","Qe5", "Qd3","Ba7", "Qf3","Qf6", "Qe2","Qc3", "Kh2","Qd4", "Qf3","Bb8", "Kh3","Bc7", "Be2","Bb8", "Bd1","f5", "Be2","f4", "Qxh5","Qxf2", "Qg5+","Kf7" }; ChessAction* parseJson(const char* s) { json j = json::parse(s); ChessAction* c = new ChessAction(j); return c; } void validate() { invalidated=false; } void invalidate() { invalidated=true; } bool isInvalidated() { return invalidated; } void processMouseEvent(SDL_Event* event) { Component* result = buttonGroup.mouseEvent(event); if(result) { // printf("Event for %s\n",result->id()); if(event->type == SDL_MOUSEBUTTONUP) { if (!strcmp(result->id(), "power")) { printf("Connecting to controller at %s:%d\n", host, port); connector.connect(host, port); printf("Connected to controller\n"); Button *b = static_cast<Button *>(result); b->setChecked(true); } else if (!strcmp(result->id(), "settings")) { Dialog message("Demo","Fast bunnies",DIALOG_TYPE_OK_CANCEL); if(message.show(renderer)==DIALOG_SELECTED_OKAY) { printf("user selected okay\n"); } else { printf("user selected cancel\n"); } } else if (!strcmp(result->id(), "inspect")) { } else if (!strcmp(result->id(), "fwd")) { thc::Move mv; mv.NaturalIn(board.rules(), gameMoves[gameMovesIndex++]); movesPanel->add(mv); } else if (!strcmp(result->id(), "back")) { const char *fen = "rnbqkb1r/ppp1pppp/5n2/3p4/3P1B2/4P3/PPP2PPP/RN1QKBNR b KQkq - 0 3"; board.Forsyth(fen); } else if (!strcmp(result->id(), "hint")) { snprintf(buffer,sizeof(buffer),"hint %d",++counter); movesPanel->add(buffer); int i = 0; Button *b = static_cast<Button *>(buttonGroup.find("hint")); if (b) { b->setChecked(!b->isChecked()); board.highlightSquare(i, !board.isHighlighted(i)); i++; board.highlightSquare(i, !board.isHighlighted(i)); } } } invalidate(); } //was processing the components here, then using a lamba. Will see about using a lambda again later. // for(list<Component*>::iterator it=buttonGroup.begin(); it != buttonGroup.end(); ++it) { // Button* b = static_cast<Button*>(*it); // b->mouseEvent(event,[](Button* b){printf("button %s was clicked size=%dx%d\n",b->id(),b->rect()->w,b->rect()->h);}); //called method signature is //bool Button::mouseEvent(SDL_Event* event,void(*f)(Button* b)); // } } void coolSpot(bool fullscreen) { SDL_Rect r; SDL_Rect r2; SDL_Point center; Uint32 timer=0; // SDL_EnableScreenSaver(); if (SDL_Init(SDL_INIT_VIDEO) < 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s", SDL_GetError()); return; } // SDL_RendererInfo info; // int numRenderDrivers = SDL_GetNumRenderDrivers(); // printf("Number of render driver: %d\n", numRenderDrivers); // for(int i=0; i < numRenderDrivers; i++) // { // if ( SDL_GetRenderDriverInfo(i,&info) == 0 ) // { // printf("%s\n",info.name); // } // } // const char* drivername="RPI"; // if (SDL_VideoInit(drivername) != 0) { // printf("unable to init video %s\n",SDL_GetError()); // } // int err=SDL_CreateWindowAndRenderer(480,800,FULL_SCREEN_MODE,&m_window,&m_renderer); // if(err!=0) printf("SDL_CreateWindowAndRenderer error %s\n",SDL_GetError()); window = SDL_CreateWindow( "Chessbox", // SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED, 300,100, SCREEN_WIDTH, SCREEN_HEIGHT, fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP:SDL_WINDOW_RESIZABLE); SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); FontManager::instance()->add("small","Inconsolata-Medium.ttf",10); FontManager::instance()->add("normal","Inconsolata-Medium.ttf",16); FontManager::instance()->add("large","Inconsolata-Medium.ttf",26); r.w = 100; r.h = 50; r2.w = r.w; r2.h = r.h; center.x = r.w / 2; center.y = r.h / 2; renderer = SDL_CreateRenderer(window, -1, 0); if(!renderer) { printf("rederer error %s\n",SDL_GetError()); } SDL_SetRenderDrawColor(renderer, 128, 0, 0, 255); movesPanel=new MovesPanel("moves",480-200,480,200,800-320,board.rules()); whiteClockText=new Label("whiteclock", 0, 480, 140, 25); whiteClockText->setFont(FontManager::instance()->font("large")); blackClockText=new Label("blackclock", 140, 480, 140, 25); blackClockText->setFont(FontManager::instance()->font("large")); logo.load(renderer,"assets/logo-sm.png",1,82+105/2,518+130/2); uistuff.push_back(&logo); movesBG.load(renderer,"assets/moves-bg1.png",1,480-100,480+320/2); uistuff.push_back(&movesBG); uistuff.push_back(whiteClockText); uistuff.push_back(blackClockText); SDL_Color whiteColor = {255,255,255}; blackClockText->setColor(whiteColor); whiteClockText->setColor(whiteColor); whiteClockText->setText(" W 1:00:00"); blackClockText->setText(" B 1:00:00"); int ww=60,hh=60,xx=0,yy=0; AnimButton settingsButton("settings",renderer,"assets/button-gear.png",1,xx,yy); xx+=ww+10; AnimButton quitButton("power",renderer,"assets/button_power.png",1,xx,yy); xx+=ww+10; TextButton hintButton("hint","Hint",xx,yy,ww,hh); xx+=ww+10; TextButton inspectButton("inspect","Inspect",xx,yy,ww,hh); xx+=ww+10; xx=0; yy+=70; AnimButton fastbackButton("fastback",renderer,"assets/button-fastback.png",1,xx,yy); xx+=ww+10; AnimButton backButton("back",renderer,"assets/button-back.png",1,xx,yy); xx+=ww+10; AnimButton fwdButton("fwd",renderer,"assets/button-fwd.png",1,xx,yy); xx+=ww+10; AnimButton fastfwdButton("fastfwd",renderer,"assets/button-fastfwd.png",1,xx,yy); xx+=ww+10; board.loadPieces(renderer,"merida_new"); buttonGroup.add(&settingsButton); buttonGroup.add(&quitButton); buttonGroup.add(&hintButton); buttonGroup.add(&inspectButton); buttonGroup.add(&fastbackButton); buttonGroup.add(&backButton); buttonGroup.add(&fwdButton); buttonGroup.add(&fastfwdButton); TextField tf("textfield",10,10,460,30); tf.setText("your name here"); uistuff.push_back(&tf); running=true; while (running) { SDL_Event event; if (SDL_PollEvent(&event)) { // printf("got event type %04X\n", event.type); switch (event.type) { case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: case SDL_MOUSEMOTION: case SDL_MOUSEWHEEL: processMouseEvent(&event); break; case SDL_QUIT: running = false; break; case SDL_WINDOWEVENT: // printf("had a m_window event!!!\n"); break; case SDL_KEYDOWN: if(SDL_SCANCODE_ESCAPE==event.key.keysym.scancode) running = false; break; default: break; } } if(isInvalidated()) { validate(); SDL_SetRenderDrawColor(renderer, 191, 37, 0, SDL_ALPHA_OPAQUE); SDL_RenderClear(renderer); board.draw(renderer); for (list<Component *>::iterator it = uistuff.begin(); it != uistuff.end(); it++) { (*it)->draw(renderer); } buttonGroup.draw(renderer); movesPanel->draw(renderer); SDL_RenderPresent(renderer); } Uint32 ticks = SDL_GetTicks(); for (list<Component *>::iterator it = uistuff.begin(); it != uistuff.end(); it++) { (*it)->update(ticks); } buttonGroup.update(ticks); board.update(ticks); movesPanel->update(ticks); if(ticks>timer) { invalidate(); timer=ticks+100; } #if 1 // if(!connector.isConnected() && attemptConnect) { // attemptConnect=false; // try { // printf("Connecting to controller at %s:%d\n",host,port); // connector.connect(host, port); // printf("Connected to controller\n"); // quitButton.setChecked(true); // } catch(SocketInstanceException& e) { // printf("Not able to connect to %s:%d\n",host,port); // } // } if(connector.isConnected()) { char buffer[1024]; if(connector.readline(buffer, sizeof(buffer))) { printf("Read from socket: %s\n",buffer); if(buffer[0]=='{') { json j = json::parse(buffer); if(j.contains("action")) { string action = j["action"]; if(!action.compare("pieceUp")) { string square=j["square"]; board.highlightSquare(board.toIndex(square.c_str()),true); invalidate(); } else if(!action.compare("pieceDown")) { string square=j["square"]; board.highlightSquare(board.toIndex(square.c_str()),false); invalidate(); } else if(!action.compare("move")) { ChessAction* a=new ChessAction(j); ChessMove m = a->move(0); printf("Move from=%s to=%s lan=%s\n",m.from(),m.to(),m.lan()); board.playMove(m.lan()); invalidate(); } else if(!action.compare("setposition")) { string fen=j["fen"]; board.Forsyth(fen.c_str()); board.rules()->display_position(); movesPanel->clear(); invalidate(); } } } if(buffer[0]=='W') { connector.send("{\"action\":\"ping\"}"); connector.send("{\"action\":\"fen\"}"); } } } #endif } SDL_DestroyWindow(window); SDL_DestroyRenderer(renderer); TTF_Quit(); SDL_Quit(); } //Just some test stuff void foo(void(*f)()) { printf("calling f\n"); f(); } class A { public: void foo() { bar(); } virtual void bar() { printf("A foobar\n"); } virtual void cat() { printf("A cat\n"); } }; class B : public A { public: virtual void bar() { printf("B bar\n"); } virtual void cat() { printf("B cat\n"); } }; class Greet : public B { public: string m_name; Greet(string name) : m_name(name) {} virtual void bar() { printf("Hello %s\n",m_name.c_str()); } }; void svgtest(const char* filename,bool fullscreen) { SDL_Window* m_window; SDL_Renderer* m_renderer; bool m_running; if (SDL_Init(SDL_INIT_VIDEO) < 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s", SDL_GetError()); return; } m_window = SDL_CreateWindow( "Chessbox", 300,100, // SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP:SDL_WINDOW_RESIZABLE); SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); m_renderer = SDL_CreateRenderer(m_window, -1, 0); if(!m_renderer) { printf("m_renderer error %s\n",SDL_GetError()); } SDL_RWops *src = SDL_RWFromFile(filename, "rb"); SDL_Surface * surface = IMG_LoadSVG_RW(src); SDL_Texture* texture = SDL_CreateTextureFromSurface(m_renderer,surface); SDL_Rect srcrect={0,0,0,0}; SDL_QueryTexture(texture, NULL, NULL, &srcrect.w, &srcrect.h); SDL_Rect destrect={0,0,srcrect.w,srcrect.h}; bool running=true; while(running) { SDL_Event event; if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: running = false; break; case SDL_WINDOWEVENT: break; case SDL_KEYDOWN: if(SDL_SCANCODE_ESCAPE==event.key.keysym.scancode) running = false; break; default: break; } } SDL_SetRenderDrawColor(m_renderer, 128, 0, 0, 255); SDL_RenderClear(m_renderer); SDL_RenderCopyEx(m_renderer,texture, &srcrect, &destrect, 0, 0, SDL_FLIP_NONE); SDL_RenderPresent(m_renderer); } SDL_DestroyWindow(m_window); SDL_DestroyRenderer(m_renderer); SDL_Quit(); } void add(MovesPanel& m,const char* s) { m.add(s); } void show(MovesPanel& m) { for(int i=0; i<17; i++) { printf("%02d %s\n",i,m.text(i)); } } void scrolltest() { BoardRules rules; MovesPanel m("moves",0,0,100,100,&rules); int i; show(m); for(int i=0; i<20; i++) { snprintf(buffer,sizeof(buffer),"add %d",i); printf("%s (enter)\n",buffer); getchar(); add(m,buffer); show(m); } } int main(int argc, char* argv[]) { printf("You may need to run 'export SDL_VIDEODRIVER=rpi'\n"); #if 1 int numdrivers, i, working; const char* drivername; if (SDL_Init(0) != 0) { printf("Error initializing SDL: %s\n", SDL_GetError()); return 1; } atexit(SDL_Quit); numdrivers = SDL_GetNumVideoDrivers(); working = 0; for (i = 0; i < numdrivers; ++i) { drivername = SDL_GetVideoDriver(i); if (SDL_VideoInit(drivername) == 0) { SDL_VideoQuit(); ++working; printf("Driver %s works.\n", drivername); } else { printf("Driver %s doesn't work.\n", drivername); } } printf("\n%d video drivers total (%d work)\n", numdrivers, working); #endif #if 1 [](){}(); //cool lambda that does nothing, but is valid and C++ compiles bool fullscreen=false; #ifdef WIN32 string pgn="/t/game.pgn"; string engine="C:/Program Files (x86)/ShredderChess/Deep Shredder 13/EngineDeepShredder13UCIx64.exe"; #else string pgn="/home/pi/game.pgn"; string engine="engine/stockfish8"; #endif for(int i=1; i<argc; i++) { if(!strcmp("-f",argv[i])) { fullscreen=true; } else if(!strcmp("-h",argv[i]) && i+1 <= argc) { strncpy(host,argv[++i],sizeof(host)); NULL_TERMINATE(host, sizeof(host)); } else if(!strcmp(argv[i],"-e")) { engine=argv[++i]; } else if(!strcmp("-p",argv[i])) { pgn=argv[++i]; } } // scrolltest(); // coolSpot(fullscreen); ControllerGUI gui(fullscreen,host,port,engine.c_str(),pgn.c_str()); gui.startGame(); #endif #if 0 // svgtest("assets/chessbox-box.svg",false); int err=system(NULL); printf("system returned %d\n",err); #endif return 0; } //todo lee settings should allow for piece choosing
31.026016
221
0.543997
abathur8bit
0c524a156ce45e1050bf490928af9185b4a1197a
1,096
hpp
C++
SDK/ARKSurvivalEvolved_FeedingTrough_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_FeedingTrough_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_FeedingTrough_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_FeedingTrough_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass FeedingTrough.FeedingTrough_C // 0x000C (0x0EC0 - 0x0EB4) class AFeedingTrough_C : public AFeedingTroughBaseBP_C { public: unsigned char UnknownData00[0x4]; // 0x0EB4(0x0004) MISSED OFFSET class UPrimalInventoryBP_FeedingTrough_C* PrimalInventoryBP_FeedingTrough_C1; // 0x0EB8(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass FeedingTrough.FeedingTrough_C"); return ptr; } void UserConstructionScript(); void ExecuteUbergraph_FeedingTrough(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
26.095238
179
0.603102
2bite
0c5579e83da9607ae2c95691f28f89ca1f057427
5,490
cpp
C++
src/qt/qtbase/examples/qpa/windows/window.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
src/qt/qtbase/examples/qpa/windows/window.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/examples/qpa/windows/window.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Qt Company Ltd 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." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "window.h" #include <private/qguiapplication_p.h> #include <QBackingStore> #include <QPainter> static int colorIndexId = 0; QColor colorTable[] = { QColor("#f09f8f"), QColor("#a2bff2"), QColor("#c0ef8f") }; Window::Window(QScreen *screen) : QWindow(screen) , m_backgroundColorIndex(colorIndexId++) { initialize(); } Window::Window(QWindow *parent) : QWindow(parent) , m_backgroundColorIndex(colorIndexId++) { initialize(); } void Window::initialize() { if (parent()) setGeometry(QRect(160, 120, 320, 240)); else { setFlags(flags() | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint); const QSize baseSize = QSize(640, 480); setGeometry(QRect(geometry().topLeft(), baseSize)); setSizeIncrement(QSize(10, 10)); setBaseSize(baseSize); setMinimumSize(QSize(240, 160)); setMaximumSize(QSize(800, 600)); } create(); m_backingStore = new QBackingStore(this); m_image = QImage(geometry().size(), QImage::Format_RGB32); m_image.fill(colorTable[m_backgroundColorIndex % (sizeof(colorTable) / sizeof(colorTable[0]))].rgba()); m_lastPos = QPoint(-1, -1); m_renderTimer = 0; } void Window::mousePressEvent(QMouseEvent *event) { m_lastPos = event->pos(); } void Window::mouseMoveEvent(QMouseEvent *event) { if (m_lastPos != QPoint(-1, -1)) { QPainter p(&m_image); p.setRenderHint(QPainter::Antialiasing); p.drawLine(m_lastPos, event->pos()); m_lastPos = event->pos(); scheduleRender(); } } void Window::mouseReleaseEvent(QMouseEvent *event) { if (m_lastPos != QPoint(-1, -1)) { QPainter p(&m_image); p.setRenderHint(QPainter::Antialiasing); p.drawLine(m_lastPos, event->pos()); m_lastPos = QPoint(-1, -1); scheduleRender(); } } void Window::exposeEvent(QExposeEvent *) { scheduleRender(); } void Window::resizeEvent(QResizeEvent *) { QImage old = m_image; int width = qMax(geometry().width(), old.width()); int height = qMax(geometry().height(), old.height()); if (width > old.width() || height > old.height()) { m_image = QImage(width, height, QImage::Format_RGB32); m_image.fill(colorTable[(m_backgroundColorIndex) % (sizeof(colorTable) / sizeof(colorTable[0]))].rgba()); QPainter p(&m_image); p.drawImage(0, 0, old); } scheduleRender(); } void Window::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Backspace: m_text.chop(1); break; case Qt::Key_Enter: case Qt::Key_Return: m_text.append('\n'); break; default: m_text.append(event->text()); break; } scheduleRender(); } void Window::scheduleRender() { if (!m_renderTimer) m_renderTimer = startTimer(1); } void Window::timerEvent(QTimerEvent *) { if (isExposed()) render(); killTimer(m_renderTimer); m_renderTimer = 0; } void Window::render() { QRect rect(QPoint(), geometry().size()); m_backingStore->resize(rect.size()); m_backingStore->beginPaint(rect); QPaintDevice *device = m_backingStore->paintDevice(); QPainter p(device); p.drawImage(0, 0, m_image); QFont font; font.setPixelSize(32); p.setFont(font); p.drawText(rect, 0, m_text); m_backingStore->endPaint(); m_backingStore->flush(rect); }
27.178218
113
0.645902
power-electro
0c5657582846cb797ddcaa56ac88e7b01bed3456
5,256
cpp
C++
src/propagation.cpp
cgilmour/dd-opentracing-cpp
c83c6a5dc72029d13ab0d64a7222fb139a1889f1
[ "Apache-2.0" ]
null
null
null
src/propagation.cpp
cgilmour/dd-opentracing-cpp
c83c6a5dc72029d13ab0d64a7222fb139a1889f1
[ "Apache-2.0" ]
null
null
null
src/propagation.cpp
cgilmour/dd-opentracing-cpp
c83c6a5dc72029d13ab0d64a7222fb139a1889f1
[ "Apache-2.0" ]
null
null
null
#include "propagation.h" #include <algorithm> namespace ot = opentracing; namespace datadog { namespace opentracing { namespace { // Header names for trace data. const std::string trace_id_header = "x-datadog-trace-id"; const std::string parent_id_header = "x-datadog-parent-id"; // Header name prefix for OpenTracing baggage. Should be "ot-baggage-" to support OpenTracing // interop. const ot::string_view baggage_prefix = "ot-baggage-"; // Does what it says on the tin. Just looks at each char, so don't try and use this on // unicode strings, only used for comparing HTTP header names. // Rolled my own because I don't want to import all of libboost for a couple of functions! bool equals_ignore_case(const std::string &a, const std::string &b) { return std::equal(a.begin(), a.end(), b.begin(), b.end(), [](char a, char b) { return tolower(a) == tolower(b); }); } // Checks to see if the given string has the given prefix. bool has_prefix(const std::string &str, const std::string &prefix) { if (str.size() < prefix.size()) { return false; } auto result = std::mismatch(prefix.begin(), prefix.end(), str.begin()); return result.first == prefix.end(); } } // namespace SpanContext::SpanContext(uint64_t id, uint64_t trace_id, std::unordered_map<std::string, std::string> &&baggage) : id_(id), trace_id_(trace_id), baggage_(std::move(baggage)) {} SpanContext::SpanContext(SpanContext &&other) : id_(other.id_), trace_id_(other.trace_id_), baggage_(std::move(other.baggage_)) {} SpanContext &SpanContext::operator=(SpanContext &&other) { std::lock_guard<std::mutex> lock{mutex_}; id_ = other.id_; trace_id_ = other.trace_id_; baggage_ = std::move(other.baggage_); return *this; } void SpanContext::ForeachBaggageItem( std::function<bool(const std::string &, const std::string &)> f) const { for (const auto &baggage_item : baggage_) { if (!f(baggage_item.first, baggage_item.second)) { return; } } } uint64_t SpanContext::id() const { // Not locked, since id_ never modified. return id_; } uint64_t SpanContext::trace_id() const { // Not locked, since trace_id_ never modified. return trace_id_; } void SpanContext::setBaggageItem(ot::string_view key, ot::string_view value) noexcept try { std::lock_guard<std::mutex> lock{mutex_}; baggage_.emplace(key, value); } catch (const std::bad_alloc &) { } std::string SpanContext::baggageItem(ot::string_view key) const { std::lock_guard<std::mutex> lock{mutex_}; auto lookup = baggage_.find(key); if (lookup != baggage_.end()) { return lookup->second; } return {}; } SpanContext SpanContext::withId(uint64_t id) const { std::lock_guard<std::mutex> lock{mutex_}; auto baggage = baggage_; // (Shallow) copy baggage. return std::move(SpanContext{id, trace_id_, std::move(baggage)}); } ot::expected<void> SpanContext::serialize(const ot::TextMapWriter &writer) const { std::lock_guard<std::mutex> lock{mutex_}; auto result = writer.Set(trace_id_header, std::to_string(trace_id_)); if (!result) { return result; } // Yes, "id" does go to "parent id" since this is the point where subsequent Spans getting this // context become children. result = writer.Set(parent_id_header, std::to_string(id_)); if (!result) { return result; } for (auto baggage_item : baggage_) { std::string key = std::string(baggage_prefix) + baggage_item.first; result = writer.Set(key, baggage_item.second); if (!result) { return result; } } return result; } ot::expected<std::unique_ptr<ot::SpanContext>> SpanContext::deserialize( const ot::TextMapReader &reader) try { uint64_t trace_id, parent_id; bool trace_id_set = false; bool parent_id_set = false; std::unordered_map<std::string, std::string> baggage; auto result = reader.ForeachKey([&](ot::string_view key, ot::string_view value) -> ot::expected<void> { try { if (equals_ignore_case(key, trace_id_header)) { trace_id = std::stoull(value); trace_id_set = true; } else if (equals_ignore_case(key, parent_id_header)) { parent_id = std::stoull(value); parent_id_set = true; } else if (has_prefix(key, baggage_prefix)) { baggage.emplace(std::string{std::begin(key) + baggage_prefix.size(), std::end(key)}, value); } } catch (const std::invalid_argument &ia) { return ot::make_unexpected(ot::span_context_corrupted_error); } catch (const std::out_of_range &oor) { return ot::make_unexpected(ot::span_context_corrupted_error); } return {}; }); if (!result) { // "if unexpected", hence "{}" from above is fine. return ot::make_unexpected(result.error()); } if (!trace_id_set || !parent_id_set) { return ot::make_unexpected(ot::span_context_corrupted_error); } return std::move( std::unique_ptr<ot::SpanContext>{new SpanContext{parent_id, trace_id, std::move(baggage)}}); } catch (const std::bad_alloc &) { return ot::make_unexpected(std::make_error_code(std::errc::not_enough_memory)); } } // namespace opentracing } // namespace datadog
33.692308
98
0.671994
cgilmour
0c574bb7a0f52371cf40a35c5e8bba3f85c880ab
1,426
cpp
C++
Documentation/Examples/Matrices/SparseMatrix/SparseMatrixViewExample_wrapCSR.cpp
grinisrit/tnl-dev
4403b2dca895e2c32636395d6f1c1210c7afcefd
[ "MIT" ]
null
null
null
Documentation/Examples/Matrices/SparseMatrix/SparseMatrixViewExample_wrapCSR.cpp
grinisrit/tnl-dev
4403b2dca895e2c32636395d6f1c1210c7afcefd
[ "MIT" ]
null
null
null
Documentation/Examples/Matrices/SparseMatrix/SparseMatrixViewExample_wrapCSR.cpp
grinisrit/tnl-dev
4403b2dca895e2c32636395d6f1c1210c7afcefd
[ "MIT" ]
null
null
null
#include <iostream> #include <TNL/Algorithms/ParallelFor.h> #include <TNL/Matrices/DenseMatrix.h> #include <TNL/Matrices/MatrixWrapping.h> #include <TNL/Devices/Host.h> #include <TNL/Devices/Cuda.h> template< typename Device > void wrapMatrixView() { /*** * Encode the following matrix to CSR format... * * / 1 2 0 0 \. * | 0 6 0 0 | * | 9 0 0 0 | * \ 0 0 15 16 / */ const int rows( 4 ), columns( 4 ); TNL::Containers::Vector< double, Device > valuesVector { 1, 2, 6, 9, 15, 16 }; TNL::Containers::Vector< int, Device > columnIndexesVector { 0, 1, 1, 0, 2, 3 }; TNL::Containers::Vector< int, Device > rowPointersVector { 0, 2, 3, 4, 6 }; double* values = valuesVector.getData(); int* columnIndexes = columnIndexesVector.getData(); int* rowPointers = rowPointersVector.getData(); /*** * Wrap the arrays `rowPointers, `values` and `columnIndexes` to sparse matrix view */ auto matrix = TNL::Matrices::wrapCSRMatrix< Device >( rows, columns, rowPointers, values, columnIndexes ); std::cout << "Matrix reads as: " << std::endl << matrix << std::endl; } int main( int argc, char* argv[] ) { std::cout << "Wraping matrix view on host: " << std::endl; wrapMatrixView< TNL::Devices::Host >(); #ifdef HAVE_CUDA std::cout << "Wraping matrix view on CUDA device: " << std::endl; wrapMatrixView< TNL::Devices::Cuda >(); #endif }
31
109
0.62763
grinisrit
0c5b8a12c288cd2d0fd22368b928cebf0c476b3a
4,213
cpp
C++
owGameWMO/WMO_PortalsController.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
null
null
null
owGameWMO/WMO_PortalsController.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
null
null
null
owGameWMO/WMO_PortalsController.cpp
adan830/OpenWow
9b6e9c248bd185b1677fe616d2a3a81a35ca8894
[ "Apache-2.0" ]
1
2020-05-11T13:32:49.000Z
2020-05-11T13:32:49.000Z
#include "stdafx.h" // Include #include "WMO.h" #include "WMO_Base_Instance.h" // General #include "WMO_PortalsController.h" // Additional #include "WMO_Group_Instance.h" CWMO_PortalsController::CWMO_PortalsController(const WMO* _parentWMO) : m_ParentWMO(_parentWMO) { for (auto& it : m_ParentWMO->m_PortalReferences) { CWMO_Part_Portal* portal = m_ParentWMO->m_Portals[it.portalIndex]; WMO_Group* group = m_ParentWMO->m_Groups[it.groupIndex]; if (it.groupIndex == group->m_GroupIndex) { group->m_Portals.push_back(portal); } else { fail1(); } portal->setGroup(it.groupIndex, it.side); } } void CWMO_PortalsController::GetPolyFrustum(const vec3* poly, uint32 num_verts, Frustum* _frustum, vec3 eye, bool _isPositive) { assert1(_frustum != nullptr); Plane _portalPlanes[15]; assert1(num_verts < 15); for (uint32 i = 0; i < num_verts; i++) { vec3 v1 = poly[i]; vec3 v2 = poly[(i + 1) % num_verts]; if (_isPositive) { _portalPlanes[i] = Plane(eye, v1, v2); } else { _portalPlanes[i] = Plane(eye, v2, v1); } } _frustum->buildCustomFrustrum(_portalPlanes, num_verts); } void CWMO_PortalsController::Update(CWMO_Base_Instance* _localContr, cvec3 _InvWorldCamera) { // Reset all flags for (auto& group : _localContr->getGroupInstances()) { group->m_PortalsVis = false; group->m_Calculated = false; for (auto& doodad : group->getDoodadsInstances()) { if (doodad) { doodad->setPortalVisibility(false); } } } bool insideIndoor = false; if (m_ParentWMO->getBounds().isPointInside(_InvWorldCamera)) { for (auto& group : _localContr->getGroupInstances()) { if (!(group->getBounds().isPointInside(_Render->getCamera()->Position))) { continue; } if (!group->getObject()->m_Header.flags.HAS_COLLISION) { continue; } if (group->getObject()->m_Header.flags.IS_OUTDOOR) { continue; } bool recurResult = Recur(_localContr, group.operator->(), _InvWorldCamera, _Render->getCamera()->getFrustum(), true); if (!recurResult) { continue; } if (group->getObject()->m_Header.flags.IS_INDOOR) { insideIndoor = true; } } } //assert1(insideOneAtLeast || !(m_ParentWMO->m_OutdoorGroups.empty())); // If we outside WMO, then get outdorr group //if (!insideIndoor) { for (auto& ogr : _localContr->getGroupOutdoorInstances()) { Recur(_localContr, ogr.operator->(), _InvWorldCamera, _Render->getCamera()->getFrustum(), true); } } } bool CWMO_PortalsController::Recur(CWMO_Base_Instance* _localContr, CWMO_Group_Instance* _group, cvec3 _InvWorldCamera, const Frustum& _frustum, bool _isFirstIteration) { if (_group == nullptr || _group->m_Calculated) { return false; } if (_Render->getCamera()->getFrustum().cullBox(_group->getBounds())) { return false; } // Set visible for current _group->m_PortalsVis = true; _group->m_Calculated = true; for (auto& doodad : _group->getDoodadsInstances()) { if (doodad && (_isFirstIteration || !_frustum.cullBox(doodad->getBounds()))) { doodad->setPortalVisibility(true); } } for (auto& p : _group->getObject()->m_Portals) { // If we don't see portal // TODO: Don't use it on first step if (_Render->getCamera()->getFrustum().cullPoly(_localContr->getVerts() + p->getStartVertex(), p->getCount())) { continue; } // And we don't see portal from other portal if (!p->IsVisible(_localContr, _frustum.getPlanes(), _frustum.getPlanesCnt())) { continue; } bool isPositive = p->IsPositive(_InvWorldCamera); // Build camera-to-poratl frustum Frustum portalFrustum; GetPolyFrustum ( _localContr->getVerts() + p->getStartVertex(), p->getCount(), &portalFrustum, _Render->getCamera()->Position, isPositive ); // Find attached to portal group CWMO_Group_Instance* groupInstance = nullptr; int32 groupIndex = isPositive ? p->getGrInner() : p->getGrOuter(); if (groupIndex >= 0 && groupIndex < _localContr->getGroupInstances().size()) { groupInstance = _localContr->getGroupInstances()[groupIndex].operator->(); } Recur ( _localContr, groupInstance, _InvWorldCamera, portalFrustum, false ); } return true; }
22.173684
168
0.682886
adan830
0c5f006f2cf1a2fcfc16d43162a30ba4c5900f13
694
cpp
C++
PATA1050.cpp
Geeks-Z/PAT-Advanced-Level-Practice
6b25d07ae602310215e46c951638b93080b382bf
[ "MIT" ]
null
null
null
PATA1050.cpp
Geeks-Z/PAT-Advanced-Level-Practice
6b25d07ae602310215e46c951638b93080b382bf
[ "MIT" ]
null
null
null
PATA1050.cpp
Geeks-Z/PAT-Advanced-Level-Practice
6b25d07ae602310215e46c951638b93080b382bf
[ "MIT" ]
null
null
null
/* * @Descripttion: https://blog.csdn.net/DayDream_x/article/details/104362662/ * @version: 1.0 * @Author: Geeks_Z * @Date: 2021-05-31 17:07:22 * @LastEditors: Geeks_Z * @LastEditTime: 2021-05-31 17:07:44 */ //⽤cha[256]数组变量标记str1出现过的字符为true,str2出现过的字符为false, //输出str1的时候根据cha[str1[i]]是否为true,如果是true就输出 #include <iostream> #include <string> using namespace std; bool cha[256]; int main() { string s1, s2; getline(cin, s1); getline(cin, s2); for (int i = 0; i < s1.size(); i++) { cha[s1[i]] = true; } for (int i = 0; i < s2.size(); i++) { cha[s2[i]] = false; } for (int i = 0; i < s1.size(); i++) { if (cha[s1[i]]) cout << s1[i]; } return 0; }
19.828571
77
0.592219
Geeks-Z
0c609bf3cdcfbe883fa7763c385768483d140a50
570
cpp
C++
codes/cpp/cplusplus-codesnippet/src/templates/example_template_valarray.cpp
zhoujiagen/learning-system-programming
2a18e9f8558433708837ba4bd0fae5d7c11bf110
[ "MIT" ]
null
null
null
codes/cpp/cplusplus-codesnippet/src/templates/example_template_valarray.cpp
zhoujiagen/learning-system-programming
2a18e9f8558433708837ba4bd0fae5d7c11bf110
[ "MIT" ]
null
null
null
codes/cpp/cplusplus-codesnippet/src/templates/example_template_valarray.cpp
zhoujiagen/learning-system-programming
2a18e9f8558433708837ba4bd0fae5d7c11bf110
[ "MIT" ]
null
null
null
#include <iostream> #include <valarray> int main (int argc, char **argv) { using namespace std; // 数值数组 double gpa[5] = { 3.1, 3.5, 3.8, 2.9, 3.3 }; valarray<double> v1; // size: 0 cout << v1.size () << endl; valarray<int> v2 (8); // size: 8 cout << v2.size () << endl; valarray<int> v3 (10, 8); // size: 8, e: 10 cout << v3.size () << endl; valarray<double> v4 (gpa, 4); // size: 4, e: first 4 elements of gpa cout << v4.size () << endl; valarray<int> v5 = { 20, 32, 17, 9 }; // C++11 cout << v5.size () << endl; return 0; }
18.387097
70
0.529825
zhoujiagen
0c63454c8fd021902141ae6784d729ff5dd384cc
2,123
hh
C++
include/NeuTrackingAction.hh
kwierman/Argon40Conversion
3c94209cd8036f846f7e3903bb41d35bcd85c2c0
[ "MIT" ]
null
null
null
include/NeuTrackingAction.hh
kwierman/Argon40Conversion
3c94209cd8036f846f7e3903bb41d35bcd85c2c0
[ "MIT" ]
null
null
null
include/NeuTrackingAction.hh
kwierman/Argon40Conversion
3c94209cd8036f846f7e3903bb41d35bcd85c2c0
[ "MIT" ]
null
null
null
#ifndef NeuTrackingAction_hh_ #define NeuTrackingAction_hh_ #include "NeuRootOutput.hh" #include "G4UserTrackingAction.hh" #include "globals.hh" namespace NeuFlux { /*! \class NeuTrackingAction \ingroup NeuFlux \brief Header file for defining the actions to take at the beginning and end of a track. The only capability programmed in at the moment is set parentPDG. This helps to identify a track with it's parent track to find where products come from. This modifies the event so that the top track is always pointed at the correct track. \note Position calculation is still rough, given that paths may curve \author Kevin Wierman \version 1.0 \date Oct 1, 2013 \contact kwierman@email.unc.edu */ class NeuTrackingAction : public G4UserTrackingAction , public NeuOutputtingComponent { public: NeuTrackingAction(); ~NeuTrackingAction(); void PreUserTrackingAction(const G4Track*); void PostUserTrackingAction(const G4Track*); void OnNewFileCreate(); void UpdateBranches(const G4Track* theTrack); private: Double_t fTrackID ; Double_t fParentID ; Double_t fPreX ; Double_t fPreY ; Double_t fPreZ ; Double_t fPreLT ; Double_t fPreGT ; Double_t fPrePT ; Double_t fPostX ; Double_t fPostY ; Double_t fPostZ ; Double_t fPostLT ; Double_t fPostGT ; Double_t fPostPT ; Double_t fPDGMass ; Double_t fPDGWidth ; Double_t fPDGCharge ; Double_t fPDGSpin ; Double_t fPDGiSpin ; Double_t fPDGiParity ; Double_t fPDGiConjugation; Double_t fPDGIsospin ; Double_t fPDGIsospin3 ; Double_t fPDGiIsospin ; Double_t fPDGiIsospin3 ; Double_t fPDGiGParity ; Double_t fPDGMagneticMoment ; Double_t fLeptonNumber; Double_t fBaryonNumber ; Int_t fPDGEncoding ; Double_t fAtomicNumber; Double_t fAtomicMass ; Double_t fVolume; Double_t fNextVolume; }; } #endif
23.32967
92
0.661799
kwierman
0c635191d64cfa0639fea9185cb642a34789d1f3
808
cpp
C++
Zerojudge/d618.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
9
2017-10-08T16:22:03.000Z
2021-08-20T09:32:17.000Z
Zerojudge/d618.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
null
null
null
Zerojudge/d618.cpp
w181496/OJ
67d1d32770376865eba8a9dd1767e97dae68989a
[ "MIT" ]
2
2018-01-15T16:35:44.000Z
2019-03-21T18:30:04.000Z
#include <iostream> #include <cstdio> #include <string> using namespace std; int main() { string s; int t,state; cin>>t; for(int i=1;i<=t;++i) { cin>>s; state=s[0]-'0'; for(int j=1;j<s.size();++j) { if(state==2) { if(s[j]-'0'!=1)continue; else state=1; } else if(state==3||state==4) { if(state==3&&s[j]-'0'==4)state=4; else if(state==4&&s[j]-'0'==3)state=3; else if(s[j]-'0'==1)state=1; } else if(state==1||state==5||state==6||state==7) { state=(s[j]-'0'); } } cout<<state<<endl; } return 0; }
22.444444
60
0.355198
w181496
0c63a30c7121cfde2b7c785c0d2d4c46942fbd53
10,150
hpp
C++
src/core/interfaces/common_include/qrc_loader.hpp
wgsyd/wgtf
d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed
[ "BSD-3-Clause" ]
28
2016-06-03T05:28:25.000Z
2019-02-14T12:04:31.000Z
src/core/interfaces/common_include/qrc_loader.hpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
null
null
null
src/core/interfaces/common_include/qrc_loader.hpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
14
2016-06-03T05:52:27.000Z
2019-03-21T09:56:03.000Z
#ifndef QRC_LOADER_HPP #define QRC_LOADER_HPP #include "qrc_loader_helper.hpp" #include "env_pointer.hpp" #include "core_common/assert.hpp" // Macro provide qrc resources loading for other plugins in WGTF, and a plugin which use this macro needs to link to // QtCore // and this plugin need to be loaded before other plugins which want to load qrc resources #ifdef QT_NAMESPACE #define WGT_INIT_QRC_LOADER \ \ namespace QT_NAMESPACE \ \ { \ bool qRegisterResourceData(int, const unsigned char*, const unsigned char*, const unsigned char*); \ bool qUnregisterResourceData(int, const unsigned char*, const unsigned char*, const unsigned char*); \ \ } \ \ using namespace QT_NAMESPACE; \ \ namespace wgt \ \ { \ namespace wgt_qrc_loader \ { \ class StaticInitializer \ { \ public: \ StaticInitializer() \ { \ static uintptr_t qtHooks[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; \ qtHooks[registerData] = reinterpret_cast<uintptr_t>(qRegisterResourceData); \ qtHooks[unRegisterData] = reinterpret_cast<uintptr_t>(qUnregisterResourceData); \ setPointer(QT_HOOK_ENV, &qtHooks[0]); \ } \ }; \ static StaticInitializer dummy; \ } \ \ } #else #define WGT_INIT_QRC_LOADER \ \ bool qRegisterResourceData(int, const unsigned char*, const unsigned char*, const unsigned char*); \ \ bool qUnregisterResourceData(int, const unsigned char*, const unsigned char*, const unsigned char*); \ \ \ namespace wgt \ \ { \ namespace wgt_qrc_loader \ { \ class StaticInitializer \ { \ public: \ StaticInitializer() \ { \ static uintptr_t qtHooks[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; \ qtHooks[registerData] = reinterpret_cast<uintptr_t>(qRegisterResourceData); \ qtHooks[unRegisterData] = reinterpret_cast<uintptr_t>(qUnregisterResourceData); \ setPointer(QT_HOOK_ENV, &qtHooks[0]); \ } \ }; \ static StaticInitializer dummy; \ } \ \ } #endif // Macro used in plugins which want to load qrc resources without link to QtCore. // Plugins which use this macro assuming that there is a plugin which has already used WGT_INIT_QRC_LOADER // and has been loaded before application loading this plugin #define WGT_INIT_QRC_RESOURCE \ \ namespace wgt \ \ { \ \ uintptr_t** \ getQtHooks() \ \ { \ static uintptr_t** s_qtHooks = nullptr; \ if (s_qtHooks == nullptr) \ { \ s_qtHooks = getPointerT<uintptr_t*>(QT_HOOK_ENV); \ TF_ASSERT(s_qtHooks != nullptr); \ } \ return s_qtHooks; \ \ } \ \ } \ \ bool qRegisterResourceData(int id, const unsigned char* qt_resource_struct, const unsigned char* qt_resource_name, \ const unsigned char* qt_resource_data) \ \ { \ auto hooks = wgt::getQtHooks(); \ if (hooks == nullptr) \ { \ return false; \ } \ auto func = reinterpret_cast<wgt::ResourceDataRegisterFunc>(hooks[wgt::registerData]); \ if (func == nullptr) \ { \ return false; \ } \ return func(id, qt_resource_struct, qt_resource_name, qt_resource_data); \ \ } \ \ \ bool qUnregisterResourceData(int id, const unsigned char* qt_resource_struct, const unsigned char* qt_resource_name, \ const unsigned char* qt_resource_data) \ \ { \ auto hooks = wgt::getQtHooks(); \ if (hooks == nullptr) \ { \ return false; \ } \ auto func = reinterpret_cast<wgt::ResourceDataUnregisterFunc>(hooks[wgt::unRegisterData]); \ if (func == nullptr) \ { \ return false; \ } \ return func(id, qt_resource_struct, qt_resource_name, qt_resource_data); \ \ } #endif // QRC_LOADER_HPP
74.632353
118
0.238621
wgsyd
0c66869100aab4eff2cd244d1ee5a5da6802ed71
8,892
hpp
C++
relacy/stdlib/pthread.hpp
pereckerdal/relacy
05d8a8fbb0b3600ff5bf34da0bab2bb148dff059
[ "BSD-3-Clause" ]
1
2020-05-30T13:06:12.000Z
2020-05-30T13:06:12.000Z
relacy/stdlib/pthread.hpp
pereckerdal/relacy
05d8a8fbb0b3600ff5bf34da0bab2bb148dff059
[ "BSD-3-Clause" ]
null
null
null
relacy/stdlib/pthread.hpp
pereckerdal/relacy
05d8a8fbb0b3600ff5bf34da0bab2bb148dff059
[ "BSD-3-Clause" ]
null
null
null
/* Relacy Race Detector * Copyright (c) 2008-2013, Dmitry S. Vyukov * All rights reserved. * This software is provided AS-IS with no warranty, either express or implied. * This software is distributed under a license and may not be copied, * modified or distributed except as expressly authorized under the * terms of the license contained in the file LICENSE in this distribution. */ #pragma once #include "mutex.hpp" #include "condition_variable.hpp" #include "semaphore.hpp" namespace rl { enum RL_POSIX_ERROR_CODE { RL_SUCCESS, RL_EINVAL, RL_ETIMEDOUT, RL_EBUSY, RL_EINTR, RL_EAGAIN, RL_EWOULDBLOCK, }; void rl_sched_yield(debug_info_param info); typedef win_waitable_object* rl_pthread_t; typedef void* rl_pthread_attr_t; int rl_pthread_create(rl_pthread_t* th, rl_pthread_attr_t* attr, void* (*func) (void*), void* arg, debug_info_param info); rl_pthread_t rl_pthread_self(debug_info_param info); int rl_pthread_join(rl_pthread_t th, void** res, debug_info_param info); struct sem_tag_pthread; typedef semaphore<sem_tag_pthread> rl_sem_t; int rl_sem_init(rl_sem_t* sema, int /*pshared*/, unsigned int initial_count, debug_info_param info); int rl_sem_destroy(rl_sem_t* sema, debug_info_param info); int rl_sem_wait(rl_sem_t* sema, debug_info_param info); int rl_sem_trywait(rl_sem_t* sema, debug_info_param info); int rl_sem_post(rl_sem_t* sema, debug_info_param info); int rl_sem_getvalue(rl_sem_t* sema, int* value, debug_info_param info); struct mutex_tag_pthread_mtx; typedef generic_mutex<mutex_tag_pthread_mtx> rl_pthread_mutex_t; struct rl_pthread_mutexattr_t { bool is_recursive_; }; enum RL_PTHREAD_MUTEX_TYPE { RL_PTHREAD_MUTEX_NORMAL, RL_PTHREAD_MUTEX_ERRORCHECK, RL_PTHREAD_MUTEX_RECURSIVE, RL_PTHREAD_MUTEX_DEFAULT, }; int rl_pthread_mutexattr_init(rl_pthread_mutexattr_t* attr, debug_info_param info); int rl_pthread_mutexattr_destroy(rl_pthread_mutexattr_t* attr, debug_info_param info); int rl_pthread_mutexattr_settype(rl_pthread_mutexattr_t* attr, int type, debug_info_param info); int rl_pthread_mutex_init(rl_pthread_mutex_t* m, rl_pthread_mutexattr_t const* attr, debug_info_param info); int rl_pthread_mutex_destroy(rl_pthread_mutex_t* m, debug_info_param info); int rl_pthread_mutex_lock(rl_pthread_mutex_t* m, debug_info_param info); int rl_pthread_mutex_timedlock(rl_pthread_mutex_t* m, const void* abs_timeout, debug_info_param info); int rl_pthread_mutex_try_lock(rl_pthread_mutex_t* m, debug_info_param info); int rl_pthread_mutex_unlock(rl_pthread_mutex_t* m, debug_info_param info); struct mutex_tag_pthread_rwlock; typedef generic_mutex<mutex_tag_pthread_rwlock> rl_pthread_rwlock_t; int rl_pthread_rwlock_init(rl_pthread_rwlock_t* lock, void const* /*attr*/, debug_info_param info); int rl_pthread_rwlock_destroy(rl_pthread_rwlock_t* lock, debug_info_param info); int rl_pthread_rwlock_rdlock(rl_pthread_rwlock_t* lock, debug_info_param info); int rl_pthread_rwlock_tryrdlock(rl_pthread_rwlock_t* lock, debug_info_param info); int rl_pthread_rwlock_wrlock(rl_pthread_rwlock_t* lock, debug_info_param info); int rl_pthread_rwlock_trywrlock(rl_pthread_rwlock_t* lock, debug_info_param info); int rl_pthread_rwlock_unlock(rl_pthread_rwlock_t* lock, debug_info_param info); struct condvar_tag_pthread; typedef condvar<condvar_tag_pthread> rl_pthread_cond_t; typedef int rl_pthread_condattr_t; int rl_pthread_cond_init(rl_pthread_cond_t* cv, rl_pthread_condattr_t* /*condattr*/, debug_info_param info); int rl_pthread_cond_destroy(rl_pthread_cond_t* cv, debug_info_param info); int rl_pthread_cond_broadcast(rl_pthread_cond_t* cv, debug_info_param info); int rl_pthread_cond_signal(rl_pthread_cond_t* cv, debug_info_param info); int rl_pthread_cond_timedwait(rl_pthread_cond_t* cv, rl_pthread_mutex_t* m, void const* /*timespec*/, debug_info_param info); int rl_pthread_cond_wait(rl_pthread_cond_t* cv, rl_pthread_mutex_t* m, debug_info_param info); enum RL_FUTEX_OP { RL_FUTEX_WAIT, RL_FUTEX_WAKE, }; int rl_int_futex_impl(context& c, atomic<int>* uaddr, int op, int val, struct timespec const* timeout, atomic<int>* uaddr2, int val3, debug_info_param info); struct futex_event { void* addr_; int op_; int val_; bool timeout_; int res_; void output(std::ostream& s) const; }; int rl_futex(atomic<int>* uaddr, int op, int val, struct timespec const* timeout, atomic<int>* uaddr2, int val3, debug_info_param info); } #ifdef EINVAL # undef EINVAL #endif #define EINVAL rl::RL_EINVAL #ifdef ETIMEDOUT # undef ETIMEDOUT #endif #define ETIMEDOUT rl::RL_ETIMEDOUT #ifdef EBUSY # undef EBUSY #endif #define EBUSY rl::RL_EBUSY #ifdef EINTR # undef EINTR #endif #define EINTR rl::RL_EINTR #ifdef EAGAIN # undef EAGAIN #endif #define EAGAIN rl::RL_EAGAIN #ifdef EWOULDBLOCK # undef EWOULDBLOCK #endif #define EWOULDBLOCK rl::RL_EWOULDBLOCK #define sched_yield() \ rl::rl_sched_yield($) #define pthread_yield() \ rl::rl_sched_yield($) #define pthread_t rl::rl_pthread_t #define pthread_attr_t rl::rl_pthread_attr_t #define pthread_create(th, attr, func, arg) \ rl::rl_pthread_create(th, attr, func, arg, $) #define pthread_self() \ rl::rl_pthread_self($) #define pthread_join(th, res) \ rl::rl_pthread_join(th, res, $) #define sem_t rl::rl_sem_t #define sem_init(sema, pshared, initial_count)\ rl::rl_sem_init(sema, pshared, initial_count, $) #define sem_destroy(sema)\ rl::rl_sem_destroy(sema, $) #define sem_wait(sema)\ rl::rl_sem_wait(sema, $) #define sem_trywait(sema)\ rl::rl_sem_trywait(sema, $) #define sem_post(sema)\ rl::rl_sem_post(sema, $) #define sem_getvalue(sema, pvalue)\ rl::rl_sem_getvalue(sema, pvalue, $) #define pthread_mutex_t rl::rl_pthread_mutex_t #define pthread_mutexattr_t rl::rl_pthread_mutexattr_t #ifdef PTHREAD_MUTEX_NORMAL # undef PTHREAD_MUTEX_NORMAL # undef PTHREAD_MUTEX_ERRORCHECK # undef PTHREAD_MUTEX_RECURSIVE # undef PTHREAD_MUTEX_DEFAULT #endif #define PTHREAD_MUTEX_NORMAL rl::RL_PTHREAD_MUTEX_NORMAL #define PTHREAD_MUTEX_ERRORCHECK rl::RL_PTHREAD_MUTEX_ERRORCHECK #define PTHREAD_MUTEX_RECURSIVE rl::RL_PTHREAD_MUTEX_RECURSIVE #define PTHREAD_MUTEX_DEFAULT rl::RL_PTHREAD_MUTEX_DEFAULT #define pthread_mutexattr_init(attr) \ rl::rl_pthread_mutexattr_init(attr, $) #define pthread_mutexattr_destroy(attr) \ rl::rl_pthread_mutexattr_destroy(attr, $) #define pthread_mutexattr_settype(attr, type) \ rl::rl_pthread_mutexattr_settype(attr, type, $) #define pthread_mutex_init(m, attr) \ rl::rl_pthread_mutex_init(m, attr, $) #define pthread_mutex_destroy(m) \ rl::rl_pthread_mutex_destroy(m, $) #define pthread_mutex_lock(m) \ rl::rl_pthread_mutex_lock(m, $) #define pthread_mutex_timedlock(m, abs_timeout) \ rl::rl_pthread_mutex_timedlock(m, abs_timeout, $) #define pthread_mutex_try_lock(m) \ rl::rl_pthread_mutex_try_lock(m, $) #define pthread_mutex_unlock(m) \ rl::rl_pthread_mutex_unlock(m, $) #define pthread_rwlock_t rl::rl_pthread_rwlock_t #define pthread_rwlock_init(lock, attr) \ rl::rl_pthread_rwlock_init(lock, attr, $) #define pthread_rwlock_destroy(lock) \ rl::rl_pthread_rwlock_destroy(lock, $) #define pthread_rwlock_rdlock(lock) \ rl::rl_pthread_rwlock_rdlock(lock, $) #define pthread_rwlock_tryrdlock(lock) \ rl::rl_pthread_rwlock_tryrdlock(lock, $) #define pthread_rwlock_wrlock(lock) \ rl::rl_pthread_rwlock_wrlock(lock, $) #define pthread_rwlock_trywrlock(lock) \ rl::rl_pthread_rwlock_trywrlock(lock, $) #define pthread_rwlock_unlock(lock) \ rl::rl_pthread_rwlock_unlock(lock, $) #define pthread_cond_t rl::rl_pthread_cond_t #define pthread_condattr_t rl::rl_pthread_condattr_t #define pthread_cond_init(cv, condattr) \ rl::rl_pthread_cond_init(cv, condattr, $) #define pthread_cond_destroy(cv) \ rl::rl_pthread_cond_destroy(cv, $) #define pthread_cond_broadcast(cv) \ rl::rl_pthread_cond_broadcast(cv, $) #define pthread_cond_signal(cv) \ rl::rl_pthread_cond_signal(cv, $) #define pthread_cond_timedwait(cv, m, timespec) \ rl::rl_pthread_cond_timedwait(cv, m, timespec, $) #define pthread_cond_wait(cv, m) \ rl::rl_pthread_cond_wait(cv, m, $) #ifdef FUTEX_WAKE # undef FUTEX_WAKE #endif #define FUTEX_WAKE rl::RL_FUTEX_WAKE #ifdef FUTEX_WAIT # undef FUTEX_WAIT #endif #define FUTEX_WAIT rl::RL_FUTEX_WAIT #define futex(uaddr, op, val, timeout, uaddr2, val3) \ rl::rl_futex(uaddr, op, val, timeout, uaddr2, val3, $)
24.977528
125
0.752024
pereckerdal
0c6ba9bf5a78c36b40a2bc1c771ea0c842ae02f8
4,192
cpp
C++
sakura_core/util/format.cpp
zlatantan/sakura
a722f9c86f2860606b3f9e7dc79bb169294cfaea
[ "Zlib" ]
1
2019-03-15T16:55:33.000Z
2019-03-15T16:55:33.000Z
sakura_core/util/format.cpp
zlatantan/sakura
a722f9c86f2860606b3f9e7dc79bb169294cfaea
[ "Zlib" ]
null
null
null
sakura_core/util/format.cpp
zlatantan/sakura
a722f9c86f2860606b3f9e7dc79bb169294cfaea
[ "Zlib" ]
null
null
null
/*! @file */ /* Copyright (C) 2007, kobake This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "StdAfx.h" #include "format.h" /*! 日時をフォーマット @param[out] 書式変換後の文字列 @param[in] バッファサイズ @param[in] format 書式 @param[in] systime 書式化したい日時 @return bool true @note %Y %y %m %d %H %M %S の変換に対応 @author aroka @date 2005.11.21 新規 @todo 出力バッファのサイズチェックを行う */ bool GetDateTimeFormat( TCHAR* szResult, int size, const TCHAR* format, const SYSTEMTIME& systime ) { TCHAR szTime[10]; const TCHAR *p = format; TCHAR *q = szResult; int len; while( *p ){ if( *p == _T('%') ){ ++p; switch(*p){ case _T('Y'): len = wsprintf(szTime,_T("%d"),systime.wYear); _tcscpy( q, szTime ); break; case _T('y'): len = wsprintf(szTime,_T("%02d"),(systime.wYear%100)); _tcscpy( q, szTime ); break; case _T('m'): len = wsprintf(szTime,_T("%02d"),systime.wMonth); _tcscpy( q, szTime ); break; case _T('d'): len = wsprintf(szTime,_T("%02d"),systime.wDay); _tcscpy( q, szTime ); break; case _T('H'): len = wsprintf(szTime,_T("%02d"),systime.wHour); _tcscpy( q, szTime ); break; case _T('M'): len = wsprintf(szTime,_T("%02d"),systime.wMinute); _tcscpy( q, szTime ); break; case _T('S'): len = wsprintf(szTime,_T("%02d"),systime.wSecond); _tcscpy( q, szTime ); break; // A Z case _T('%'): default: *q = *p; len = 1; break; } q+=len;//q += strlen(szTime); ++p; } else{ *q = *p; q++; p++; } } *q = *p; return true; } /*! バージョン番号の解析 @param[in] バージョン番号文字列 @return UINT32 8bit(符号1bit+数値7bit)ずつメジャー、マイナー、ビルド、リビジョンを格納 @author syat @date 2011.03.18 新規 @note 参考 PHP version_compare http://php.s3.to/man/function.version-compare.html */ UINT32 ParseVersion( const TCHAR* sVer ) { int nVer; int nShift = 0; //特別な文字列による下駄 int nDigit = 0; //連続する数字の数 UINT32 ret = 0; const TCHAR *p = sVer; int i; for( i=0; *p && i<4; i++){ //特別な文字列の処理 if( *p == _T('a') ){ if( _tcsncmp( _T("alpha"), p, 5 ) == 0 )p += 5; else p++; nShift = -0x60; } else if( *p == _T('b') ){ if( _tcsncmp( _T("beta"), p, 4 ) == 0 )p += 4; else p++; nShift = -0x40; } else if( *p == _T('r') || *p == _T('R') ){ if( _tcsnicmp( _T("rc"), p, 2 ) == 0 )p += 2; else p++; nShift = -0x20; } else if( *p == _T('p') ){ if( _tcsncmp( _T("pl"), p, 2 ) == 0 )p += 2; else p++; nShift = 0x20; } else if( !_istdigit(*p) ){ nShift = -0x80; } else{ nShift = 0; } while( *p && !_istdigit(*p) ){ p++; } //数値の抽出 for( nVer = 0, nDigit = 0; _istdigit(*p); p++ ){ if( ++nDigit > 2 )break; //数字は2桁までで止める nVer = nVer * 10 + *p - _T('0'); } //区切り文字の処理 while( *p && _tcschr( _T(".-_+"), *p ) ){ p++; } DEBUG_TRACE(_T(" VersionPart%d: ver=%d,shift=%d\n"), i, nVer, nShift); ret |= ( (nShift + nVer + 128) << (24-8*i) ); } for( ; i<4; i++ ){ //残りの部分はsigned 0 (=0x80)を埋める ret |= ( 128 << (24-8*i) ); } #ifdef _UNICODE DEBUG_TRACE(_T("ParseVersion %ls -> %08x\n"), sVer, ret); #endif return ret; } /*! バージョン番号の比較 @param[in] バージョンA @param[in] バージョンB @return int 0: バージョンは等しい、1以上: Aが新しい、-1以下: Bが新しい @author syat @date 2011.03.18 新規 */ int CompareVersion( const TCHAR* verA, const TCHAR* verB ) { UINT32 nVerA = ParseVersion(verA); UINT32 nVerB = ParseVersion(verB); return nVerA - nVerB; }
22.297872
99
0.595181
zlatantan
0c6ceb1940734cd71aefbb108f367a8cafd1abb3
3,423
cpp
C++
src/lib/init.cpp
lucteo/concore
ffbc3b8cead7498ddad601dcf357fa72529f81ad
[ "MIT" ]
52
2020-05-23T21:34:33.000Z
2022-02-23T03:06:50.000Z
src/lib/init.cpp
lucteo/concore
ffbc3b8cead7498ddad601dcf357fa72529f81ad
[ "MIT" ]
null
null
null
src/lib/init.cpp
lucteo/concore
ffbc3b8cead7498ddad601dcf357fa72529f81ad
[ "MIT" ]
2
2021-05-06T18:41:25.000Z
2021-07-24T03:50:42.000Z
#include "concore/init.hpp" #include "concore/low_level/spin_mutex.hpp" #include "concore/detail/platform.hpp" #include "concore/detail/likely.hpp" #include "concore/detail/library_data.hpp" #include "concore/detail/exec_context.hpp" #include <mutex> #define __IMPL__CONCORE_USE_CXX_ABI CONCORE_CPP_COMPILER(gcc) || CONCORE_CPP_COMPILER(clang) namespace concore { namespace detail { #if __IMPL__CONCORE_USE_CXX_ABI #if CONCORE_CPU_ARCH(arm) using cxa_guard_type = uint32_t; #else using cxa_guard_type = uint64_t; #endif static cxa_guard_type g_initialized_guard{0}; static exec_context* g_exec_context{nullptr}; // Take the advantage of ABI compatibility extern "C" int __cxa_guard_acquire(cxa_guard_type*); extern "C" void __cxa_guard_release(cxa_guard_type*); extern "C" void __cxa_guard_abort(cxa_guard_type*); #else static std::atomic<exec_context*> g_exec_context{nullptr}; #endif //! Copy of the init_data used to create the global exec_context init_data g_init_data_used; //! The per-thread execution context; can be null if the thread doesn't belong to any execution //! context. thread_local exec_context* g_tlsCtx{nullptr}; //! Called to shutdown the library void do_shutdown() { if (!is_initialized()) return; #if __IMPL__CONCORE_USE_CXX_ABI delete detail::g_exec_context; detail::g_exec_context = nullptr; g_initialized_guard = 0; #else delete detail::g_exec_context.load(); detail::g_exec_context.store(nullptr, std::memory_order_release); #endif } //! Actually initialized the library; this is guarded by get_exec_context() void do_init(const init_data* config) { static init_data default_config; if (!config) config = &default_config; auto global_ctx = new exec_context(*config); g_init_data_used = *config; #if __IMPL__CONCORE_USE_CXX_ABI detail::g_exec_context = global_ctx; #else detail::g_exec_context.store(global_ctx, std::memory_order_release); #endif atexit(&do_shutdown); } exec_context& get_exec_context(const init_data* config) { // If we have an execution context in the current thread, return it if (g_tlsCtx) return *g_tlsCtx; #if __IMPL__CONCORE_USE_CXX_ABI CONCORE_IF_UNLIKELY(__cxa_guard_acquire(&g_initialized_guard)) { try { do_init(config); } catch (...) { __cxa_guard_abort(&g_initialized_guard); throw; } __cxa_guard_release(&g_initialized_guard); } return *g_exec_context; #else auto p = detail::g_exec_context.load(std::memory_order_acquire); CONCORE_IF_UNLIKELY(!p) { static spin_mutex init_bottleneck; try { init_bottleneck.lock(); do_init(config); init_bottleneck.unlock(); p = g_exec_context.load(std::memory_order_acquire); } catch (...) { init_bottleneck.unlock(); throw; } } return *p; #endif } void set_context_in_current_thread(exec_context* ctx) { g_tlsCtx = ctx; } init_data get_current_init_data() { return g_init_data_used; } } // namespace detail inline namespace v1 { void init(const init_data& config) { if (is_initialized()) throw already_initialized(); detail::get_exec_context(&config); } bool is_initialized() { return detail::g_exec_context != nullptr; } void shutdown() { detail::do_shutdown(); } } // namespace v1 } // namespace concore
26.952756
95
0.715746
lucteo
0c6eb2e404923c73a81c117c51c8c746243191d2
491
cpp
C++
chapter-12/12.17.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
chapter-12/12.17.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
chapter-12/12.17.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
// int ix = 1024, *pi = &ix. *pi2 = new int(2048); // typedef unique_ptr<int> IntP; // a: IntP p0(ix); illegal, unique_ptr must be binded to a ptr which is the return value of operator 'new'. // b: IntP p1(pi); illegal, same reason as a. // c: IntP p2(pi2); legal, but pi2 may become a dangling pointer. // d: IntP p3(&ix); illegal, same reason as a. // e: IntP p4(new int(2048)); legal; // f: IntP p5(p2.get()); illegal, p2 has not yet release its pointer, poniter is still 'owned' by p2.
49.1
107
0.659878
zero4drift
0c7118e140840ec289a924ba09e009b60764842f
1,146
cpp
C++
Source/TacticalVRCore/Private/Weapon/Component/TVRAttachPoint_Muzzle.cpp
Tomura/TacticalVRCorePlugin
8c8ade8a33b68751cd73a51ddfdd098823197503
[ "MIT" ]
8
2021-12-20T01:04:23.000Z
2022-03-28T02:55:34.000Z
Source/TacticalVRCore/Private/Weapon/Component/TVRAttachPoint_Muzzle.cpp
Tomura/TacticalVRCorePlugin
8c8ade8a33b68751cd73a51ddfdd098823197503
[ "MIT" ]
null
null
null
Source/TacticalVRCore/Private/Weapon/Component/TVRAttachPoint_Muzzle.cpp
Tomura/TacticalVRCorePlugin
8c8ade8a33b68751cd73a51ddfdd098823197503
[ "MIT" ]
null
null
null
// This file is covered by the LICENSE file in the root of this plugin. #include "Weapon/Component/TVRAttachPoint_Muzzle.h" #include "Weapon/Attachments/WPNA_Muzzle.h" UTVRAttachPoint_Muzzle::UTVRAttachPoint_Muzzle(const FObjectInitializer& OI) : Super(OI) { CurrentAttachmentClass = nullptr; } bool UTVRAttachPoint_Muzzle::SetCurrentAttachmentClass(TSubclassOf<ATVRWeaponAttachment> NewClass) { if(NewClass == nullptr) { CurrentAttachmentClass = nullptr; OnConstruction(); return true; } if(NewClass->IsChildOf(AWPNA_Muzzle::StaticClass())) { const TSubclassOf<AWPNA_Muzzle> TestClass = *NewClass; if(AllowedMuzzles.Find(TestClass) != INDEX_NONE) { CurrentAttachmentClass = TestClass; OnConstruction(); return true; } } return false; } TSubclassOf<ATVRWeaponAttachment> UTVRAttachPoint_Muzzle::GetCurrentAttachmentClass_Internal() const { return CurrentAttachmentClass; } void UTVRAttachPoint_Muzzle::GetAllowedAttachments( TArray<TSubclassOf<ATVRWeaponAttachment>>& OutAllowedAttachments) const { for(TSubclassOf<AWPNA_Muzzle> TestClass : AllowedMuzzles) { OutAllowedAttachments.Add(TestClass); } }
24.913043
100
0.787958
Tomura
0c722dabcdd943c2f0f17b01d76a282850bc0e58
3,031
cpp
C++
src/internal/text_formatter.cpp
stefano-pogliani/promclient-cpp
d31b06de41f8e111ae8c463ad396e3e7f8078af9
[ "MIT" ]
null
null
null
src/internal/text_formatter.cpp
stefano-pogliani/promclient-cpp
d31b06de41f8e111ae8c463ad396e3e7f8078af9
[ "MIT" ]
null
null
null
src/internal/text_formatter.cpp
stefano-pogliani/promclient-cpp
d31b06de41f8e111ae8c463ad396e3e7f8078af9
[ "MIT" ]
null
null
null
// Copyright 2017 Stefano Pogliani <stefano@spogliani.net> #include "promclient/internal/text_formatter.h" #include <iomanip> #include <regex> #include <sstream> #include "promclient/collector_registry.h" #include "promclient/metric.h" using promclient::CollectorRegistry; using promclient::DescriptorRef; using promclient::Sample; using promclient::internal::TextFormatBridge; using promclient::internal::TextFormatter; std::regex NEW_LINE_RE = std::regex("\n"); std::regex QUOTE_RE = std::regex("\""); std::regex SLASH_RE = std::regex("\\\\"); TextFormatBridge::TextFormatBridge(CollectorRegistry* registry) { this->registry_ = registry; this->strategy_ = CollectorRegistry::CollectStrategy::SORTED; } void TextFormatBridge::collect() { MetricsList metrics = this->registry_->collect(this->strategy_); for (auto metric : metrics) { DescriptorRef descriptor = metric.descriptor(); std::string desc = formatter.describe(descriptor); std::string name = descriptor->name(); this->write(desc); for (Sample sample : metric.samples()) { std::string line = formatter.sample(name, sample); this->write(line); } } } std::string TextFormatter::describe(DescriptorRef descriptor) { std::string help = descriptor->help(); std::string name = descriptor->name(); std::string type = descriptor->type(); std::stringstream desc; if (help != "") { std::string help_ = help; help_ = std::regex_replace(help_, SLASH_RE, "\\\\"); help_ = std::regex_replace(help_, NEW_LINE_RE, "\\n"); desc << "# HELP " << name << " " << help_ << '\n'; } desc << "# TYPE " << name << " " << type << '\n'; return desc.str(); } std::string TextFormatter::sample(std::string name, Sample sample) { // Start the line with the metric name. std::stringstream line; line << name; // Add the sample role, if any. if (sample.role() != "") { line << '_' << sample.role(); } // Add labels, if any. std::map<std::string, std::string> labels = sample.labels(); if (labels.size() != 0) { std::size_t count = labels.size(); std::size_t index = 0; line << '{'; for (auto pair : labels) { std::string name = pair.first; std::string value = pair.second; // Escape label value. value = std::regex_replace(value, SLASH_RE, "\\\\"); value = std::regex_replace(value, NEW_LINE_RE, "\\n"); value = std::regex_replace(value, QUOTE_RE, "\\\""); line << name << "=\"" << value << '"'; index += 1; if (index != count) { line << ','; } } line << '}'; } // Format value. double value = sample.value(); if (isinf(value) && value > 0) { line << " +Inf\n"; } else if(isinf(value) && value < 0) { line << " -Inf\n"; } else if(isnan(value)) { line << " NaN\n"; } else { auto digits = std::numeric_limits<double>::digits10 + 1; line << ' ' << std::setprecision(digits) << std::scientific << value << '\n'; } return line.str(); }
25.905983
68
0.61036
stefano-pogliani
0c77941a30e177d2c59dfb86f6cc39ee86d9b2d5
770
cpp
C++
urionlinejudge/1040.cpp
andraantariksa/code-exercise-answer
69b7dbdc081cdb094cb110a72bc0c9242d3d344d
[ "MIT" ]
1
2019-11-06T15:17:48.000Z
2019-11-06T15:17:48.000Z
urionlinejudge/1040.cpp
andraantariksa/code-exercise-answer
69b7dbdc081cdb094cb110a72bc0c9242d3d344d
[ "MIT" ]
null
null
null
urionlinejudge/1040.cpp
andraantariksa/code-exercise-answer
69b7dbdc081cdb094cb110a72bc0c9242d3d344d
[ "MIT" ]
1
2018-11-13T08:43:26.000Z
2018-11-13T08:43:26.000Z
#include <iostream> #include <iomanip> float a, b, c, d, e, average; int main(){ std::cin>>a>>b>>c>>d; average = (a*2+b*3+c*4+d)/10; std::cout<<std::fixed<<std::setprecision(1); std::cout<<"Media: "<<average<<std::endl; if(average >= 7.0){ std::cout<<"Aluno aprovado."<<std::endl; }else if(average < 5.0){ std::cout<<"Aluno reprovado."<<std::endl; }else{ std::cout<<"Aluno em exame."<<std::endl; std::cin>>e; std::cout<<"Nota do exame: "<<e<<std::endl; if((average+e)/2 >= 5){ std::cout<<"Aluno aprovado."<<std::endl; }else{ std::cout<<"Aluno reprovado."<<std::endl; } std::cout<<"Media final: "<<(average+e)/2<<std::endl; } return 0; }
28.518519
61
0.507792
andraantariksa
0c789ba1d9c67d5169288ddcb2fe8f56d8af7a6c
1,377
cpp
C++
codeforces/185/A/test.cpp
rdragos/work
aed4c9ace3fad6b0c63caadee69de2abde108b40
[ "MIT" ]
2
2020-05-30T17:11:47.000Z
2021-09-25T08:16:48.000Z
codeforces/185/A/test.cpp
rdragos/work
aed4c9ace3fad6b0c63caadee69de2abde108b40
[ "MIT" ]
null
null
null
codeforces/185/A/test.cpp
rdragos/work
aed4c9ace3fad6b0c63caadee69de2abde108b40
[ "MIT" ]
1
2021-09-24T11:14:27.000Z
2021-09-24T11:14:27.000Z
#include <cstdio> #include <algorithm> #include <fstream> #include <iostream> #include <vector> #include <queue> #include <map> #include <cstring> #include <string> #include <set> #define pb push_back #define mp make_pair #define f first #define s second #define ll long long const int MAXN = 200; using namespace std; int N; char A[MAXN]; int main() { // freopen("test.in", "r", stdin); // freopen("test.out", "w", stdout); scanf("%d\n", &N); string strl, strm, strd; strl = "Freda's"; strm = "Rainbow's"; strd = "OMG>.< I don't know!"; for (int i = 1; i <= N; ++i) { memset(A, '\0', sizeof(A)); gets(A); int n = strlen(A); int okm = 0; int okl = 0; if (n >= 5) okm |= (A[0] == 'm' && A[1] == 'i' && A[2] == 'a' && A[3] == 'o' && A[4] == '.'); if (n >= 5) okl |= (A[n - 1] == '.' && A[n - 2] == 'a' && A[n - 3] == 'l' && A[n - 4] == 'a' && A[n - 5] == 'l'); // cerr << okm << " " << okl << "\n"; if (okm && okl) { cout << strd << "\n"; continue; } if (okm) { cout << strm << "\n"; continue; } if (okl) { cout << strl << "\n"; continue; } cout << strd << "\n"; } return 0; }
19.671429
113
0.406681
rdragos
0c7cb62dee58e3b14e7e73475c57baa87bbccc92
5,565
cpp
C++
imageprocessing.cpp
MrFinchh/Receipt-OCR
887afa12d90b153548fc59d72acb7ba30123cf89
[ "MIT" ]
1
2021-04-22T01:53:55.000Z
2021-04-22T01:53:55.000Z
imageprocessing.cpp
MrFinchh/Receipt-OCR
887afa12d90b153548fc59d72acb7ba30123cf89
[ "MIT" ]
null
null
null
imageprocessing.cpp
MrFinchh/Receipt-OCR
887afa12d90b153548fc59d72acb7ba30123cf89
[ "MIT" ]
null
null
null
#include "imageprocessing.h" using namespace cv ; using namespace std; using namespace tesseract; ImageProcessing::ImageProcessing() { } QString ImageProcessing::readImage(Mat gray) { imshow("gelen",gray); waitKey(0); destroyAllWindows(); cout << "the output : "<< endl; // Pass it to Tesseract API tesseract::TessBaseAPI api; //api.Init(NULL,"eng",tesseract::OEM_LSTM_ONLY); api.Init(NULL, "eng1", tesseract::OEM_LSTM_ONLY); //after OEM_DEFAULT->, NULL, 0, NULL, NULL, false); api.SetPageSegMode(tesseract::PSM_SINGLE_BLOCK); api.SetImage((uchar*)gray.data, gray.cols, gray.rows, 1, gray.cols); // Get the text char* out = api.GetUTF8Text(); //cout << out.toUtf8().constData() << endl; return out ; } bool compareContourAreas ( std::vector<cv::Point> contour1, std::vector<cv::Point> contour2 ) { double i = fabs( contourArea(cv::Mat(contour1)) ); double j = fabs( contourArea(cv::Mat(contour2)) ); return ( i > j ); } bool compareXCords(Point p1, Point p2) { return (p1.x < p2.x); } bool compareYCords(Point p1, Point p2) { return (p1.y < p2.y); } bool compareDistance(pair<Point, Point> p1, pair<Point, Point> p2) { return (norm(p1.first - p1.second) < norm(p2.first - p2.second)); } double _distance(Point p1, Point p2) { return sqrt(((p1.x - p2.x) * (p1.x - p2.x)) + ((p1.y - p2.y) * (p1.y - p2.y))); } void resizeToHeight(Mat src, Mat &dst, int height) { Size s = Size(src.cols * (height / double(src.rows)), height); resize(src, dst, s, INTER_AREA); } void orderPoints(vector<Point> inpts, vector<Point> &ordered) { sort(inpts.begin(), inpts.end(), compareXCords); vector<Point> lm(inpts.begin(), inpts.begin()+2); vector<Point> rm(inpts.end()-2, inpts.end()); sort(lm.begin(), lm.end(), compareYCords); Point tl(lm[0]); Point bl(lm[1]); vector<pair<Point, Point> > tmp; for(size_t i = 0; i< rm.size(); i++) { tmp.push_back(make_pair(tl, rm[i])); } sort(tmp.begin(), tmp.end(), compareDistance); Point tr(tmp[0].second); Point br(tmp[1].second); ordered.push_back(tl); ordered.push_back(tr); ordered.push_back(br); ordered.push_back(bl); } void fourPointTransform(Mat src, Mat &dst, vector<Point> pts) { vector<Point> ordered_pts; orderPoints(pts, ordered_pts); double wa = _distance(ordered_pts[2], ordered_pts[3]); double wb = _distance(ordered_pts[1], ordered_pts[0]); double mw = max(wa, wb); double ha = _distance(ordered_pts[1], ordered_pts[2]); double hb = _distance(ordered_pts[0], ordered_pts[3]); double mh = max(ha, hb); Point2f src_[] = { Point2f(ordered_pts[0].x, ordered_pts[0].y), Point2f(ordered_pts[1].x, ordered_pts[1].y), Point2f(ordered_pts[2].x, ordered_pts[2].y), Point2f(ordered_pts[3].x, ordered_pts[3].y), }; Point2f dst_[] = { Point2f(0,0), Point2f(mw - 1, 0), Point2f(mw - 1, mh - 1), Point2f(0, mh - 1) }; Mat m = getPerspectiveTransform(src_, dst_); warpPerspective(src, dst, m, Size(mw, mh)); } void preProcess(Mat src, Mat &dst) { cv::Mat imageGrayed; cv::Mat imageOpen, imageClosed, imageBlurred; cvtColor(src, imageGrayed, COLOR_BGR2GRAY); cv::Mat structuringElmt = cv::getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(4,4)); morphologyEx(imageGrayed, imageOpen, cv::MORPH_OPEN, structuringElmt); morphologyEx(imageOpen, imageClosed, cv::MORPH_CLOSE, structuringElmt); GaussianBlur(imageClosed, imageBlurred, Size(5, 5), 0); Canny(imageBlurred, dst, 40, 84); } QString ImageProcessing::init() { QString output ; Mat image = imread(this->path); Mat gray, edged, warped; preProcess(image, edged); vector<vector<Point> > contours; vector<Vec4i> hierarchy; vector<vector<Point> > approx; findContours(edged, contours, hierarchy, RETR_LIST, CHAIN_APPROX_SIMPLE); approx.resize(contours.size()); size_t i,j; for(i = 0; i< contours.size(); i++) { double peri = arcLength(contours[i], true); approxPolyDP(contours[i], approx[i], 0.02 * peri, true); } sort(approx.begin(), approx.end(), compareContourAreas); vector<vector<Point>> cnts; int LIMIT = 5 ; if(approx.size() < LIMIT) LIMIT = approx.size(); for(int m = 0 ; m < LIMIT ; m++) { cnts.push_back(approx[m]); } for(i = 0; i< cnts.size(); i++) { if(cnts[i].size() == 4) { break; } } if(i < cnts.size()) { drawContours(image, cnts, i, Scalar(0, 255, 0), 2); fourPointTransform(image, warped, cnts[i]); cvtColor(warped, warped, COLOR_BGR2GRAY, 1); adaptiveThreshold(warped, warped, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, 15); GaussianBlur(warped, warped, Size(3, 3), 0); output = readImage(warped); } else { cvtColor(image,image,COLOR_BGR2GRAY); adaptiveThreshold(image, image, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 15, 15); GaussianBlur(image, image, Size(3, 3), 0); output = readImage(image); } return output ; } QString ImageProcessing::getInfo(QString filePath) { this->path = filePath.toUtf8().constData(); QString output = init(); /* Mat src = imread(this->path); cvtColor(src,src,COLOR_BGR2GRAY); QString output = readImage(src); */ return output ; }
26.25
95
0.616712
MrFinchh
0c7e449d9a76d4de261d1021b25def40d323d6fd
843
cpp
C++
PAT1040.cpp
Geeks-Z/PAT
c02f08f11c4a628203f8d2dccbd7fecfc0943b34
[ "MIT" ]
null
null
null
PAT1040.cpp
Geeks-Z/PAT
c02f08f11c4a628203f8d2dccbd7fecfc0943b34
[ "MIT" ]
null
null
null
PAT1040.cpp
Geeks-Z/PAT
c02f08f11c4a628203f8d2dccbd7fecfc0943b34
[ "MIT" ]
null
null
null
/* * @Descripttion: 有几个PAT * @version: 1.0 * @Author: Geeks_Z * @Date: 2021-04-30 14:40:53 * @LastEditors: Geeks_Z * @LastEditTime: 2021-05-08 11:30:38 */ #include <cstdio> #include <iostream> #include <string> using namespace std; const int mod = 1000000007; const int maxn = 100010; int main() { // freopen("input.txt", "r", stdin); string str; cin >> str; int pNum[maxn] = {0}, res = 0; if (str[0] == 'P') { pNum[0] = 1; } for (int i = 1; i < str.length(); i++) { if (str[i] == 'P') { pNum[i] = pNum[i - 1] + 1; } else { pNum[i] = pNum[i - 1]; } } int tNum = 0; for (int i = str.length() - 1; i >= 0; i--) { if (str[i] == 'T') { tNum++; } if (str[i] == 'A') { res = (res + pNum[i] * tNum) % mod; } } cout << res; return 0; }
16.529412
45
0.476868
Geeks-Z
0c7f99cf703b44ea3817338b95a06c3aee761336
6,285
cpp
C++
connectors/dds4ccm/tests/CoherentWriter/Sender/CoherentWrite_Test_Sender_exec.cpp
qinwang13/CIAO
e69add1b5da8e9602bcc85d581ecbf1bd41c49a3
[ "DOC" ]
10
2016-07-20T00:55:50.000Z
2020-10-04T19:07:10.000Z
connectors/dds4ccm/tests/CoherentWriter/Sender/CoherentWrite_Test_Sender_exec.cpp
qinwang13/CIAO
e69add1b5da8e9602bcc85d581ecbf1bd41c49a3
[ "DOC" ]
13
2016-09-27T14:08:27.000Z
2020-11-11T10:45:56.000Z
connectors/dds4ccm/tests/CoherentWriter/Sender/CoherentWrite_Test_Sender_exec.cpp
qinwang13/CIAO
e69add1b5da8e9602bcc85d581ecbf1bd41c49a3
[ "DOC" ]
12
2016-04-20T09:57:02.000Z
2021-12-24T17:23:45.000Z
// -*- C++ -*- /** * Code generated by the The ACE ORB (TAO) IDL Compiler v1.8.3 * TAO and the TAO IDL Compiler have been developed by: * Center for Distributed Object Computing * Washington University * St. Louis, MO * USA * http://www.cs.wustl.edu/~schmidt/doc-center.html * and * Distributed Object Computing Laboratory * University of California at Irvine * Irvine, CA * USA * and * Institute for Software Integrated Systems * Vanderbilt University * Nashville, TN * USA * http://www.isis.vanderbilt.edu/ * * Information about TAO is available at: * http://www.dre.vanderbilt.edu/~schmidt/TAO.html **/ #include "CoherentWrite_Test_Sender_exec.h" #include "tao/ORB_Core.h" #include "ace/Reactor.h" namespace CIAO_CoherentWrite_Test_Sender_Impl { /** * WriteHandler */ WriteHandler::WriteHandler (Sender_exec_i &callback) : callback_ (callback) { } int WriteHandler::handle_exception (ACE_HANDLE) { this->callback_.start (); return 0; } /** * Facet Executor Implementation Class: restart_writer_exec_i */ restart_writer_exec_i::restart_writer_exec_i ( ::CoherentWrite_Test::CCM_Sender_Context_ptr ctx, Sender_exec_i &callback) : ciao_context_ ( ::CoherentWrite_Test::CCM_Sender_Context::_duplicate (ctx)) , callback_ (callback) { } restart_writer_exec_i::~restart_writer_exec_i (void) { } // Operations from ::CoherentWriteRestarter void restart_writer_exec_i::restart_write (void) { this->callback_.restart (); } /** * Component Executor Implementation Class: Sender_exec_i */ Sender_exec_i::Sender_exec_i (void) : iterations_ (0) , run_ (1) , total_iter (0) , wh_ (0) { ACE_NEW_THROW_EX (this->wh_, WriteHandler (*this), ::CORBA::INTERNAL ()); } Sender_exec_i::~Sender_exec_i (void) { delete this->wh_; } // Supported operations and attributes. ACE_Reactor* Sender_exec_i::reactor (void) { ACE_Reactor* reactor = 0; ::CORBA::Object_var ccm_object = this->ciao_context_->get_CCM_object(); if (! ::CORBA::is_nil (ccm_object.in ())) { ::CORBA::ORB_var orb = ccm_object->_get_orb (); if (! ::CORBA::is_nil (orb.in ())) { reactor = orb->orb_core ()->reactor (); } } if (reactor == 0) { throw ::CORBA::INTERNAL (); } return reactor; } void Sender_exec_i::restart (void) { ++this->run_; delete this->wh_; ACE_NEW_THROW_EX (this->wh_, WriteHandler (*this), ::CORBA::INTERNAL ()); this->reactor ()->notify (this->wh_); } void Sender_exec_i::start (void) { ::CoherentWriteTestConnector::Writer_var writer = this->ciao_context_->get_connection_info_write_data (); CoherentWriteStarter_var starter = this->ciao_context_->get_connection_start_reader (); if (::CORBA::is_nil (starter.in ()) || ::CORBA::is_nil (writer.in ())) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: Unable to start the reader\n"))); return; } writer->is_coherent_write (true); starter->set_reader_properties (this->iterations_); ACE_DEBUG ((LM_DEBUG, "Start run <%d> with <%u> iterations\n", this->run_, this->iterations ())); CoherentWriteTestSeq write_many_seq (this->iterations_); write_many_seq.length (this->iterations_); for (int i = 1; i < this->iterations_ + 1; ++i) { CoherentWriteTest new_key; new_key.symbol = CORBA::string_dup("KEY_1"); new_key.iteration = ++total_iter; write_many_seq[i-1] = new_key; } writer->write_many (write_many_seq); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Written <%u> keys uptil now\n"), total_iter)); ACE_OS::sleep (2); starter->start_read (this->run_); } // Component attributes and port operations. ::CCM_CoherentWriteRestarter_ptr Sender_exec_i::get_restart_writer (void) { if ( ::CORBA::is_nil (this->ciao_restart_writer_.in ())) { restart_writer_exec_i *tmp = 0; ACE_NEW_RETURN ( tmp, restart_writer_exec_i ( this->ciao_context_.in (), *this), ::CCM_CoherentWriteRestarter::_nil ()); this->ciao_restart_writer_ = tmp; } return ::CCM_CoherentWriteRestarter::_duplicate ( this->ciao_restart_writer_.in ()); } ::CORBA::UShort Sender_exec_i::iterations (void) { return this->iterations_; } void Sender_exec_i::iterations ( const ::CORBA::UShort iterations) { this->iterations_ = iterations; } // Operations from Components::SessionComponent. void Sender_exec_i::set_session_context ( ::Components::SessionContext_ptr ctx) { this->ciao_context_ = ::CoherentWrite_Test::CCM_Sender_Context::_narrow (ctx); if ( ::CORBA::is_nil (this->ciao_context_.in ())) { throw ::CORBA::INTERNAL (); } } void Sender_exec_i::configuration_complete (void) { /* Your code here. */ } void Sender_exec_i::ccm_activate (void) { try { this->reactor ()->notify (this->wh_); } catch (const ::CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught:"); ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: GET_CONNECTION_START_READER : Exception caught\n"))); } catch (...) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("ERROR: GET_CONNECTION_START_READER : Unknown exception caught\n"))); } } void Sender_exec_i::ccm_passivate (void) { /* Your code here. */ } void Sender_exec_i::ccm_remove (void) { /* Your code here. */ } extern "C" SENDER_EXEC_Export ::Components::EnterpriseComponent_ptr create_CoherentWrite_Test_Sender_Impl (void) { ::Components::EnterpriseComponent_ptr retval = ::Components::EnterpriseComponent::_nil (); ACE_NEW_NORETURN ( retval, Sender_exec_i); return retval; } }
23.62782
89
0.606046
qinwang13
0c81e9c6cdd0c7ffa40ae96cb31e06601cd9a962
3,374
hpp
C++
saga/saga/adaptors/utils/ini/ini.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
5
2015-09-15T16:24:14.000Z
2021-08-12T11:05:55.000Z
saga/saga/adaptors/utils/ini/ini.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
null
null
null
saga/saga/adaptors/utils/ini/ini.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
3
2016-11-17T04:38:38.000Z
2021-04-10T17:23:52.000Z
// Copyright (c) 2005-2007 Andre Merzky (andre@merzky.net) // Copyright (c) 2009 João Abecasis // // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef _SAGA_INI_H_ #define _SAGA_INI_H_ 1 #include <map> #include <list> #include <vector> #include <iostream> // other includes from SAGA #include <saga/saga/util.hpp> #include <saga/saga/types.hpp> // suppress warnings about dependent classes not being exported from the dll #if defined(BOOST_MSVC) #pragma warning(push) #pragma warning(disable: 4251 4231 4275 4660) #endif ////////////////////////////////////////// // // C++ interface // namespace saga { // forward declaration namespace impl { namespace ini { class section; } } namespace ini { class section; typedef section ini; typedef std::map <std::string, std::string> entry_map; typedef std::map <std::string, section> section_map; #define SAGA_INI_EXPORT /**/ class SAGA_EXPORT/*SAGA_INI_EXPORT*/ section { private: typedef saga::impl::ini::section impl_sec; typedef TR1::shared_ptr <impl_sec> shared_sec; shared_sec impl_; shared_sec get_impl (void) const { return (impl_); } explicit section (shared_sec impl); explicit section (impl_sec * sec); void debug (std::string = "") const; public: section (std::string filename = ""); section (const section & in); ~section (void); void read (std::string filename); void parse (std::string sourcename, std::vector <std::string> lines); void merge (std::string second); void merge ( const section & second); void dump (int ind = 0, std::ostream& strm = std::cout) const; void add_section (std::string sec_name, const section & sec); bool has_section (std::string sec_name) const; bool has_section_full (std::string sec_name) const; section get_section (std::string sec_name) const; section_map get_sections (void) const; void add_entry (std::string key, std::string val); bool has_entry (std::string key) const; std::string get_entry (std::string key) const; std::string get_entry (std::string key, std::string dflt_val) const; entry_map get_entries (void) const; section get_root (void) const; std::string get_name (void) const; }; } // namespace ini } // namespace saga #endif // _SAGA_INI_H_
31.240741
85
0.496147
saga-project
0c84a0e6e65d8b30939677ac795d81a0ca6776c2
386
hpp
C++
src/include/Window.hpp
sglyons2/edu-chat
0520c76903a84c1034ec6b83c51f162e195fe74f
[ "MIT" ]
null
null
null
src/include/Window.hpp
sglyons2/edu-chat
0520c76903a84c1034ec6b83c51f162e195fe74f
[ "MIT" ]
null
null
null
src/include/Window.hpp
sglyons2/edu-chat
0520c76903a84c1034ec6b83c51f162e195fe74f
[ "MIT" ]
null
null
null
#ifndef WINDOW_HPP #define WINDOW_HPP #include <ncurses.h> #include <vector> #include <string> struct Window { WINDOW *window; int height; int width; int begin_y; int begin_x; Window(int height, int width, int begin_y, int begin_x); ~Window(); void print(std::vector<std::string>& lines, bool boxed); void resize(int height, int width, int begin_y, int begin_x); }; #endif
17.545455
62
0.715026
sglyons2
0c8a7d9784c2b2b3f68921b1a452c4081c5ce82a
3,888
cpp
C++
util.cpp
tpruvot/skminer
2dd652461ed8dcce2137547b58376dc2107f6103
[ "Apache-2.0" ]
3
2015-10-22T03:11:03.000Z
2021-05-26T07:47:48.000Z
util.cpp
tpruvot/skminer
2dd652461ed8dcce2137547b58376dc2107f6103
[ "Apache-2.0" ]
null
null
null
util.cpp
tpruvot/skminer
2dd652461ed8dcce2137547b58376dc2107f6103
[ "Apache-2.0" ]
2
2017-07-14T19:21:17.000Z
2017-12-22T08:05:25.000Z
/* * Copyright 2010 Jeff Garzik * Copyright 2012-2014 pooler * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. See COPYING for more details. */ #define _GNU_SOURCE #include "cpuminer-config.h" #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <stdarg.h> #include <string.h> #include <stdbool.h> #include <inttypes.h> #include <unistd.h> #include <jansson.h> #include <curl/curl.h> #include <time.h> #if defined(WIN32) #include <winsock2.h> #include <mstcpip.h> #else #include <errno.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #endif #include "compat.h" #include "miner.h" #include "elist.h" void abin2hex(char *s, const unsigned char *p, size_t len) { int i; for (i = 0; i < len; i++) sprintf(s + (i * 2), "%02x", (unsigned int) p[i]); } char *bin2hex(const unsigned char *p, size_t len) { unsigned int i; char *s = (char*)malloc((len * 2) + 1); if (!s) return NULL; for (i = 0; i < len; i++) sprintf(s + (i * 2), "%02x", (unsigned int) p[i]); return s; } bool hex2bin(unsigned char *p, const char *hexstr, size_t len) { char hex_byte[3]; char *ep; hex_byte[2] = '\0'; while (*hexstr && len) { if (!hexstr[1]) { // applog(LOG_ERR, "hex2bin str truncated"); return false; } hex_byte[0] = hexstr[0]; hex_byte[1] = hexstr[1]; *p = (unsigned char) strtol(hex_byte, &ep, 16); if (*ep) { // applog(LOG_ERR, "hex2bin failed on '%s'", hex_byte); return false; } p++; hexstr += 2; len--; } return (len == 0 && *hexstr == 0) ? true : false; } /* Subtract the `struct timeval' values X and Y, storing the result in RESULT. Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating Y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * `tv_usec' is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } void diff_to_target(uint32_t *target, double diff) { uint64_t m; int k; for (k = 6; k > 0 && diff > 1.0; k--) diff /= 4294967296.0; m = (uint64_t)(4294901760.0 / diff); if (m == 0 && k == 6) memset(target, 0xff, 32); else { memset(target, 0, 32); target[k] = (uint32_t)m; target[k + 1] = (uint32_t)(m >> 32); } } #ifdef WIN32 #define socket_blocks() (WSAGetLastError() == WSAEWOULDBLOCK) #else #define socket_blocks() (errno == EAGAIN || errno == EWOULDBLOCK) #endif static bool send_line(curl_socket_t sock, char *s) { ssize_t len, sent = 0; len = (ssize_t)strlen(s); s[len++] = '\n'; while (len > 0) { struct timeval timeout = {0, 0}; ssize_t n; fd_set wd; FD_ZERO(&wd); FD_SET(sock, &wd); if (select((int)sock + 1, NULL, &wd, NULL, &timeout) < 1) return false; n = send(sock, s + sent, len, 0); if (n < 0) { if (!socket_blocks()) return false; n = 0; } sent += n; len -= n; } return true; } #define RBUFSIZE 2048 #define RECVSIZE (RBUFSIZE - 4) #if LIBCURL_VERSION_NUM >= 0x071101 static curl_socket_t opensocket_grab_cb(void *clientp, curlsocktype purpose, struct curl_sockaddr *addr) { curl_socket_t *sock = (curl_socket_t *)clientp; *sock = socket(addr->family, addr->socktype, addr->protocol); return *sock; } #endif
20.145078
77
0.635288
tpruvot
0c8c43c713088275106d5fbb860304d038893db2
12,668
cpp
C++
coreneuron/mpi/lib/mpispike.cpp
phoenixdong/CoreNeuron
ff80819b04d5cbe41d9dfc35608b55df961c5646
[ "BSD-3-Clause" ]
null
null
null
coreneuron/mpi/lib/mpispike.cpp
phoenixdong/CoreNeuron
ff80819b04d5cbe41d9dfc35608b55df961c5646
[ "BSD-3-Clause" ]
null
null
null
coreneuron/mpi/lib/mpispike.cpp
phoenixdong/CoreNeuron
ff80819b04d5cbe41d9dfc35608b55df961c5646
[ "BSD-3-Clause" ]
null
null
null
/* # ============================================================================= # Copyright (c) 2016 - 2021 Blue Brain Project/EPFL # # See top-level LICENSE file for details. # =============================================================================. */ #include "coreneuron/nrnconf.h" /* do not want the redef in the dynamic load case */ #include "coreneuron/mpi/nrnmpiuse.h" #include "coreneuron/mpi/nrnmpi.h" #include "coreneuron/mpi/nrnmpidec.h" #include "nrnmpi.hpp" #include "coreneuron/utils/profile/profiler_interface.h" #include "coreneuron/utils/nrn_assert.h" #include <mpi.h> #include <cstring> namespace coreneuron { extern MPI_Comm nrnmpi_comm; static int np; static int* displs{nullptr}; static int* byteovfl{nullptr}; /* for the compressed transfer method */ static MPI_Datatype spike_type; static void* emalloc(size_t size) { void* memptr = malloc(size); assert(memptr); return memptr; } // Register type NRNMPI_Spike void nrnmpi_spike_initialize() { NRNMPI_Spike s; int block_lengths[2] = {1, 1}; MPI_Aint addresses[3]; MPI_Get_address(&s, &addresses[0]); MPI_Get_address(&(s.gid), &addresses[1]); MPI_Get_address(&(s.spiketime), &addresses[2]); MPI_Aint displacements[2] = {addresses[1] - addresses[0], addresses[2] - addresses[0]}; MPI_Datatype typelist[2] = {MPI_INT, MPI_DOUBLE}; MPI_Type_create_struct(2, block_lengths, displacements, typelist, &spike_type); MPI_Type_commit(&spike_type); } #if nrn_spikebuf_size > 0 static MPI_Datatype spikebuf_type; // Register type NRNMPI_Spikebuf static void make_spikebuf_type() { NRNMPI_Spikebuf s; int block_lengths[3] = {1, nrn_spikebuf_size, nrn_spikebuf_size}; MPI_Datatype typelist[3] = {MPI_INT, MPI_INT, MPI_DOUBLE}; MPI_Aint addresses[4]; MPI_Get_address(&s, &addresses[0]); MPI_Get_address(&(s.nspike), &addresses[1]); MPI_Get_address(&(s.gid[0]), &addresses[2]); MPI_Get_address(&(s.spiketime[0]), &addresses[3]); MPI_Aint displacements[3] = {addresses[1] - addresses[0], addresses[2] - addresses[0], addresses[3] - addresses[0]}; MPI_Type_create_struct(3, block_lengths, displacements, typelist, &spikebuf_type); MPI_Type_commit(&spikebuf_type); } #endif void wait_before_spike_exchange() { MPI_Barrier(nrnmpi_comm); } int nrnmpi_spike_exchange_impl(int* nin, NRNMPI_Spike* spikeout, int icapacity, NRNMPI_Spike** spikein, int& ovfl, int nout, NRNMPI_Spikebuf* spbufout, NRNMPI_Spikebuf* spbufin) { nrn_assert(spikein); Instrumentor::phase_begin("spike-exchange"); { Instrumentor::phase p("imbalance"); wait_before_spike_exchange(); } Instrumentor::phase_begin("communication"); if (!displs) { np = nrnmpi_numprocs_; displs = (int*) emalloc(np * sizeof(int)); displs[0] = 0; #if nrn_spikebuf_size > 0 make_spikebuf_type(); #endif } #if nrn_spikebuf_size == 0 MPI_Allgather(&nout, 1, MPI_INT, nin, 1, MPI_INT, nrnmpi_comm); int n = nin[0]; for (int i = 1; i < np; ++i) { displs[i] = n; n += nin[i]; } if (n) { if (icapacity < n) { icapacity = n + 10; free(*spikein); *spikein = (NRNMPI_Spike*) emalloc(icapacity * sizeof(NRNMPI_Spike)); } MPI_Allgatherv(spikeout, nout, spike_type, *spikein, nin, displs, spike_type, nrnmpi_comm); } #else MPI_Allgather(spbufout, 1, spikebuf_type, spbufin, 1, spikebuf_type, nrnmpi_comm); int novfl = 0; int n = spbufin[0].nspike; if (n > nrn_spikebuf_size) { nin[0] = n - nrn_spikebuf_size; novfl += nin[0]; } else { nin[0] = 0; } for (int i = 1; i < np; ++i) { displs[i] = novfl; int n1 = spbufin[i].nspike; n += n1; if (n1 > nrn_spikebuf_size) { nin[i] = n1 - nrn_spikebuf_size; novfl += nin[i]; } else { nin[i] = 0; } } if (novfl) { if (icapacity < novfl) { icapacity = novfl + 10; free(*spikein); *spikein = (NRNMPI_Spike*) emalloc(icapacity * sizeof(NRNMPI_Spike)); } int n1 = (nout > nrn_spikebuf_size) ? nout - nrn_spikebuf_size : 0; MPI_Allgatherv(spikeout, n1, spike_type, *spikein, nin, displs, spike_type, nrnmpi_comm); } ovfl = novfl; #endif Instrumentor::phase_end("communication"); Instrumentor::phase_end("spike-exchange"); return n; } /* The compressed spike format is restricted to the fixed step method and is a sequence of unsigned char. nspike = buf[0]*256 + buf[1] a sequence of spiketime, localgid pairs. There are nspike of them. spiketime is relative to the last transfer time in units of dt. note that this requires a mindelay < 256*dt. localgid is an unsigned int, unsigned short, or unsigned char in size depending on the range and thus takes 4, 2, or 1 byte respectively. To be machine independent we do our own byte coding. When the localgid range is smaller than the true gid range, the gid->PreSyn are remapped into hostid specific maps. If there are not many holes, i.e just about every spike from a source machine is delivered to some cell on a target machine, then instead of a hash map, a vector is used. The allgather sends the first part of the buf and the allgatherv buffer sends any overflow. */ int nrnmpi_spike_exchange_compressed_impl(int localgid_size, unsigned char*& spfixin_ovfl, int send_nspike, int* nin, int ovfl_capacity, unsigned char* spikeout_fixed, int ag_send_size, unsigned char* spikein_fixed, int& ovfl) { if (!displs) { np = nrnmpi_numprocs_; displs = (int*) emalloc(np * sizeof(int)); displs[0] = 0; } if (!byteovfl) { byteovfl = (int*) emalloc(np * sizeof(int)); } MPI_Allgather( spikeout_fixed, ag_send_size, MPI_BYTE, spikein_fixed, ag_send_size, MPI_BYTE, nrnmpi_comm); int novfl = 0; int ntot = 0; int bstot = 0; for (int i = 0; i < np; ++i) { displs[i] = bstot; int idx = i * ag_send_size; int n = spikein_fixed[idx++] * 256; n += spikein_fixed[idx++]; ntot += n; nin[i] = n; if (n > send_nspike) { int bs = 2 + n * (1 + localgid_size) - ag_send_size; byteovfl[i] = bs; bstot += bs; novfl += n - send_nspike; } else { byteovfl[i] = 0; } } if (novfl) { if (ovfl_capacity < novfl) { ovfl_capacity = novfl + 10; free(spfixin_ovfl); spfixin_ovfl = (unsigned char*) emalloc(ovfl_capacity * (1 + localgid_size) * sizeof(unsigned char)); } int bs = byteovfl[nrnmpi_myid_]; /* note that the spikeout_fixed buffer is one since the overflow is contiguous to the first part. But the spfixin_ovfl is completely separate from the spikein_fixed since the latter dynamically changes its size during a run. */ MPI_Allgatherv(spikeout_fixed + ag_send_size, bs, MPI_BYTE, spfixin_ovfl, byteovfl, displs, MPI_BYTE, nrnmpi_comm); } ovfl = novfl; return ntot; } int nrnmpi_int_allmax_impl(int x) { int result; MPI_Allreduce(&x, &result, 1, MPI_INT, MPI_MAX, nrnmpi_comm); return result; } extern void nrnmpi_int_alltoall_impl(int* s, int* r, int n) { MPI_Alltoall(s, n, MPI_INT, r, n, MPI_INT, nrnmpi_comm); } extern void nrnmpi_int_alltoallv_impl(const int* s, const int* scnt, const int* sdispl, int* r, int* rcnt, int* rdispl) { MPI_Alltoallv(s, scnt, sdispl, MPI_INT, r, rcnt, rdispl, MPI_INT, nrnmpi_comm); } extern void nrnmpi_dbl_alltoallv_impl(double* s, int* scnt, int* sdispl, double* r, int* rcnt, int* rdispl) { MPI_Alltoallv(s, scnt, sdispl, MPI_DOUBLE, r, rcnt, rdispl, MPI_DOUBLE, nrnmpi_comm); } /* following are for the partrans */ void nrnmpi_int_allgather_impl(int* s, int* r, int n) { MPI_Allgather(s, n, MPI_INT, r, n, MPI_INT, nrnmpi_comm); } double nrnmpi_dbl_allmin_impl(double x) { double result; MPI_Allreduce(&x, &result, 1, MPI_DOUBLE, MPI_MIN, nrnmpi_comm); return result; } double nrnmpi_dbl_allmax_impl(double x) { double result; MPI_Allreduce(&x, &result, 1, MPI_DOUBLE, MPI_MAX, nrnmpi_comm); return result; } void nrnmpi_barrier_impl() { MPI_Barrier(nrnmpi_comm); } double nrnmpi_dbl_allreduce_impl(double x, int type) { double result; MPI_Op tt; if (type == 1) { tt = MPI_SUM; } else if (type == 2) { tt = MPI_MAX; } else { tt = MPI_MIN; } MPI_Allreduce(&x, &result, 1, MPI_DOUBLE, tt, nrnmpi_comm); return result; } void nrnmpi_dbl_allreduce_vec_impl(double* src, double* dest, int cnt, int type) { MPI_Op tt; assert(src != dest); if (type == 1) { tt = MPI_SUM; } else if (type == 2) { tt = MPI_MAX; } else { tt = MPI_MIN; } MPI_Allreduce(src, dest, cnt, MPI_DOUBLE, tt, nrnmpi_comm); return; } void nrnmpi_long_allreduce_vec_impl(long* src, long* dest, int cnt, int type) { MPI_Op tt; assert(src != dest); if (type == 1) { tt = MPI_SUM; } else if (type == 2) { tt = MPI_MAX; } else { tt = MPI_MIN; } MPI_Allreduce(src, dest, cnt, MPI_LONG, tt, nrnmpi_comm); return; } #if NRN_MULTISEND static MPI_Comm multisend_comm; void nrnmpi_multisend_comm_impl() { if (!multisend_comm) { MPI_Comm_dup(MPI_COMM_WORLD, &multisend_comm); } } void nrnmpi_multisend_impl(NRNMPI_Spike* spk, int n, int* hosts) { //dong { Instrumentor::phase p("nrnmpi_multisend"); MPI_Request r; for (int i = 0; i < n; ++i) { MPI_Isend(spk, 1, spike_type, hosts[i], 1, multisend_comm, &r); MPI_Request_free(&r); } } } //dong void nrnmpi_multisend_impl_j(NRNMPI_Spike* spk, int n, int* hosts, MPI_Comm* pcomm) { { Instrumentor::phase p("nrnmpi_multisend"); MPI_Request r; for (int i = 0; i < n; ++i) { MPI_Isend(spk, 1, spike_type, hosts[i], 1, *pcomm, &r); MPI_Request_free(&r); } } } int nrnmpi_multisend_single_advance_impl(NRNMPI_Spike* spk) { int flag = 0; //dong { Instrumentor::phase p("nrnmpi_multisend_advance"); MPI_Status status; MPI_Iprobe(MPI_ANY_SOURCE, 1, multisend_comm, &flag, &status); if (flag) { MPI_Recv(spk, 1, spike_type, MPI_ANY_SOURCE, 1, multisend_comm, &status); } } return flag; } //dong int nrnmpi_multisend_single_advance_impl_j(NRNMPI_Spike* spk, MPI_Comm* pcomm) { int flag = 0; { Instrumentor::phase p("nrnmpi_multisend_advance_j"); MPI_Status status; MPI_Iprobe(MPI_ANY_SOURCE, 1, *pcomm, &flag, &status); if (flag) { MPI_Recv(spk, 1, spike_type, MPI_ANY_SOURCE, 1, *pcomm, &status); } } return flag; } int nrnmpi_multisend_conserve_impl(int nsend, int nrecv) { int tcnts[2]; tcnts[0] = nsend - nrecv; MPI_Allreduce(tcnts, tcnts + 1, 1, MPI_INT, MPI_SUM, multisend_comm); return tcnts[1]; } //dong int nrnmpi_multisend_conserve_impl_j(int nsend, int nrecv, MPI_Comm* pcomm) { int tcnts[2]; tcnts[0] = nsend - nrecv; MPI_Allreduce(tcnts, tcnts + 1, 1, MPI_INT, MPI_SUM, *pcomm); return tcnts[1]; } #endif /*NRN_MULTISEND*/ } // namespace coreneuron
30.673123
100
0.570019
phoenixdong
0c8cffd5adea2a57dd600d70f915d4de39410f54
4,060
cpp
C++
DT3Core/Types/Memory/MemoryAllocatorTrace_cmd.cpp
9heart/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
3
2018-10-05T15:03:27.000Z
2019-03-19T11:01:56.000Z
DT3Core/Types/Memory/MemoryAllocatorTrace_cmd.cpp
pakoito/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
1
2016-01-28T14:39:49.000Z
2016-01-28T22:12:07.000Z
DT3Core/Types/Memory/MemoryAllocatorTrace_cmd.cpp
adderly/DT3
e2605be091ec903d3582e182313837cbaf790857
[ "MIT" ]
3
2016-01-25T16:44:51.000Z
2021-01-29T19:59:45.000Z
//============================================================================== /// /// File: MemoryAllocatorTrace_cmd.cpp /// /// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved. /// /// This file is subject to the terms and conditions defined in /// file 'LICENSE.txt', which is part of this source code package. /// //============================================================================== #include "DT3Core/System/Command.hpp" #ifdef DT3_COMMANDS #include "DT3Core/System/Factory.hpp" #include "DT3Core/Types/Utility/CommandResult.hpp" #include "DT3Core/Types/Utility/CommandRegistry.hpp" #include "DT3Core/Types/Utility/CommandContext.hpp" #include "DT3Core/Types/Memory/MemoryAllocatorTrace.hpp" //============================================================================== //============================================================================== namespace DT3 { //============================================================================== //============================================================================== class MemoryAllocatorTrace_cmd: public Command { public: DEFINE_TYPE(MemoryAllocatorTrace_cmd,Command); DEFINE_CREATE void register_commands (void) { CommandRegistry::register_command("CheckMemory", &MemoryAllocatorTrace_cmd::do_check_memory); CommandRegistry::register_command("EnableCheckMemory", &MemoryAllocatorTrace_cmd::do_enable_check_memory); CommandRegistry::register_command("DisableCheckMemory", &MemoryAllocatorTrace_cmd::do_disable_check_memory); } static CommandResult do_check_memory (CommandContext &ctx, const CommandParams &p); static CommandResult do_enable_check_memory (CommandContext &ctx, const CommandParams &p); static CommandResult do_disable_check_memory (CommandContext &ctx, const CommandParams &p); }; //============================================================================== //============================================================================== IMPLEMENT_FACTORY_COMMAND(MemoryAllocatorTrace_cmd) //============================================================================== //============================================================================== CommandResult MemoryAllocatorTrace_cmd::do_check_memory (CommandContext &ctx, const CommandParams &p) { if (p.count() != 1) { return CommandResult(false, "Usage: CheckMemory", CommandResult::UPDATE_NONE); } MemoryAllocatorTrace::check_allocations(); return CommandResult(false, "CheckMemory Done", CommandResult::UPDATE_NONE); } //============================================================================== //============================================================================== CommandResult MemoryAllocatorTrace_cmd::do_enable_check_memory (CommandContext &ctx, const CommandParams &p) { if (p.count() != 1) { return CommandResult(false, "Usage: EnableCheckMemory", CommandResult::UPDATE_NONE); } MemoryAllocatorTrace::enable_check_allocations(true); return CommandResult(false, "Check Memory Enabled", CommandResult::UPDATE_NONE); } //============================================================================== //============================================================================== CommandResult MemoryAllocatorTrace_cmd::do_disable_check_memory (CommandContext &ctx, const CommandParams &p) { if (p.count() != 1) { return CommandResult(false, "Usage: DisableCheckMemory", CommandResult::UPDATE_NONE); } MemoryAllocatorTrace::enable_check_allocations(false); return CommandResult(false, "Check Memory Disabled", CommandResult::UPDATE_NONE); } //============================================================================== //============================================================================== } // DT3 #endif // DT3_COMMANDS
40.6
121
0.49064
9heart
0c8d96aae7fbd43d7a47a981380ec77c14b8fd2b
819
cpp
C++
src/code-examples/chapter-03/older-than-generic/main.cpp
nhatvu148/helpers
1a6875017cf39790dfe40ecec9dcee4410b1d89e
[ "MIT" ]
null
null
null
src/code-examples/chapter-03/older-than-generic/main.cpp
nhatvu148/helpers
1a6875017cf39790dfe40ecec9dcee4410b1d89e
[ "MIT" ]
null
null
null
src/code-examples/chapter-03/older-than-generic/main.cpp
nhatvu148/helpers
1a6875017cf39790dfe40ecec9dcee4410b1d89e
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include "../../common/person.h" // Implements a generic function object that compares an object's age // against a predefined integer limit (section 3.1.4) class older_than { public: older_than(int limit) : m_limit(limit) { } // Defining a call operator as a template function, // we will create a generic function object // that deduces the type of its argument when invoked template <typename T> bool operator() (T &&object) const { return std::forward<T>(object).age() > m_limit; } private: int m_limit; }; int main(int argc, char *argv[]) { std::vector<person_t> persons; older_than predicate(42); std::count_if(persons.cbegin(), persons.cend(), predicate); return 0; }
19.97561
69
0.654457
nhatvu148
0c905f8209cd7f77de147527063813523e9fe606
4,602
cc
C++
src/libcsg/modules/io/gmxtrajectoryreader.cc
vaidyanathanms/votca.csg
7af91bfecd620b820968956cd96ce7b3bce28a59
[ "Apache-2.0" ]
null
null
null
src/libcsg/modules/io/gmxtrajectoryreader.cc
vaidyanathanms/votca.csg
7af91bfecd620b820968956cd96ce7b3bce28a59
[ "Apache-2.0" ]
null
null
null
src/libcsg/modules/io/gmxtrajectoryreader.cc
vaidyanathanms/votca.csg
7af91bfecd620b820968956cd96ce7b3bce28a59
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2009-2011 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. * */ #include <cstdlib> #include <iostream> #include <votca/csg/topology.h> #include "gmxtrajectoryreader.h" namespace votca { namespace csg { using namespace std; bool GMXTrajectoryReader::Open(const string &file) { _filename = file; return true; } void GMXTrajectoryReader::Close() { close_trx(_gmx_status); } bool GMXTrajectoryReader::FirstFrame(Topology &conf) { #if GMX == 50 output_env_t oenv; // _snew("oenv", oenv, 1); //oenv = (output_env_t)malloc(sizeof(*oenv)); output_env_init_default (&oenv); if(!read_first_frame(oenv, &_gmx_status,(char*)_filename.c_str(),&_gmx_frame,TRX_READ_X | TRX_READ_V | TRX_READ_F)) throw std::runtime_error(string("cannot open ") + _filename); //sfree(oenv); free(oenv); #elif GMX == 45 set_program_name("VOTCA"); output_env_t oenv; // _snew("oenv", oenv, 1); oenv = (output_env_t)malloc(sizeof(*oenv)); output_env_init_default (oenv); if(!read_first_frame(oenv, &_gmx_status,(char*)_filename.c_str(),&_gmx_frame,TRX_READ_X | TRX_READ_V | TRX_READ_F)) throw std::runtime_error(string("cannot open ") + _filename); //sfree(oenv); free(oenv); #elif GMX == 40 set_program_name("VOTCA"); if(!read_first_frame(&_gmx_status,(char*)_filename.c_str(),&_gmx_frame,TRX_READ_X | TRX_READ_V | TRX_READ_F)) throw std::runtime_error(string("cannot open ") + _filename); #else #error Unsupported GMX version #endif matrix m; for(int i=0; i<3; i++) for(int j=0; j<3; j++) m[i][j] = _gmx_frame.box[j][i]; conf.setBox(m); conf.setTime(_gmx_frame.time); conf.setStep(_gmx_frame.step); cout << endl; if(_gmx_frame.natoms != (int)conf.Beads().size()) throw std::runtime_error("number of beads in trajectory do not match topology"); //conf.HasPos(true); //conf.HasF(_gmx_frame.bF); for(int i=0; i<_gmx_frame.natoms; i++) { double r[3] = { _gmx_frame.x[i][XX], _gmx_frame.x[i][YY], _gmx_frame.x[i][ZZ] }; conf.getBead(i)->setPos(r); if(_gmx_frame.bF) { double f[3] = { _gmx_frame.f[i][XX], _gmx_frame.f[i][YY], _gmx_frame.f[i][ZZ] }; conf.getBead(i)->setF(f); } if(_gmx_frame.bV) { double v[3] = { _gmx_frame.v[i][XX], _gmx_frame.v[i][YY], _gmx_frame.v[i][ZZ] }; conf.getBead(i)->setVel(v); } } return true; } bool GMXTrajectoryReader::NextFrame(Topology &conf) { #if GMX == 50 output_env_t oenv; //_snew("oenv", oenv, 1); //oenv = (output_env_t)malloc(sizeof(*oenv)); output_env_init_default (&oenv); if(!read_next_frame(oenv, _gmx_status,&_gmx_frame)) return false; //sfree(oenv); free(oenv); #elif GMX == 45 output_env_t oenv; //_snew("oenv", oenv, 1); oenv = (output_env_t)malloc(sizeof(*oenv)); output_env_init_default (oenv); if(!read_next_frame(oenv, _gmx_status,&_gmx_frame)) return false; //sfree(oenv); free(oenv); #elif GMX == 40 if(!read_next_frame(_gmx_status,&_gmx_frame)) return false; #else #error Unsupported GMX version #endif matrix m; for(int i=0; i<3; i++) for(int j=0; j<3; j++) m[i][j] = _gmx_frame.box[j][i]; conf.setTime(_gmx_frame.time); conf.setStep(_gmx_frame.step); conf.setBox(m); //conf.HasF(_gmx_frame.bF); for(int i=0; i<_gmx_frame.natoms; i++) { double r[3] = { _gmx_frame.x[i][XX], _gmx_frame.x[i][YY], _gmx_frame.x[i][ZZ] }; conf.getBead(i)->setPos(r); if(_gmx_frame.bF) { double f[3] = { _gmx_frame.f[i][XX], _gmx_frame.f[i][YY], _gmx_frame.f[i][ZZ] }; conf.getBead(i)->setF(f); } if(_gmx_frame.bV) { double v[3] = { _gmx_frame.v[i][XX], _gmx_frame.v[i][YY], _gmx_frame.v[i][ZZ] }; conf.getBead(i)->setVel(v); } } return true; } }}
29.312102
119
0.621034
vaidyanathanms
0c90e44a1b102be19e5d567dc399cda681777307
13,031
cc
C++
chrome/browser/apps/app_window_interactive_uitest.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-16T03:57:28.000Z
2021-01-23T15:29:45.000Z
chrome/browser/apps/app_window_interactive_uitest.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/apps/app_window_interactive_uitest.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2017-03-15T13:21:38.000Z
2017-03-15T13:21:38.000Z
// Copyright 2013 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 "apps/ui/native_app_window.h" #include "chrome/browser/apps/app_browsertest_util.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/test/base/interactive_test_utils.h" #if defined(OS_MACOSX) && !defined(OS_IOS) #include "base/mac/mac_util.h" #endif using apps::NativeAppWindow; // Helper class that has to be created in the stack to check if the fullscreen // setting of a NativeWindow has changed since the creation of the object. class FullscreenChangeWaiter { public: explicit FullscreenChangeWaiter(NativeAppWindow* window) : window_(window), initial_fullscreen_state_(window_->IsFullscreen()) {} void Wait() { while (initial_fullscreen_state_ == window_->IsFullscreen()) content::RunAllPendingInMessageLoop(); } private: NativeAppWindow* window_; bool initial_fullscreen_state_; DISALLOW_COPY_AND_ASSIGN(FullscreenChangeWaiter); }; class AppWindowInteractiveTest : public extensions::PlatformAppBrowserTest { public: bool RunAppWindowInteractiveTest(const char* testName) { ExtensionTestMessageListener launched_listener("Launched", true); LoadAndLaunchPlatformApp("window_api_interactive"); if (!launched_listener.WaitUntilSatisfied()) { message_ = "Did not get the 'Launched' message."; return false; } ResultCatcher catcher; launched_listener.Reply(testName); if (!catcher.GetNextResult()) { message_ = catcher.message(); return false; } return true; } bool SimulateKeyPress(ui::KeyboardCode key) { return ui_test_utils::SendKeyPressToWindowSync( GetFirstAppWindow()->GetNativeWindow(), key, false, false, false, false); } // This method will wait until the application is able to ack a key event. void WaitUntilKeyFocus() { ExtensionTestMessageListener key_listener("KeyReceived", false); while (!key_listener.was_satisfied()) { ASSERT_TRUE(SimulateKeyPress(ui::VKEY_Z)); content::RunAllPendingInMessageLoop(); } } }; IN_PROC_BROWSER_TEST_F(AppWindowInteractiveTest, ESCLeavesFullscreenWindow) { // This test is flaky on MacOS 10.6. #if defined(OS_MACOSX) && !defined(OS_IOS) if (base::mac::IsOSSnowLeopard()) return; #endif ExtensionTestMessageListener launched_listener("Launched", true); LoadAndLaunchPlatformApp("leave_fullscreen"); ASSERT_TRUE(launched_listener.WaitUntilSatisfied()); // We start by making sure the window is actually focused. ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow( GetFirstAppWindow()->GetNativeWindow())); // When receiving the reply, the application will try to go fullscreen using // the Window API but there is no synchronous way to know if that actually // succeeded. Also, failure will not be notified. A failure case will only be // known with a timeout. { FullscreenChangeWaiter fs_changed(GetFirstAppWindow()->GetBaseWindow()); launched_listener.Reply("window"); fs_changed.Wait(); } // Depending on the platform, going fullscreen might create an animation. // We want to make sure that the ESC key we will send next is actually going // to be received and the application might not receive key events during the // animation so we should wait for the key focus to be back. WaitUntilKeyFocus(); // Same idea as above but for leaving fullscreen. Fullscreen mode should be // left when ESC is received. { FullscreenChangeWaiter fs_changed(GetFirstAppWindow()->GetBaseWindow()); ASSERT_TRUE(SimulateKeyPress(ui::VKEY_ESCAPE)); fs_changed.Wait(); } } IN_PROC_BROWSER_TEST_F(AppWindowInteractiveTest, ESCLeavesFullscreenDOM) { // This test is flaky on MacOS 10.6. #if defined(OS_MACOSX) && !defined(OS_IOS) if (base::mac::IsOSSnowLeopard()) return; #endif ExtensionTestMessageListener launched_listener("Launched", true); LoadAndLaunchPlatformApp("leave_fullscreen"); ASSERT_TRUE(launched_listener.WaitUntilSatisfied()); // We start by making sure the window is actually focused. ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow( GetFirstAppWindow()->GetNativeWindow())); launched_listener.Reply("dom"); // Because the DOM way to go fullscreen requires user gesture, we simulate a // key event to get the window entering in fullscreen mode. The reply will // make the window listen for the key event. The reply will be sent to the // renderer process before the keypress and should be received in that order. // When receiving the key event, the application will try to go fullscreen // using the Window API but there is no synchronous way to know if that // actually succeeded. Also, failure will not be notified. A failure case will // only be known with a timeout. { FullscreenChangeWaiter fs_changed(GetFirstAppWindow()->GetBaseWindow()); WaitUntilKeyFocus(); ASSERT_TRUE(SimulateKeyPress(ui::VKEY_A)); fs_changed.Wait(); } // Depending on the platform, going fullscreen might create an animation. // We want to make sure that the ESC key we will send next is actually going // to be received and the application might not receive key events during the // animation so we should wait for the key focus to be back. WaitUntilKeyFocus(); // Same idea as above but for leaving fullscreen. Fullscreen mode should be // left when ESC is received. { FullscreenChangeWaiter fs_changed(GetFirstAppWindow()->GetBaseWindow()); ASSERT_TRUE(SimulateKeyPress(ui::VKEY_ESCAPE)); fs_changed.Wait(); } } IN_PROC_BROWSER_TEST_F(AppWindowInteractiveTest, ESCDoesNotLeaveFullscreenWindow) { // This test is flaky on MacOS 10.6. #if defined(OS_MACOSX) && !defined(OS_IOS) if (base::mac::IsOSSnowLeopard()) return; #endif ExtensionTestMessageListener launched_listener("Launched", true); LoadAndLaunchPlatformApp("prevent_leave_fullscreen"); ASSERT_TRUE(launched_listener.WaitUntilSatisfied()); // We start by making sure the window is actually focused. ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow( GetFirstAppWindow()->GetNativeWindow())); // When receiving the reply, the application will try to go fullscreen using // the Window API but there is no synchronous way to know if that actually // succeeded. Also, failure will not be notified. A failure case will only be // known with a timeout. { FullscreenChangeWaiter fs_changed(GetFirstAppWindow()->GetBaseWindow()); launched_listener.Reply("window"); fs_changed.Wait(); } // Depending on the platform, going fullscreen might create an animation. // We want to make sure that the ESC key we will send next is actually going // to be received and the application might not receive key events during the // animation so we should wait for the key focus to be back. WaitUntilKeyFocus(); ASSERT_TRUE(SimulateKeyPress(ui::VKEY_ESCAPE)); ExtensionTestMessageListener second_key_listener("B_KEY_RECEIVED", false); ASSERT_TRUE(SimulateKeyPress(ui::VKEY_B)); ASSERT_TRUE(second_key_listener.WaitUntilSatisfied()); // We assume that at that point, if we had to leave fullscreen, we should be. // However, by nature, we can not guarantee that and given that we do test // that nothing happens, we might end up with random-success when the feature // is broken. EXPECT_TRUE(GetFirstAppWindow()->GetBaseWindow()->IsFullscreen()); } IN_PROC_BROWSER_TEST_F(AppWindowInteractiveTest, ESCDoesNotLeaveFullscreenDOM) { // This test is flaky on MacOS 10.6. #if defined(OS_MACOSX) && !defined(OS_IOS) if (base::mac::IsOSSnowLeopard()) return; #endif ExtensionTestMessageListener launched_listener("Launched", true); LoadAndLaunchPlatformApp("prevent_leave_fullscreen"); ASSERT_TRUE(launched_listener.WaitUntilSatisfied()); // We start by making sure the window is actually focused. ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow( GetFirstAppWindow()->GetNativeWindow())); launched_listener.Reply("dom"); // Because the DOM way to go fullscreen requires user gesture, we simulate a // key event to get the window entering in fullscreen mode. The reply will // make the window listen for the key event. The reply will be sent to the // renderer process before the keypress and should be received in that order. // When receiving the key event, the application will try to go fullscreen // using the Window API but there is no synchronous way to know if that // actually succeeded. Also, failure will not be notified. A failure case will // only be known with a timeout. { FullscreenChangeWaiter fs_changed(GetFirstAppWindow()->GetBaseWindow()); WaitUntilKeyFocus(); ASSERT_TRUE(SimulateKeyPress(ui::VKEY_A)); fs_changed.Wait(); } // Depending on the platform, going fullscreen might create an animation. // We want to make sure that the ESC key we will send next is actually going // to be received and the application might not receive key events during the // animation so we should wait for the key focus to be back. WaitUntilKeyFocus(); ASSERT_TRUE(SimulateKeyPress(ui::VKEY_ESCAPE)); ExtensionTestMessageListener second_key_listener("B_KEY_RECEIVED", false); ASSERT_TRUE(SimulateKeyPress(ui::VKEY_B)); ASSERT_TRUE(second_key_listener.WaitUntilSatisfied()); // We assume that at that point, if we had to leave fullscreen, we should be. // However, by nature, we can not guarantee that and given that we do test // that nothing happens, we might end up with random-success when the feature // is broken. EXPECT_TRUE(GetFirstAppWindow()->GetBaseWindow()->IsFullscreen()); } // This test is duplicated from ESCDoesNotLeaveFullscreenWindow. // It runs the same test, but uses the old permission names: 'fullscreen' // and 'overrideEscFullscreen'. IN_PROC_BROWSER_TEST_F(AppWindowInteractiveTest, ESCDoesNotLeaveFullscreenOldPermission) { // This test is flaky on MacOS 10.6. #if defined(OS_MACOSX) && !defined(OS_IOS) if (base::mac::IsOSSnowLeopard()) return; #endif ExtensionTestMessageListener launched_listener("Launched", true); LoadAndLaunchPlatformApp("prevent_leave_fullscreen_old"); ASSERT_TRUE(launched_listener.WaitUntilSatisfied()); // We start by making sure the window is actually focused. ASSERT_TRUE(ui_test_utils::ShowAndFocusNativeWindow( GetFirstAppWindow()->GetNativeWindow())); // When receiving the reply, the application will try to go fullscreen using // the Window API but there is no synchronous way to know if that actually // succeeded. Also, failure will not be notified. A failure case will only be // known with a timeout. { FullscreenChangeWaiter fs_changed(GetFirstAppWindow()->GetBaseWindow()); launched_listener.Reply("window"); fs_changed.Wait(); } // Depending on the platform, going fullscreen might create an animation. // We want to make sure that the ESC key we will send next is actually going // to be received and the application might not receive key events during the // animation so we should wait for the key focus to be back. WaitUntilKeyFocus(); ASSERT_TRUE(SimulateKeyPress(ui::VKEY_ESCAPE)); ExtensionTestMessageListener second_key_listener("B_KEY_RECEIVED", false); ASSERT_TRUE(SimulateKeyPress(ui::VKEY_B)); ASSERT_TRUE(second_key_listener.WaitUntilSatisfied()); // We assume that at that point, if we had to leave fullscreen, we should be. // However, by nature, we can not guarantee that and given that we do test // that nothing happens, we might end up with random-success when the feature // is broken. EXPECT_TRUE(GetFirstAppWindow()->GetBaseWindow()->IsFullscreen()); } // This test does not work on Linux Aura because ShowInactive() is not // implemented. See http://crbug.com/325142 // It also does not work on Windows because of the document being focused even // though the window is not activated. See http://crbug.com/326986 // It also does not work on MacOS because ::ShowInactive() ends up behaving like // ::Show() because of Cocoa conventions. See http://crbug.com/326987 // Those tests should be disabled on Linux GTK when they are enabled on the // other platforms, see http://crbug.com/328829 #if (defined(OS_LINUX) && defined(USE_AURA)) || \ defined(OS_WIN) || defined(OS_MACOSX) #define MAYBE_TestCreate DISABLED_TestCreate #define MAYBE_TestShow DISABLED_TestShow #else #define MAYBE_TestCreate TestCreate #define MAYBE_TestShow TestShow #endif IN_PROC_BROWSER_TEST_F(AppWindowInteractiveTest, MAYBE_TestCreate) { ASSERT_TRUE(RunAppWindowInteractiveTest("testCreate")) << message_; } IN_PROC_BROWSER_TEST_F(AppWindowInteractiveTest, MAYBE_TestShow) { ASSERT_TRUE(RunAppWindowInteractiveTest("testShow")) << message_; }
36.810734
80
0.748216
shaochangbin
0c928b303e37355e440d17473b650eb8e5eed183
728
cpp
C++
394. Decode String.cpp
dipta007/leetcode-solutions-dipta007
0454ad24ce686a37fab8025c75efb7d857985f29
[ "MIT" ]
null
null
null
394. Decode String.cpp
dipta007/leetcode-solutions-dipta007
0454ad24ce686a37fab8025c75efb7d857985f29
[ "MIT" ]
null
null
null
394. Decode String.cpp
dipta007/leetcode-solutions-dipta007
0454ad24ce686a37fab8025c75efb7d857985f29
[ "MIT" ]
null
null
null
class Solution { public: string decodeString(string s) { int i = 0; return decode(s, i); } string decode(string &s, int &i) { string res = ""; while(i < s.size() && s[i] != ']') { if(!isdigit(s[i])) { res += s[i]; i++; } else { int n = 0; while(s[i] != '[') { n = n*10 + (s[i] - '0'); i++; } i++; string mid = decode(s, i); i++; while(n--) res += mid; } } return res; } };
22.75
44
0.259615
dipta007
0c9393362bdc1167bcb1477e53f488fbeb0a6185
1,228
hpp
C++
ql/experimental/templatemodels/qgaussian/quasigaussianmodels.hpp
sschlenkrich/quantlib
ff39ad2cd03d06d185044976b2e26ce34dca470c
[ "BSD-3-Clause" ]
null
null
null
ql/experimental/templatemodels/qgaussian/quasigaussianmodels.hpp
sschlenkrich/quantlib
ff39ad2cd03d06d185044976b2e26ce34dca470c
[ "BSD-3-Clause" ]
null
null
null
ql/experimental/templatemodels/qgaussian/quasigaussianmodels.hpp
sschlenkrich/quantlib
ff39ad2cd03d06d185044976b2e26ce34dca470c
[ "BSD-3-Clause" ]
null
null
null
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2015 Sebastian Schlenkrich */ /*! \file quasigaussianmodels.hpp \brief bindings of templatised quasi Gaussian models */ #ifndef quantlib_templatequasigaussianmodels_hpp #define quantlib_templatequasigaussianmodels_hpp //#include <ql/experimental/templatehullwhite/adtageo/adtageo.hpp> //#include <ql/experimental/template/auxilliaries/MinimADVariable2.hpp> #include <ql/types.hpp> #include <ql/experimental/templatemodels/qgaussian/quasigaussianmodelT.hpp> #include <ql/experimental/templatemodels/qgaussian/quasigaussianmodelabcdT.hpp> #include <ql/experimental/templatemodels/stochasticprocessT.hpp> #include <ql/experimental/templatemodels/qgaussian/qgswaptionmodelT.hpp> namespace QuantLib { // basic binding of template parameters typedef QuasiGaussianModelT<QuantLib::Time,QuantLib::Real,QuantLib::Real> RealQuasiGaussianModel; typedef QuasiGaussianModelAbcdT<QuantLib::Time,QuantLib::Real,QuantLib::Real> RealQuasiGaussianModelAbcd; typedef QGSwaptionModelT<QuantLib::Time,QuantLib::Real,QuantLib::Real> RealQGSwaptionModel; } #endif /* ifndef quantlib_templatequasigaussianmodels_hpp */
32.315789
109
0.799674
sschlenkrich
0c9521897262d9164e59b3b4f96b28ec67f3f7b2
640
cpp
C++
JAL/PAT/Advanced/1001.cpp
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
14
2018-06-21T14:41:26.000Z
2021-12-19T14:43:51.000Z
JAL/PAT/Advanced/1001.cpp
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
null
null
null
JAL/PAT/Advanced/1001.cpp
webturing/CPlusPlus
6b9c671b0c9a7c0d24d937610bf54e9aec9a5a1f
[ "AFL-2.0" ]
2
2020-04-20T11:16:53.000Z
2021-01-02T15:58:35.000Z
#include <bits/stdc++.h> using namespace std; int main() { for (int a, b; cin >> a >> b;) { int c = a + b; if (c == 0) { cout << 0 << endl; continue; } if (c < 0) { cout << "-"; c *= -1; } vector<int> d; for (; c; c = c / 1000) d.push_back(c % 1000); for (int i = d.size() - 1; i >= 0; i--) { if (i < d.size() - 1) cout << setw(3) << setfill('0') << d[i]; else cout << d[i]; if (i > 0) cout << ","; } cout << endl; } return 0; }
21.333333
56
0.315625
webturing
0c974dee941b748e38c15e52c5fc5a2e1a0767e4
736
hpp
C++
Boss/Msg/InternetOnline.hpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
108
2020-10-01T17:12:40.000Z
2022-03-30T09:18:03.000Z
Boss/Msg/InternetOnline.hpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
94
2020-10-03T13:40:30.000Z
2022-03-30T09:18:00.000Z
Boss/Msg/InternetOnline.hpp
3nprob/clboss
0435b6c074347ce82e490a5988534054e9d7348d
[ "MIT" ]
17
2020-10-29T13:27:59.000Z
2022-03-18T13:05:03.000Z
#ifndef BOSS_MSG_INTERNETONLINE_HPP #define BOSS_MSG_INTERNETONLINE_HPP namespace Boss { namespace Msg { /** struct Boss::Msg::InternetOnline * * @brief signals to everyone whether we are * online or not. * * @desc Broadcast whenever online-ness changes. * * At startup, we are considered offline, so the * first `Boss::Msg::InternetOnline` would have * `online` as `true`. * Conversely, if you are tracking this in your * module, you can initialize your module to * assume offline-ness, and once we do our * initial online check the * `Boss::Msg::InternetOnline` will update your * module if we are online after all. */ struct InternetOnline { bool online; }; }} #endif /* !defined(BOSS_MSG_INTERNETONLINE_HPP) */
24.533333
50
0.72962
3nprob
0c9db9d12b014c7979509253de89fe62165bbc01
5,998
cc
C++
libartpalette/system/palette_android.cc
Paschalis/android-llvm
317f7fd4b736a0511a2273a2487915c34cf8933e
[ "Apache-2.0" ]
20
2021-06-24T16:38:42.000Z
2022-01-20T16:15:57.000Z
libartpalette/system/palette_android.cc
Paschalis/android-llvm
317f7fd4b736a0511a2273a2487915c34cf8933e
[ "Apache-2.0" ]
null
null
null
libartpalette/system/palette_android.cc
Paschalis/android-llvm
317f7fd4b736a0511a2273a2487915c34cf8933e
[ "Apache-2.0" ]
4
2021-11-03T06:01:12.000Z
2022-02-24T02:57:31.000Z
/* * Copyright (C) 2019 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. */ #define ATRACE_TAG ATRACE_TAG_DALVIK #include "palette/palette.h" #include <errno.h> #include <sys/resource.h> #include <sys/time.h> #include <unistd.h> #include <mutex> #include <android-base/file.h> #include <android-base/logging.h> #include <android-base/macros.h> #include <cutils/sched_policy.h> #include <cutils/trace.h> #include <log/event_tag_map.h> #include <tombstoned/tombstoned.h> #include <utils/Thread.h> #include "palette_system.h" enum PaletteStatus PaletteGetVersion(int32_t* version) { *version = art::palette::kPaletteVersion; return PaletteStatus::kOkay; } // Conversion map for "nice" values. // // We use Android thread priority constants to be consistent with the rest // of the system. In some cases adjacent entries may overlap. // static const int kNiceValues[art::palette::kNumManagedThreadPriorities] = { ANDROID_PRIORITY_LOWEST, // 1 (MIN_PRIORITY) ANDROID_PRIORITY_BACKGROUND + 6, ANDROID_PRIORITY_BACKGROUND + 3, ANDROID_PRIORITY_BACKGROUND, ANDROID_PRIORITY_NORMAL, // 5 (NORM_PRIORITY) ANDROID_PRIORITY_NORMAL - 2, ANDROID_PRIORITY_NORMAL - 4, ANDROID_PRIORITY_URGENT_DISPLAY + 3, ANDROID_PRIORITY_URGENT_DISPLAY + 2, ANDROID_PRIORITY_URGENT_DISPLAY // 10 (MAX_PRIORITY) }; enum PaletteStatus PaletteSchedSetPriority(int32_t tid, int32_t managed_priority) { if (managed_priority < art::palette::kMinManagedThreadPriority || managed_priority > art::palette::kMaxManagedThreadPriority) { return PaletteStatus::kInvalidArgument; } int new_nice = kNiceValues[managed_priority - art::palette::kMinManagedThreadPriority]; // TODO: b/18249098 The code below is broken. It uses getpriority() as a proxy for whether a // thread is already in the SP_FOREGROUND cgroup. This is not necessarily true for background // processes, where all threads are in the SP_BACKGROUND cgroup. This means that callers will // have to call setPriority twice to do what they want : // // Thread.setPriority(Thread.MIN_PRIORITY); // no-op wrt to cgroups // Thread.setPriority(Thread.MAX_PRIORITY); // will actually change cgroups. if (new_nice >= ANDROID_PRIORITY_BACKGROUND) { set_sched_policy(tid, SP_BACKGROUND); } else if (getpriority(PRIO_PROCESS, tid) >= ANDROID_PRIORITY_BACKGROUND) { set_sched_policy(tid, SP_FOREGROUND); } if (setpriority(PRIO_PROCESS, tid, new_nice) != 0) { return PaletteStatus::kCheckErrno; } return PaletteStatus::kOkay; } enum PaletteStatus PaletteSchedGetPriority(int32_t tid, /*out*/int32_t* managed_priority) { errno = 0; int native_priority = getpriority(PRIO_PROCESS, tid); if (native_priority == -1 && errno != 0) { *managed_priority = art::palette::kNormalManagedThreadPriority; return PaletteStatus::kCheckErrno; } for (int p = art::palette::kMinManagedThreadPriority; p <= art::palette::kMaxManagedThreadPriority; p = p + 1) { int index = p - art::palette::kMinManagedThreadPriority; if (native_priority >= kNiceValues[index]) { *managed_priority = p; return PaletteStatus::kOkay; } } *managed_priority = art::palette::kMaxManagedThreadPriority; return PaletteStatus::kOkay; } enum PaletteStatus PaletteWriteCrashThreadStacks(/*in*/const char* stacks, size_t stacks_len) { android::base::unique_fd tombstone_fd; android::base::unique_fd output_fd; if (!tombstoned_connect(getpid(), &tombstone_fd, &output_fd, kDebuggerdJavaBacktrace)) { // Failure here could be due to file descriptor resource exhaustion // so write the stack trace message to the log in case it helps // debug that. LOG(INFO) << std::string_view(stacks, stacks_len); // tombstoned_connect() logs failure reason. return PaletteStatus::kFailedCheckLog; } PaletteStatus status = PaletteStatus::kOkay; if (!android::base::WriteFully(output_fd, stacks, stacks_len)) { PLOG(ERROR) << "Failed to write tombstoned output"; TEMP_FAILURE_RETRY(ftruncate(output_fd, 0)); status = PaletteStatus::kFailedCheckLog; } if (TEMP_FAILURE_RETRY(fdatasync(output_fd)) == -1 && errno != EINVAL) { // Ignore EINVAL so we don't report failure if we just tried to flush a pipe // or socket. if (status == PaletteStatus::kOkay) { PLOG(ERROR) << "Failed to fsync tombstoned output"; status = PaletteStatus::kFailedCheckLog; } TEMP_FAILURE_RETRY(ftruncate(output_fd, 0)); TEMP_FAILURE_RETRY(fdatasync(output_fd)); } if (close(output_fd.release()) == -1 && errno != EINTR) { if (status == PaletteStatus::kOkay) { PLOG(ERROR) << "Failed to close tombstoned output"; status = PaletteStatus::kFailedCheckLog; } } if (!tombstoned_notify_completion(tombstone_fd)) { // tombstoned_notify_completion() logs failure. status = PaletteStatus::kFailedCheckLog; } return status; } enum PaletteStatus PaletteTraceEnabled(/*out*/int32_t* enabled) { *enabled = (ATRACE_ENABLED() != 0) ? 1 : 0; return PaletteStatus::kOkay; } enum PaletteStatus PaletteTraceBegin(const char* name) { ATRACE_BEGIN(name); return PaletteStatus::kOkay; } enum PaletteStatus PaletteTraceEnd() { ATRACE_END(); return PaletteStatus::kOkay; } enum PaletteStatus PaletteTraceIntegerValue(const char* name, int32_t value) { ATRACE_INT(name, value); return PaletteStatus::kOkay; }
34.471264
95
0.726409
Paschalis
0ca00372f5a663200d4107b7b4c6e27988da7808
4,735
cpp
C++
src/engine/ui/box.cpp
FoxySeta/unibo-00819-programmazione-project
4475a3a64b78222cbbdeda908f18cf93e4a210be
[ "MIT" ]
3
2021-09-06T15:51:11.000Z
2021-09-08T12:30:35.000Z
src/engine/ui/box.cpp
lucat1/unibo_00819_progetto
4475a3a64b78222cbbdeda908f18cf93e4a210be
[ "MIT" ]
null
null
null
src/engine/ui/box.cpp
lucat1/unibo_00819_progetto
4475a3a64b78222cbbdeda908f18cf93e4a210be
[ "MIT" ]
2
2021-09-07T00:40:37.000Z
2021-09-08T17:34:45.000Z
/* University of Bologna First cicle degree in Computer Science 00819 - Programmazione Luca Tagliavini #971133 03/13/2021 box.cpp: Implements the Engine::UI::Box class. We mainly take care of childern placement, color assignment when drawing and focus on providing a solid base upon which other components can be built with the minimal adjustment. */ #include "box.hpp" #include "../../nostd/pair.hpp" #include "../screen.hpp" #include <algorithm> #include <exception> #include <stdexcept> Engine::UI::Box::~Box() { Box *it = first_child; while (it != nullptr) { Box *tmp = it; it = it->sibling; delete tmp; } } Engine::UI::Box *Engine::UI::Box::get_first_child() const { return first_child; } Engine::UI::Box *Engine::UI::Box::get_last_child() const { return last_child; } Engine::UI::Box *Engine::UI::Box::get_parent() const { return parent; } Engine::UI::Box *Engine::UI::Box::get_sibling() const { return sibling; } void Engine::UI::Box::add_child(Box *new_box) { if (last_child != nullptr) last_child->sibling = new_box; new_box->sibling = nullptr; new_box->parent = this; last_child = new_box; if (first_child == nullptr) first_child = new_box; } int Engine::UI::Box::color_pair() { return Screen::color_pair(fg, bg); } void Engine::UI::Box::start_color(WINDOW *window) { Screen::start_color(window, color_pair()); } void Engine::UI::Box::end_color(WINDOW *window) { Screen::end_color(window, color_pair()); } Engine::Color Engine::UI::Box::foreground() const { return short_to_color(fg); } Engine::Color Engine::UI::Box::background() const { return short_to_color(bg); } void Engine::UI::Box::propc(Box::Property key, Color color) { switch (key) { case Box::Property::foreground: fg = color_to_short(color); break; case Box::Property::background: bg = color_to_short(color); break; default: throw std::invalid_argument( "canont assign a color property with a bool/size value"); } } void Engine::UI::Box::propb(Box::Property key, bool value) { switch (key) { case Box::Property::direction_horizontal: dh = value; break; case Box::Property::float_right: fr = value; break; default: throw std::invalid_argument( "canont assign a bool property with a size/Color value"); } } void Engine::UI::Box::props(Box::Property key, szu value) { switch (key) { case Box::Property::padding_left: pl = value; break; case Box::Property::padding_right: pr = value; break; case Box::Property::padding_top: pt = value; break; case Box::Property::padding_bottom: pb = value; break; default: throw std::invalid_argument( "canont assign a size property with a bool/Color value"); } } Engine::UI::Box *Engine::UI::Box::child(size_t n) const { Box *it = first_child; while (it != nullptr && n--) { it = it->sibling; } return it; } void Engine::UI::Box::show(WINDOW *window, szu x, szu y, szu max_width, szu max_height) { start_color(window); // fill the box's space with the provided background color auto sz = size(max_width, max_height); for (szu i = 0; i < sz.second; i++) mvwhline(window, y + i, x, ' ', sz.first); // positioning and with values updated as we loop trough child rendering szu rel_x = pl, rel_y = pt, remaining_width = max_width - pl - pr, remaining_height = max_height - pt - pb; // iterate over all the children and display then in the approrpriate position for (Box *it = first_child; it != nullptr; it = it->sibling) { auto child_size = it->size(remaining_width, remaining_height); if (fr) it->show(window, x + max_width - pr - rel_x, y + rel_y, child_size.first, child_size.second); else it->show(window, x + rel_x, y + rel_y, child_size.first, child_size.second); if (dh) { rel_x += child_size.first; remaining_width -= child_size.first; } else { rel_y += child_size.second; remaining_height -= child_size.second; } } end_color(window); wnoutrefresh(window); } Engine::UI::Box::dim Engine::UI::Box::size(szu max_width, szu max_height) { szu width = 0, height = 0; for (Box *it = first_child; it != nullptr; it = it->sibling) { auto child_size = it->size(max_width - pl - pr - (dh ? width : 0), max_height - pt - pb - (dh ? 0 : height)); width = dh ? width + child_size.first : std::max(width, child_size.first); height = dh ? std::max(height, child_size.second) : height + child_size.second; } if (fr) width = max_width; szu w = width + pl + pr, h = height + pt + pb; return {w, h}; }
28.017751
80
0.644139
FoxySeta
0ca2705b802f37d31871757c064c9bf7c0034271
1,104
cpp
C++
source/main_win64gl.cpp
Basez/Agnostik-Engine
10171bbeb73c590e75e9db5adf0135e0235f2884
[ "MIT" ]
7
2015-06-29T09:45:09.000Z
2017-06-06T08:14:09.000Z
source/main_win64gl.cpp
Basez/Agnostik-Engine
10171bbeb73c590e75e9db5adf0135e0235f2884
[ "MIT" ]
null
null
null
source/main_win64gl.cpp
Basez/Agnostik-Engine
10171bbeb73c590e75e9db5adf0135e0235f2884
[ "MIT" ]
null
null
null
#include "shared.hpp" #include "application.hpp" #include "render_api_gl.hpp" #include "config_manager.hpp" #include "os_utils.hpp" #define WIN32_LEAN_AND_MEAN #include <Windows.h> using namespace AGN; int WINAPI WinMain(HINSTANCE a_hInstance, HINSTANCE a_hPrevInstance, LPSTR a_lpCmdLine, int a_nShowCmd) { UNREFERENCED_PARAMETER(a_hInstance); UNREFERENCED_PARAMETER(a_hPrevInstance); UNREFERENCED_PARAMETER(a_lpCmdLine); UNREFERENCED_PARAMETER(a_nShowCmd); // load configurations std::string currentFolder = OSUtils::getCurrentFolder(); std::string configFile = OSUtils::findFile("config.ini", currentFolder.c_str(), 3, 3); std::string rootFolder = OSUtils::getDirectoryOfPath(configFile); g_configManager.parseConfigFile(configFile); // show log output if (g_configManager.getConfigPropertyAsBool("enable_log_window")) { g_log.init(ELogTimeType::RunningTime, (uint8_t)ELoggerOutputType::Window | (uint8_t)ELoggerOutputType::OutputDebug); } IRenderAPI* renderAPI = new RenderAPIGL(); g_application.run(renderAPI); g_application.cleanup(); delete renderAPI; return 0; }
26.926829
118
0.788043
Basez
0ca616bef9af611edc84b8db2fe0f0bc671b81e0
146
cpp
C++
CWStore/CW_1/Task_3/HWTemple/HWTemple/initialization.cpp
Agesyne/HW
df9229c7f639f41ed85bae14b666bdaaf2e387b3
[ "MIT" ]
null
null
null
CWStore/CW_1/Task_3/HWTemple/HWTemple/initialization.cpp
Agesyne/HW
df9229c7f639f41ed85bae14b666bdaaf2e387b3
[ "MIT" ]
null
null
null
CWStore/CW_1/Task_3/HWTemple/HWTemple/initialization.cpp
Agesyne/HW
df9229c7f639f41ed85bae14b666bdaaf2e387b3
[ "MIT" ]
null
null
null
#include "pch.h" #include <iostream> int initNumber(char text[]) { int number = 0; printf("%s", text); scanf("%d", &number); return number; }
14.6
27
0.630137
Agesyne
0cab511c4195433c83ee5f153225ccf564c6fdcb
20,030
cpp
C++
GMan Map Maker/Unit2.cpp
JustoSenka/GMan-RPG-Game
d54f10093814fef7908e63f8419bd3fe59694d5d
[ "MIT" ]
null
null
null
GMan Map Maker/Unit2.cpp
JustoSenka/GMan-RPG-Game
d54f10093814fef7908e63f8419bd3fe59694d5d
[ "MIT" ]
null
null
null
GMan Map Maker/Unit2.cpp
JustoSenka/GMan-RPG-Game
d54f10093814fef7908e63f8419bd3fe59694d5d
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include <SysUtils.hpp> // If exist command here #include "Unit2.h" #include "Unit1.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TForm2 *Form2; //--------------------------------------------------------------------------- __fastcall TForm2::TForm2(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TForm2::FormShow(TObject *Sender) { // Items IList->Clear(); for (int i = 1; i <= Form1->itemnum; i++) IList->Items->Add(Form1->I[i].name); // Enemies EList->Clear(); for (int i = 1; i <= Form1->entypenum; i++) EList->Items->Add(Form1->E[i].name); } //--------------------------------------------------------------------------- void __fastcall TForm2::IListClick(TObject *Sender) { if (IList->ItemIndex > -1) { lvl->Text = Form1->I[IList->ItemIndex + 1].lvl; att->Text = Form1->I[IList->ItemIndex + 1].att; def->Text = Form1->I[IList->ItemIndex + 1].def; dem->Text = Form1->I[IList->ItemIndex + 1].demage; price->Text = Form1->I[IList->ItemIndex + 1].price; hp->Text = Form1->I[IList->ItemIndex + 1].hp; mp->Text = Form1->I[IList->ItemIndex + 1].mp; sta->Text = Form1->I[IList->ItemIndex + 1].sta; name->Text = Form1->I[IList->ItemIndex + 1].name; selicon = Form1->I[IList->ItemIndex + 1].icon; TypeCombo->ItemIndex = Form1->I[IList->ItemIndex + 1].type; Image->Picture->Bitmap = Items[selicon]; //Image->Picture->LoadFromFile("Items\\I" + IntToStr(selicon) + ".bmp"); } TypeComboChange(Sender); } //--------------------------------------------------------------------------- void __fastcall TForm2::TypeComboChange(TObject *Sender) { lvl->Enabled = true; att->Enabled = true; def->Enabled = true; dem->Enabled = true; hp->Enabled = true; mp->Enabled = true; sta->Enabled = true; if (TypeCombo->ItemIndex == 0) { lvl->Enabled = false; lvl->Text = 0; att->Enabled = false; att->Text = 0; def->Enabled = false; def->Text = 0; dem->Enabled = false; dem->Text = 0; hp->Enabled = false; hp->Text = 0; mp->Enabled = false; mp->Text = 0; sta->Enabled = false; sta->Text = 0; } if (TypeCombo->ItemIndex == 10) { lvl->Enabled = false; lvl->Text = 0; att->Enabled = false; att->Text = 0; def->Enabled = false; def->Text = 0; dem->Enabled = false; dem->Text = 0; } } //--------------------------------------------------------------------------- void __fastcall TForm2::addClick(TObject *Sender) { Form1->itemnum++; Form1->I[Form1->itemnum].lvl = StrToInt(lvl->Text); Form1->I[Form1->itemnum].att = StrToInt(att->Text); Form1->I[Form1->itemnum].def = StrToInt(def->Text); Form1->I[Form1->itemnum].demage = StrToInt(dem->Text); Form1->I[Form1->itemnum].price = StrToInt(price->Text); Form1->I[Form1->itemnum].hp = StrToInt(hp->Text); Form1->I[Form1->itemnum].mp = StrToInt(mp->Text); Form1->I[Form1->itemnum].sta = StrToInt(sta->Text); Form1->I[Form1->itemnum].type = TypeCombo->ItemIndex; Form1->I[Form1->itemnum].name = name->Text; Form1->I[Form1->itemnum].icon = selicon; IList->Items->Add(Form1->I[Form1->itemnum].name); IList->ItemIndex = Form1->itemnum - 1; } //--------------------------------------------------------------------------- void __fastcall TForm2::delClick(TObject *Sender) { if (IList->ItemIndex > -1) { Form1->itemnum--; for (int h = 1; h <= Form1->entypenum; h++) if (Form1->E[h].item[IList->ItemIndex + 1] != 0) Form1->E[h].idropc--; for (int i = IList->ItemIndex + 1; i <= Form1->itemnum; i++) { // Delete stats for items Form1->I[i].lvl = Form1->I[i+1].lvl; Form1->I[i].att = Form1->I[i+1].att; Form1->I[i].def = Form1->I[i+1].def; Form1->I[i].demage = Form1->I[i+1].demage; Form1->I[i].price = Form1->I[i+1].price; Form1->I[i].hp = Form1->I[i+1].hp; Form1->I[i].mp = Form1->I[i+1].mp; Form1->I[i].sta = Form1->I[i+1].sta; Form1->I[i].type = Form1->I[i+1].type; Form1->I[i].name = Form1->I[i+1].name; Form1->I[i].icon = Form1->I[i+1].icon; // And delete for enemy drops for (int h = 1; h <= Form1->entypenum; h++) Form1->E[h].item[i] = Form1->E[h].item[i + 1]; } int a = IList->ItemIndex; IList->Items->Delete(IList->ItemIndex); IList->ItemIndex = a; IListClick(Sender); } } //--------------------------------------------------------------------------- void __fastcall TForm2::saveClick(TObject *Sender) { Form1->I[IList->ItemIndex + 1].lvl = StrToInt(lvl->Text); Form1->I[IList->ItemIndex + 1].att = StrToInt(att->Text); Form1->I[IList->ItemIndex + 1].def = StrToInt(def->Text); Form1->I[IList->ItemIndex + 1].demage = StrToInt(dem->Text); Form1->I[IList->ItemIndex + 1].price = StrToInt(price->Text); Form1->I[IList->ItemIndex + 1].hp = StrToInt(hp->Text); Form1->I[IList->ItemIndex + 1].mp = StrToInt(mp->Text); Form1->I[IList->ItemIndex + 1].sta = StrToInt(sta->Text); Form1->I[IList->ItemIndex + 1].type = TypeCombo->ItemIndex; Form1->I[IList->ItemIndex + 1].name = name->Text; Form1->I[IList->ItemIndex + 1].icon = selicon; IList->Items->Insert(IList->ItemIndex,name->Text); int a = IList->ItemIndex - 1; IList->Items->Delete(IList->ItemIndex); IList->ItemIndex = a; } //--------------------------------------------------------------------------- void __fastcall TForm2::IListMouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { if (mouse == 0) sel = IList->ItemIndex; mouse = 1; } //--------------------------------------------------------------------------- void __fastcall TForm2::IListMouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { mouse = 0; sel = 0; } //--------------------------------------------------------------------------- void __fastcall TForm2::IListMouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { if (mouse == 1 && sel > -1) { int a; AnsiString b; if (sel > IList->ItemIndex) { // Replacing variables for items a = Form1->I[sel].lvl; Form1->I[sel].lvl = Form1->I[sel + 1].lvl; Form1->I[sel + 1].lvl = a; a = Form1->I[sel].att; Form1->I[sel].att = Form1->I[sel + 1].att; Form1->I[sel + 1].att = a; a = Form1->I[sel].def; Form1->I[sel].def = Form1->I[sel + 1].def; Form1->I[sel + 1].def = a; a = Form1->I[sel].demage; Form1->I[sel].demage = Form1->I[sel + 1].demage; Form1->I[sel + 1].demage = a; a = Form1->I[sel].price; Form1->I[sel].price = Form1->I[sel + 1].price; Form1->I[sel + 1].price = a; a = Form1->I[sel].hp; Form1->I[sel].hp = Form1->I[sel + 1].hp; Form1->I[sel + 1].hp = a; a = Form1->I[sel].mp; Form1->I[sel].mp = Form1->I[sel + 1].mp; Form1->I[sel + 1].mp = a; a = Form1->I[sel].sta; Form1->I[sel].sta = Form1->I[sel + 1].sta; Form1->I[sel + 1].sta = a; a = Form1->I[sel].type; Form1->I[sel].type = Form1->I[sel + 1].type; Form1->I[sel + 1].type = a; b = Form1->I[sel].name; Form1->I[sel].name = Form1->I[sel + 1].name; Form1->I[sel + 1].name = b; a = Form1->I[sel].icon; Form1->I[sel].icon = Form1->I[sel + 1].icon; Form1->I[sel + 1].icon = a; // And for enemy drop rates for (int i = 1; i <= Form1->entypenum; i++) {a = Form1->E[i].item[sel]; Form1->E[i].item[sel] = Form1->E[i].item[sel + 1]; Form1->E[i].item[sel + 1] = a;} IList->Items->Exchange(sel ,sel - 1); sel--; } else if (sel < IList->ItemIndex) { // Replacing variables for items a = Form1->I[sel + 2].lvl; Form1->I[sel + 2].lvl = Form1->I[sel + 1].lvl; Form1->I[sel + 1].lvl = a; a = Form1->I[sel + 2].att; Form1->I[sel + 2].att = Form1->I[sel + 1].att; Form1->I[sel + 1].att = a; a = Form1->I[sel + 2].def; Form1->I[sel + 2].def = Form1->I[sel + 1].def; Form1->I[sel + 1].def = a; a = Form1->I[sel + 2].demage; Form1->I[sel + 2].demage = Form1->I[sel + 1].demage; Form1->I[sel + 1].demage = a; a = Form1->I[sel + 2].price; Form1->I[sel + 2].price = Form1->I[sel + 1].price; Form1->I[sel + 1].price = a; a = Form1->I[sel + 2].hp; Form1->I[sel + 2].hp = Form1->I[sel + 1].hp; Form1->I[sel + 1].hp = a; a = Form1->I[sel + 2].mp; Form1->I[sel + 2].mp = Form1->I[sel + 1].mp; Form1->I[sel + 1].mp = a; a = Form1->I[sel + 2].sta; Form1->I[sel + 2].sta = Form1->I[sel + 1].sta; Form1->I[sel + 1].sta = a; a = Form1->I[sel + 2].type; Form1->I[sel + 2].type = Form1->I[sel + 1].type; Form1->I[sel + 1].type = a; b = Form1->I[sel + 2].name; Form1->I[sel + 2].name = Form1->I[sel + 1].name; Form1->I[sel + 1].name = b; a = Form1->I[sel + 2].icon; Form1->I[sel + 2].icon = Form1->I[sel + 1].icon; Form1->I[sel + 1].icon = a; // And for enemy drop rates for (int i = 1; i <= Form1->entypenum; i++) {a = Form1->E[i].item[sel + 2]; Form1->E[i].item[sel + 2] = Form1->E[i].item[sel + 1]; Form1->E[i].item[sel + 1] = a;} IList->Items->Exchange(sel,sel + 1); sel++; } } } //--------------------------------------------------------------------------- void __fastcall TForm2::FormCreate(TObject *Sender) { // Items for (int i = 1; i <= 2000; i++) if (FileExists("Items\\I" + IntToStr(i) + ".bmp")==true) { Items[i] = new Graphics::TBitmap; Items[i]->LoadFromFile("Items\\I" + IntToStr(i) + ".bmp"); Items[i]->Transparent = true; iconnum = i; // ??? I do not know what it is, but let it be.. } // Enemies for (int i = 1; i <= 200; i++) if (FileExists("Enemies\\En" + IntToStr(i) + ".bmp")==true) { EnType[i] = new Graphics::TBitmap; EnType[i]->LoadFromFile("Enemies\\En" + IntToStr(i) + ".bmp"); EnType[i]->Transparent = true; } } //--------------------------------------------------------------------------- void __fastcall TForm2::loadClick(TObject *Sender) { if (OpenDialog1->Execute()) { Image->Picture->LoadFromFile(OpenDialog1->FileName); AnsiString s = OpenDialog1->FileName; char c[15]; while (1) { c[0] = s[s.Length() - 4]; if (s[s.Length() - 5] == 'I')break; c[0] = s[s.Length() - 5]; c[1] = s[s.Length() - 4]; if (s[s.Length() - 6] == 'I')break; c[0] = s[s.Length() - 6]; c[1] = s[s.Length() - 5]; c[2] = s[s.Length() - 4]; if (s[s.Length() - 7] == 'I')break; c[0] = s[s.Length() - 7]; c[1] = s[s.Length() - 6]; c[2] = s[s.Length() - 5]; c[3] = s[s.Length() - 4]; break; } s = c; selicon = StrToInt(s); } } //--------------------------------------------------------------------------- void __fastcall TForm2::EListClick(TObject *Sender) { if (EList->ItemIndex > -1) { Ehp->Text = Form1->E[EList->ItemIndex + 1].hpmax; Espeed->Text = Form1->E[EList->ItemIndex + 1].speed; Esight->Text = Form1->E[EList->ItemIndex + 1].sight; Eatt->Text = Form1->E[EList->ItemIndex + 1].att; Edef->Text = Form1->E[EList->ItemIndex + 1].def; Edem->Text = Form1->E[EList->ItemIndex + 1].demage; Eexp->Text = Form1->E[EList->ItemIndex + 1].exp; Egold->Text = Form1->E[EList->ItemIndex + 1].gold; selicon2 = Form1->E[EList->ItemIndex + 1].icon; Ename->Text = Form1->E[EList->ItemIndex + 1].name; ItemCombo->Clear(); for (int h = 1; h <= Form1->itemnum; h++) if (Form1->E[EList->ItemIndex + 1].item[h] != 0) ItemCombo->Items->Add(Form1->I[h].name); ItemCombo->ItemIndex = 0; ItemComboChange(Sender); Image2->Picture->Bitmap = EnType[selicon2]; //Image2->Picture->LoadFromFile("Enemies\\En" + IntToStr(selicon2) + ".bmp"); } } //--------------------------------------------------------------------------- void __fastcall TForm2::EListMouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { if (mouse == 0) sel = EList->ItemIndex; mouse = 1; } //--------------------------------------------------------------------------- void __fastcall TForm2::EListMouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y) { mouse = 0; sel = 0; } //--------------------------------------------------------------------------- void __fastcall TForm2::EListMouseMove(TObject *Sender, TShiftState Shift, int X, int Y) { if (mouse == 1 && sel > -1) { int a; AnsiString b; if (sel > EList->ItemIndex) { a = Form1->E[sel].hpmax; Form1->E[sel].hpmax = Form1->E[sel + 1].hpmax; Form1->E[sel + 1].hpmax = a; a = Form1->E[sel].speed; Form1->E[sel].speed = Form1->E[sel + 1].speed; Form1->E[sel + 1].speed = a; a = Form1->E[sel].sight; Form1->E[sel].sight = Form1->E[sel + 1].sight; Form1->E[sel + 1].sight = a; a = Form1->E[sel].att; Form1->E[sel].att = Form1->E[sel + 1].att; Form1->E[sel + 1].att = a; a = Form1->E[sel].def; Form1->E[sel].def = Form1->E[sel + 1].def; Form1->E[sel + 1].def = a; a = Form1->E[sel].demage; Form1->E[sel].demage = Form1->E[sel + 1].demage; Form1->E[sel + 1].demage = a; a = Form1->E[sel].exp; Form1->E[sel].exp = Form1->E[sel + 1].exp; Form1->E[sel + 1].exp = a; a = Form1->E[sel].gold; Form1->E[sel].gold = Form1->E[sel + 1].gold; Form1->E[sel + 1].gold = a; b = Form1->E[sel].name; Form1->E[sel].name = Form1->E[sel + 1].name; Form1->E[sel + 1].name = b; a = Form1->E[sel].icon; Form1->E[sel].icon = Form1->E[sel + 1].icon; Form1->E[sel + 1].icon = a; a = Form1->E[sel].idropc; Form1->E[sel].idropc = Form1->E[sel + 1].idropc; Form1->E[sel + 1].idropc = a; for (int h = 1; h <= Form1->itemnum; h++) {a = Form1->E[sel].item[h]; Form1->E[sel].item[h] = Form1->E[sel + 1].item[h]; Form1->E[sel + 1].item[h] = a;} EList->Items->Exchange(sel ,sel - 1); sel--; } else if (sel < EList->ItemIndex) { a = Form1->E[sel + 2].hpmax; Form1->E[sel + 2].hpmax = Form1->E[sel + 1].hpmax; Form1->E[sel + 1].hpmax = a; a = Form1->E[sel + 2].speed; Form1->E[sel + 2].speed = Form1->E[sel + 1].speed; Form1->E[sel + 1].speed = a; a = Form1->E[sel + 2].sight; Form1->E[sel + 2].sight = Form1->E[sel + 1].sight; Form1->E[sel + 1].sight = a; a = Form1->E[sel + 2].att; Form1->E[sel + 2].att = Form1->E[sel + 1].att; Form1->E[sel + 1].att = a; a = Form1->E[sel + 2].def; Form1->E[sel + 2].def = Form1->E[sel + 1].def; Form1->E[sel + 1].def = a; a = Form1->E[sel + 2].demage; Form1->E[sel + 2].demage = Form1->E[sel + 1].demage; Form1->E[sel + 1].demage = a; a = Form1->E[sel + 2].exp; Form1->E[sel + 2].exp = Form1->E[sel + 1].exp; Form1->E[sel + 1].exp = a; a = Form1->E[sel + 2].gold; Form1->E[sel + 2].gold = Form1->E[sel + 1].gold; Form1->E[sel + 1].gold = a; b = Form1->E[sel + 2].name; Form1->E[sel + 2].name = Form1->E[sel + 1].name; Form1->E[sel + 1].name = b; a = Form1->E[sel + 2].icon; Form1->E[sel + 2].icon = Form1->E[sel + 1].icon; Form1->E[sel + 1].icon = a; a = Form1->E[sel + 2].idropc; Form1->E[sel + 2].idropc = Form1->E[sel + 1].idropc; Form1->E[sel + 1].idropc = a; for (int h = 1; h <= Form1->itemnum; h++) {a = Form1->E[sel + 2].item[h]; Form1->E[sel + 2].item[h] = Form1->E[sel + 1].item[h]; Form1->E[sel + 1].item[h] = a;} EList->Items->Exchange(sel ,sel + 1); sel++; } } } //--------------------------------------------------------------------------- void __fastcall TForm2::ItemComboChange(TObject *Sender) { if (ItemCombo->ItemIndex > -1) { for (int i = 1; i <= Form1->itemnum; i++) if (Form1->E[EList->ItemIndex + 1].item[i] != 0 && Form1->I[i].name == ItemCombo->Items->Strings[ItemCombo->ItemIndex]) { Edrop->Text = Form1->E[EList->ItemIndex + 1].item[i]; selic = i; } } } //--------------------------------------------------------------------------- void __fastcall TForm2::EaddClick(TObject *Sender) { /* Form1->itemnum++; Form1->I[Form1->itemnum].lvl = StrToInt(lvl->Text); Form1->I[Form1->itemnum].att = StrToInt(att->Text); Form1->I[Form1->itemnum].def = StrToInt(def->Text); Form1->I[Form1->itemnum].demage = StrToInt(dem->Text); Form1->I[Form1->itemnum].price = StrToInt(price->Text); Form1->I[Form1->itemnum].hp = StrToInt(hp->Text); Form1->I[Form1->itemnum].mp = StrToInt(mp->Text); Reikia redaguoti Form1->I[Form1->itemnum].sta = StrToInt(sta->Text); Kaip su menu Form1->I[Form1->itemnum].type = TypeCombo->ItemIndex; idesi Form1->I[Form1->itemnum].name = name->Text; pakeisti vietoj Form1->I[Form1->itemnum].icon = selicon; I - E IList->Items->Add(Form1->I[Form1->itemnum].name); IList->ItemIndex = Form1->itemnum - 1; */ } //--------------------------------------------------------------------------- void __fastcall TForm2::EdelClick(TObject *Sender) { /* if (IList->ItemIndex > -1) { Form1->itemnum--; for (int i = IList->ItemIndex + 1; i <= Form1->itemnum; i++) { Form1->I[i].lvl = Form1->I[i+1].lvl; Form1->I[i].att = Form1->I[i+1].att; Form1->I[i].def = Form1->I[i+1].def; Form1->I[i].demage = Form1->I[i+1].demage; Form1->I[i].price = Form1->I[i+1].price; Form1->I[i].hp = Form1->I[i+1].hp; Form1->I[i].mp = Form1->I[i+1].mp; Taip pat Form1->I[i].sta = Form1->I[i+1].sta; redaguoti Form1->I[i].type = Form1->I[i+1].type; Form1->I[i].name = Form1->I[i+1].name; Form1->I[i].icon = Form1->I[i+1].icon; } int a = IList->ItemIndex; IList->Items->Delete(IList->ItemIndex); IList->ItemIndex = a; IListClick(Sender); } */ } //--------------------------------------------------------------------------- void __fastcall TForm2::EsaveClick(TObject *Sender) { Form1->E[EList->ItemIndex + 1].hpmax = StrToInt(Ehp->Text); Form1->E[EList->ItemIndex + 1].speed = StrToInt(Espeed->Text); Form1->E[EList->ItemIndex + 1].sight = StrToInt(Esight->Text); Form1->E[EList->ItemIndex + 1].att = StrToInt(Eatt->Text); Form1->E[EList->ItemIndex + 1].def = StrToInt(Edef->Text); Form1->E[EList->ItemIndex + 1].demage = StrToInt(Edem->Text); Form1->E[EList->ItemIndex + 1].exp = StrToInt(Eexp->Text); Form1->E[EList->ItemIndex + 1].gold = StrToInt(Egold->Text); Form1->E[EList->ItemIndex + 1].name = Ename->Text; Form1->E[EList->ItemIndex + 1].icon = selicon2; EList->Items->Insert(EList->ItemIndex,Ename->Text); int a = EList->ItemIndex - 1; EList->Items->Delete(EList->ItemIndex); EList->ItemIndex = a; } //--------------------------------------------------------------------------- void __fastcall TForm2::EloadClick(TObject *Sender) { if (OpenDialog1->Execute()) { Image2->Picture->LoadFromFile(OpenDialog1->FileName); AnsiString s = OpenDialog1->FileName; char c[15]; while (1) { c[0] = s[s.Length() - 4]; if (s[s.Length() - 5] == 'n')break; c[0] = s[s.Length() - 5]; c[1] = s[s.Length() - 4]; if (s[s.Length() - 6] == 'n')break; c[0] = s[s.Length() - 6]; c[1] = s[s.Length() - 5]; c[2] = s[s.Length() - 4]; if (s[s.Length() - 7] == 'n')break; c[0] = s[s.Length() - 7]; c[1] = s[s.Length() - 6]; c[2] = s[s.Length() - 5]; c[3] = s[s.Length() - 4]; break; } s = c; selicon2 = StrToInt(s); } } //--------------------------------------------------------------------------- void __fastcall TForm2::EokClick(TObject *Sender) { Form1->E[EList->ItemIndex + 1].item[selic] = StrToInt(Edrop->Text); if (StrToInt(Edrop->Text) == 0) { ItemCombo->Items->Delete(ItemCombo->ItemIndex); Form1->E[EList->ItemIndex + 1].idropc--; } //ItemCombo->ItemIndex = 0; } //--------------------------------------------------------------------------- void __fastcall TForm2::Button1Click(TObject *Sender) { Form1->E[EList->ItemIndex + 1].item[IList->ItemIndex + 1] = 100; Form1->E[EList->ItemIndex + 1].idropc++; ItemCombo->Items->Add(IList->Items->Strings[IList->ItemIndex]); } //---------------------------------------------------------------------------
36.752294
127
0.522466
JustoSenka
0cafd91af3f1d372d401af345bc4533839eab7ab
10,259
cxx
C++
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimMaterialLayerSet.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
3
2016-05-30T15:12:16.000Z
2022-03-22T08:11:13.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimMaterialLayerSet.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
21
2016-06-13T11:33:45.000Z
2017-05-23T09:46:52.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimMaterialLayerSet.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
null
null
null
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimMaterialLayerSet.hxx" #include "intendedbldgelemtypes.hxx" namespace schema { namespace simxml { namespace ResourcesGeneral { // SimMaterialLayerSet // const SimMaterialLayerSet::MaterialLayers_optional& SimMaterialLayerSet:: MaterialLayers () const { return this->MaterialLayers_; } SimMaterialLayerSet::MaterialLayers_optional& SimMaterialLayerSet:: MaterialLayers () { return this->MaterialLayers_; } void SimMaterialLayerSet:: MaterialLayers (const MaterialLayers_type& x) { this->MaterialLayers_.set (x); } void SimMaterialLayerSet:: MaterialLayers (const MaterialLayers_optional& x) { this->MaterialLayers_ = x; } void SimMaterialLayerSet:: MaterialLayers (::std::auto_ptr< MaterialLayers_type > x) { this->MaterialLayers_.set (x); } const SimMaterialLayerSet::LayerSetName_optional& SimMaterialLayerSet:: LayerSetName () const { return this->LayerSetName_; } SimMaterialLayerSet::LayerSetName_optional& SimMaterialLayerSet:: LayerSetName () { return this->LayerSetName_; } void SimMaterialLayerSet:: LayerSetName (const LayerSetName_type& x) { this->LayerSetName_.set (x); } void SimMaterialLayerSet:: LayerSetName (const LayerSetName_optional& x) { this->LayerSetName_ = x; } void SimMaterialLayerSet:: LayerSetName (::std::auto_ptr< LayerSetName_type > x) { this->LayerSetName_.set (x); } const SimMaterialLayerSet::IntendedBldgElemTypes_optional& SimMaterialLayerSet:: IntendedBldgElemTypes () const { return this->IntendedBldgElemTypes_; } SimMaterialLayerSet::IntendedBldgElemTypes_optional& SimMaterialLayerSet:: IntendedBldgElemTypes () { return this->IntendedBldgElemTypes_; } void SimMaterialLayerSet:: IntendedBldgElemTypes (const IntendedBldgElemTypes_type& x) { this->IntendedBldgElemTypes_.set (x); } void SimMaterialLayerSet:: IntendedBldgElemTypes (const IntendedBldgElemTypes_optional& x) { this->IntendedBldgElemTypes_ = x; } void SimMaterialLayerSet:: IntendedBldgElemTypes (::std::auto_ptr< IntendedBldgElemTypes_type > x) { this->IntendedBldgElemTypes_.set (x); } const SimMaterialLayerSet::CompositeThermalTrans_optional& SimMaterialLayerSet:: CompositeThermalTrans () const { return this->CompositeThermalTrans_; } SimMaterialLayerSet::CompositeThermalTrans_optional& SimMaterialLayerSet:: CompositeThermalTrans () { return this->CompositeThermalTrans_; } void SimMaterialLayerSet:: CompositeThermalTrans (const CompositeThermalTrans_type& x) { this->CompositeThermalTrans_.set (x); } void SimMaterialLayerSet:: CompositeThermalTrans (const CompositeThermalTrans_optional& x) { this->CompositeThermalTrans_ = x; } } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace ResourcesGeneral { // SimMaterialLayerSet // SimMaterialLayerSet:: SimMaterialLayerSet () : ::schema::simxml::SimModelCore::SimResourceObject (), MaterialLayers_ (this), LayerSetName_ (this), IntendedBldgElemTypes_ (this), CompositeThermalTrans_ (this) { } SimMaterialLayerSet:: SimMaterialLayerSet (const RefId_type& RefId) : ::schema::simxml::SimModelCore::SimResourceObject (RefId), MaterialLayers_ (this), LayerSetName_ (this), IntendedBldgElemTypes_ (this), CompositeThermalTrans_ (this) { } SimMaterialLayerSet:: SimMaterialLayerSet (const SimMaterialLayerSet& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::SimModelCore::SimResourceObject (x, f, c), MaterialLayers_ (x.MaterialLayers_, f, this), LayerSetName_ (x.LayerSetName_, f, this), IntendedBldgElemTypes_ (x.IntendedBldgElemTypes_, f, this), CompositeThermalTrans_ (x.CompositeThermalTrans_, f, this) { } SimMaterialLayerSet:: SimMaterialLayerSet (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::SimModelCore::SimResourceObject (e, f | ::xml_schema::flags::base, c), MaterialLayers_ (this), LayerSetName_ (this), IntendedBldgElemTypes_ (this), CompositeThermalTrans_ (this) { if ((f & ::xml_schema::flags::base) == 0) { ::xsd::cxx::xml::dom::parser< char > p (e, true, false, true); this->parse (p, f); } } void SimMaterialLayerSet:: parse (::xsd::cxx::xml::dom::parser< char >& p, ::xml_schema::flags f) { this->::schema::simxml::SimModelCore::SimResourceObject::parse (p, f); for (; p.more_content (); p.next_content (false)) { const ::xercesc::DOMElement& i (p.cur_element ()); const ::xsd::cxx::xml::qualified_name< char > n ( ::xsd::cxx::xml::dom::name< char > (i)); // MaterialLayers // if (n.name () == "MaterialLayers" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< MaterialLayers_type > r ( MaterialLayers_traits::create (i, f, this)); if (!this->MaterialLayers_) { this->MaterialLayers_.set (r); continue; } } // LayerSetName // if (n.name () == "LayerSetName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< LayerSetName_type > r ( LayerSetName_traits::create (i, f, this)); if (!this->LayerSetName_) { this->LayerSetName_.set (r); continue; } } // IntendedBldgElemTypes // if (n.name () == "IntendedBldgElemTypes" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { ::std::auto_ptr< IntendedBldgElemTypes_type > r ( IntendedBldgElemTypes_traits::create (i, f, this)); if (!this->IntendedBldgElemTypes_) { this->IntendedBldgElemTypes_.set (r); continue; } } // CompositeThermalTrans // if (n.name () == "CompositeThermalTrans" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeneral") { if (!this->CompositeThermalTrans_) { this->CompositeThermalTrans_.set (CompositeThermalTrans_traits::create (i, f, this)); continue; } } break; } } SimMaterialLayerSet* SimMaterialLayerSet:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimMaterialLayerSet (*this, f, c); } SimMaterialLayerSet& SimMaterialLayerSet:: operator= (const SimMaterialLayerSet& x) { if (this != &x) { static_cast< ::schema::simxml::SimModelCore::SimResourceObject& > (*this) = x; this->MaterialLayers_ = x.MaterialLayers_; this->LayerSetName_ = x.LayerSetName_; this->IntendedBldgElemTypes_ = x.IntendedBldgElemTypes_; this->CompositeThermalTrans_ = x.CompositeThermalTrans_; } return *this; } SimMaterialLayerSet:: ~SimMaterialLayerSet () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace ResourcesGeneral { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
28.497222
127
0.615167
EnEff-BIM
0cb357f43d5613478f4a975d5b5d8ec61c4b4c4c
3,256
cpp
C++
test/test02.cpp
subject721/flow-orchestrator
cadc646db5eece510c1dc1edf7bacf5060a7915c
[ "BSD-3-Clause" ]
3
2021-10-05T08:13:56.000Z
2022-02-07T22:41:03.000Z
test/test02.cpp
subject721/flow-orchestrator
cadc646db5eece510c1dc1edf7bacf5060a7915c
[ "BSD-3-Clause" ]
null
null
null
test/test02.cpp
subject721/flow-orchestrator
cadc646db5eece510c1dc1edf7bacf5060a7915c
[ "BSD-3-Clause" ]
1
2022-02-07T22:41:05.000Z
2022-02-07T22:41:05.000Z
/* * SPDX-License-Identifier: BSD-3-Clause * Copyright (c) 2021, Stefan Seitz * */ #include <common/common.hpp> #include <dpdk/dpdk_common.hpp> #include <flow_executor.hpp> class executor_test { public: executor_test() : executor(*this) {} void run_test(const std::vector< lcore_info >& available_lcores) { try { executor.setup({0, 0}, 1, available_lcores); executor.start(&executor_test::run_endpoint_tasks, &executor_test::run_distributor_tasks); rte_delay_us_sleep(10000); executor.stop(); } catch ( const std::exception& e ) { log(LOG_ERROR, "test failed: {}", e.what()); } } private: void run_endpoint_tasks(const size_t* indicies, size_t num_indicies, std::atomic_bool& run_flag) { for ( size_t i = 0; i < num_indicies; ++i ) { size_t index = indicies[i]; log(LOG_INFO, "Running endpoint task: {} on lcore {}", index, rte_lcore_id()); rte_delay_us_sleep(200); } } void run_distributor_tasks(const size_t* indicies, size_t num_indicies, std::atomic_bool& run_flag) { for ( size_t i = 0; i < num_indicies; ++i ) { size_t index = indicies[i]; log(LOG_INFO, "Running distributor task: {} on lcore {}", index, rte_lcore_id()); rte_delay_us_sleep(200); } } flow_executor< reduced_core_policy, executor_test > executor; }; int main(int argc, char** argv) { try { dpdk_eal_init({"--no-shconf", "--in-memory", "-l", "1,2,3,4"}); } catch ( const std::exception& e ) { log(LOG_ERROR, "could not init dpdk eal: {}", e.what()); return 1; } executor_test test; test.run_test(lcore_info::get_available_worker_lcores()); try { mbuf_ring ring("my_ring", 0, 512); dpdk_packet_mempool mempool(512, 0, 1024, 32); static_mbuf_vec< 32 > mbuf_vec; static_mbuf_vec< 32 > mbuf_vec_out; uint16_t burst_size = 16; log(LOG_INFO, "mempool alloc stats after init: {}/{}", mempool.get_num_allocated(), mempool.get_capacity()); if ( mempool.bulk_alloc(mbuf_vec, burst_size) ) { throw std::runtime_error("could not alloc mbufs"); } log(LOG_INFO, "mempool alloc stats after alloc: {}/{}", mempool.get_num_allocated(), mempool.get_capacity()); if ( ring.enqueue(mbuf_vec) != burst_size ) { throw std::runtime_error("queuing failed"); } log(LOG_INFO, "mempool alloc stats after queue: {}/{}", mempool.get_num_allocated(), mempool.get_capacity()); if ( ring.dequeue(mbuf_vec_out) != burst_size ) { throw std::runtime_error("dequeuing failed"); } log(LOG_INFO, "mempool alloc stats after dequeue: {}/{}", mempool.get_num_allocated(), mempool.get_capacity()); if ( mbuf_vec_out.size() != burst_size ) { throw std::runtime_error("mbuf vec wrong size"); } mbuf_vec_out.free(); log(LOG_INFO, "mempool alloc stats after free: {}/{}", mempool.get_num_allocated(), mempool.get_capacity()); } catch ( const std::exception& e ) { log(LOG_ERROR, "error while testing ring: {}", e.what()); } return 0; }
30.148148
119
0.610258
subject721
0cb706c5b94022177ade165039b90ff253dd2ca7
675
cpp
C++
Codeforces/459D.cpp
Alipashaimani/Competitive-programming
5d55567b71ea61e69a6450cda7323c41956d3cb9
[ "MIT" ]
null
null
null
Codeforces/459D.cpp
Alipashaimani/Competitive-programming
5d55567b71ea61e69a6450cda7323c41956d3cb9
[ "MIT" ]
null
null
null
Codeforces/459D.cpp
Alipashaimani/Competitive-programming
5d55567b71ea61e69a6450cda7323c41956d3cb9
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; constexpr int MAXN = 1e6 + 10; map <int, int> f1, f2, cnt; int n, a[MAXN], fw[MAXN]; long long ans = 0; void update (int i){ for (; i <= n; i += i&(-i)) ++fw[i]; } int query (int i) { int x = 0; for (--i; ~i+1; i -= i&(-i)) x += fw[i]; return x; } int main () { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n; for(int i = 1; i <= n; ++i) cin >> a[i], f1[i] = ++cnt[a[i]]; for(int i = 1; i <= n; ++i) f2[i] = cnt[a[i]]--; for(int i = n; ~i+1; --i) ans += query(f1[i]), update(f2[i]); cout << ans << endl; }
17.763158
46
0.441481
Alipashaimani
0cbba2ebea73847428df973d267e6c5cd468e698
611
cpp
C++
test/common/timeType/date/TestDate.cpp
liupengzhouyi/MyNotion
6ddc96e0e6e061adac78aa68c2d2b9b53bd4ad85
[ "Apache-2.0" ]
null
null
null
test/common/timeType/date/TestDate.cpp
liupengzhouyi/MyNotion
6ddc96e0e6e061adac78aa68c2d2b9b53bd4ad85
[ "Apache-2.0" ]
null
null
null
test/common/timeType/date/TestDate.cpp
liupengzhouyi/MyNotion
6ddc96e0e6e061adac78aa68c2d2b9b53bd4ad85
[ "Apache-2.0" ]
null
null
null
#include "TestDate.h" #include <iostream> #include <string> #include "../../../../src/common/timeType/date/date.h" #include "gtest/gtest.h" int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } using Test::TestCommon::TestTimeType::TestDate; using Common::TimeType::Date; TEST_F(TestDate, One) { int n = 0; Date date; date.init(); std::string strDate = date.getDateAsString(); EXPECT_EQ(n, 0); } TEST_F(TestDate, Tow) { int n = 0; Date date; date.init(); std::string strDate = date.getDateAsString(); EXPECT_EQ(strDate.length(), 10); }
19.709677
54
0.667758
liupengzhouyi
0cbfb4a61188286604772331ea7b281a262932e4
314
cpp
C++
Source/Async/Utils.cpp
loudedtwist/cpp-task-loop
71795ad6916bf35ddca5dc04fd291d2affb2ffff
[ "MIT" ]
null
null
null
Source/Async/Utils.cpp
loudedtwist/cpp-task-loop
71795ad6916bf35ddca5dc04fd291d2affb2ffff
[ "MIT" ]
null
null
null
Source/Async/Utils.cpp
loudedtwist/cpp-task-loop
71795ad6916bf35ddca5dc04fd291d2affb2ffff
[ "MIT" ]
null
null
null
#include <Async/Utils.hpp> #include <chrono> namespace utils { unique_id GenerateTimestampID() { return (unique_id) std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::system_clock::now().time_since_epoch() + std::chrono::high_resolution_clock::now().time_since_epoch()) .count(); } }
22.428571
119
0.719745
loudedtwist
0cc076f8a92c4a68c1353295b8ed1a3953f66df2
2,085
cpp
C++
luogu/3804/me.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
luogu/3804/me.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
luogu/3804/me.cpp
jinzhengyu1212/Clovers
0efbb0d87b5c035e548103409c67914a1f776752
[ "MIT" ]
null
null
null
/* the vast starry sky, bright for those who chase the light. */ #include<bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int,int> pii; #define mk make_pair const int inf=(int)1e9; const ll INF=(ll)5e18; const int MOD=998244353; int add(int x,int y){x+=y; return x>=MOD ? x-MOD : x;} int sub(int x,int y){x-=y; return x<0 ? x+MOD : x;} #define mul(x,y) (ll)(x)*(y)%MOD int qpow(int x,int y){int ret=1; while(y){if(y&1) ret=mul(ret,x); x=mul(x,x); y>>=1;} return ret;} void checkmin(int &x,int y){if(x>y) x=y;} void checkmax(int &x,int y){if(x<y) x=y;} void checkmin(ll &x,ll y){if(x>y) x=y;} void checkmax(ll &x,ll y){if(x<y) x=y;} #define out(x) cerr<<#x<<'='<<x<<' ' #define outln(x) cerr<<#x<<'='<<x<<endl #define sz(x) (int)(x).size() inline int read(){ int x=0,f=1; char c=getchar(); while(c>'9'||c<'0'){if(c=='-') f=-1; c=getchar();} while(c>='0'&&c<='9') x=(x<<1)+(x<<3)+(c^48),c=getchar(); return x*f; } const int N=300005; int sz=1,lst=1; ll ans=0; struct SAM{ int link[N],maxlen[N],trans[N][26]; ll f[N]; void extend(int id){ int cur=++sz,p; maxlen[cur]=maxlen[lst]+1; for(p=lst;p&&!trans[p][id];p=link[p]) trans[p][id]=cur; if(!p) link[cur]=1; else{ int q=trans[p][id]; if(maxlen[q]==maxlen[p]+1) link[cur]=q; else{ int tmp=++sz; maxlen[tmp]=maxlen[p]+1; copy(trans[q],trans[q]+26,trans[tmp]); link[tmp]=link[q]; for(;p&&trans[p][id]==q;p=link[p]) trans[p][id]=tmp; link[cur]=link[q]=tmp; } } lst=cur; } int vis[N]; vector<int> v[N]; void dfs(int u){ f[u]=1; vis[u]=1; for(int i=0;i<26;i++) if(trans[u][i]){ if(!vis[trans[u][i]]) dfs(trans[u][i]); f[u]+=f[trans[u][i]]; } } }tree; char s[N]; int n; int main() { n=read(); scanf("%s",s+1); for(int i=1;i<=n;i++) tree.extend(s[i]-'a'); tree.dfs(1); cout<<tree.f[1]-1<<endl; return 0; }
28.175676
98
0.506475
jinzhengyu1212
0cc084f33ed98c9f36480c7082e9cff7a5c937a7
2,347
cpp
C++
policy.cpp
slist/cbapi-qt-demo
b44e31824a5b9973aa0ccff39c15ff7805902b8b
[ "MIT" ]
3
2020-09-14T19:39:53.000Z
2021-01-19T11:58:27.000Z
policy.cpp
slist/cbapi-qt-demo
b44e31824a5b9973aa0ccff39c15ff7805902b8b
[ "MIT" ]
null
null
null
policy.cpp
slist/cbapi-qt-demo
b44e31824a5b9973aa0ccff39c15ff7805902b8b
[ "MIT" ]
null
null
null
// Copyright 2020 VMware, Inc. // SPDX-License-Identifier: MIT #include "policy.h" #include "ui_policy.h" Policy::Policy(QWidget *parent) : QWidget(parent), ui(new Ui::Policy) { ui->setupUi(this); } Policy::~Policy() { delete ui; } void Policy::setName(const QString n) { name = n; ui->label_name->setText(n); } void Policy::setDescription(const QString d) { description = d; ui->label_name->setToolTip(d); } void Policy::setUi(bool b) { if (b) { ui->label_ui->setStyleSheet("border: 2px solid gray;border-radius: 5px;background-color: #2AA62A;"); ui->label_ui->setText("UI\nON"); } else { ui->label_ui->setStyleSheet("border: 2px solid gray;border-radius: 5px;background-color: #FD7979;"); ui->label_ui->setText("UI\nOFF"); } } void Policy::setGoLive(bool b) { ui->label_go_live->setAlignment(Qt::AlignCenter); ui->label_go_live->setMargin(2); if (b) { ui->label_go_live->setStyleSheet("border: 2px solid gray;border-radius: 5px;background-color: #2AA62A;"); ui->label_go_live->setText(" Go Live \nON"); } else { ui->label_go_live->setStyleSheet("border: 2px solid gray;border-radius: 5px;background-color: #FD7979;"); ui->label_go_live->setText(" Go Live \nOFF"); } } void Policy::setRulesNumber(int n) { if (n > 0) { ui->label_rules->setStyleSheet("border: 2px solid gray;border-radius: 5px;background-color: #2AA62A;"); } else { ui->label_rules->setStyleSheet("border: 2px solid gray;border-radius: 5px;background-color: #FD7979;"); } QString s = QString("Rules:\n%1").arg(n); ui->label_rules->setText(s); } void Policy::setLog(bool b) { if (b) { ui->label_log->setStyleSheet("border: 2px solid gray;border-radius: 5px;background-color: #2AA62A;"); ui->label_log->setText("LOG\nON"); } else { ui->label_log->setStyleSheet("border: 2px solid gray;border-radius: 5px;background-color: #FD7979;"); ui->label_log->setText("LOG\nOFF"); } } void Policy::on_checkBox_stateChanged(int arg1) { switch (arg1) { case Qt::Unchecked: emit pol_deselected(name); break; case Qt::Checked: emit pol_selected(name); break; } } void Policy::unselect() { ui->checkBox->setChecked(false); }
24.705263
113
0.633575
slist
0cc669d3fe485bedc8e1dbc9d9c4d2f1afaa24b7
2,333
cpp
C++
Problems/36_Valide_Sudoku/main.cpp
camelboat/LeetCode_Archive
c29d263e068752a9ad355925f326b56f672bb584
[ "MIT" ]
3
2019-09-21T16:25:44.000Z
2021-08-29T20:43:57.000Z
Problems/36_Valide_Sudoku/main.cpp
camelboat/LeetCode_Archive
c29d263e068752a9ad355925f326b56f672bb584
[ "MIT" ]
null
null
null
Problems/36_Valide_Sudoku/main.cpp
camelboat/LeetCode_Archive
c29d263e068752a9ad355925f326b56f672bb584
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { vector<bool> base(27*9, false); for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { int tar = board[i][j] - '0'; if (tar != '.'-'0') { // cout << "i " << i << '\n'; // cout << "j " << j << '\n'; int fir = 9*i+tar-1; if (base[fir]) return false; else base[fir] = true; int sec = 81 + j*9 + tar-1; if (base[sec]) return false; else base[sec] = true; int thi = 162 + ((i/3)*3+j/3)*9+tar-1; if (base[thi]) return false; else base[thi] = true; } } } return true; // typedef unordered_map<char, int> hashmap; // vector<hashmap> base; // for (int i = 0; i < 27; ++i) // { // hashmap tmp; // base.emplace_back(tmp); // } // for (int i = 0; i < 9; ++i) // { // for (int j = 0; j < 9; ++j) // { // // hashmap i (row) // // hashmap 9+j (column) // // hashmap 18+(i/3)*3+j/3 (grid) // if (board[i][j] != '.') // { // if (base[i].find(board[i][j])!=base[i].end()) return false; // else base[i][board[i][j]]++; // int sec = 9+j; // if (base[sec].find(board[i][j])!=base[sec].end()) return false; // else // { // base[sec][board[i][j]]++; // } // int thi = 18+(i/3)*3+(j/3); // if (base[thi].find(board[i][j])!=base[thi].end()) return false; // else base[thi][board[i][j]]++; // } // } // } // return true; } }; // for (int k = 0; k < 27; ++k) // { // cout << "group " << k << '\n'; // for (auto& x: base[k]) std::cout << " " << x.first << ":" << x.second << '\n'; // }
30.697368
86
0.328333
camelboat
0cc7cd6722f67bb702ca9abb75124bd8fa896670
2,236
hpp
C++
android-31/java/time/chrono/JapaneseDate.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/java/time/chrono/JapaneseDate.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/java/time/chrono/JapaneseDate.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once namespace java::io { class ObjectInputStream; } class JObject; class JString; namespace java::time { class Clock; } namespace java::time { class LocalDate; } namespace java::time { class LocalTime; } namespace java::time { class ZoneId; } namespace java::time::chrono { class JapaneseChronology; } namespace java::time::chrono { class JapaneseEra; } namespace java::time::temporal { class ValueRange; } namespace java::time::chrono { class JapaneseDate : public JObject { public: // Fields // QJniObject forward template<typename ...Ts> explicit JapaneseDate(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} JapaneseDate(QJniObject obj); // Constructors // Methods static java::time::chrono::JapaneseDate from(JObject arg0); static java::time::chrono::JapaneseDate now(); static java::time::chrono::JapaneseDate now(java::time::Clock arg0); static java::time::chrono::JapaneseDate now(java::time::ZoneId arg0); static java::time::chrono::JapaneseDate of(jint arg0, jint arg1, jint arg2); static java::time::chrono::JapaneseDate of(java::time::chrono::JapaneseEra arg0, jint arg1, jint arg2, jint arg3); JObject atTime(java::time::LocalTime arg0) const; jboolean equals(JObject arg0) const; java::time::chrono::JapaneseChronology getChronology() const; java::time::chrono::JapaneseEra getEra() const; jlong getLong(JObject arg0) const; jint hashCode() const; jboolean isSupported(JObject arg0) const; jint lengthOfMonth() const; jint lengthOfYear() const; java::time::chrono::JapaneseDate minus(JObject arg0) const; java::time::chrono::JapaneseDate minus(jlong arg0, JObject arg1) const; java::time::chrono::JapaneseDate plus(JObject arg0) const; java::time::chrono::JapaneseDate plus(jlong arg0, JObject arg1) const; java::time::temporal::ValueRange range(JObject arg0) const; jlong toEpochDay() const; JString toString() const; JObject until(JObject arg0) const; jlong until(JObject arg0, JObject arg1) const; java::time::chrono::JapaneseDate with(JObject arg0) const; java::time::chrono::JapaneseDate with(JObject arg0, jlong arg1) const; }; } // namespace java::time::chrono
27.268293
153
0.731664
YJBeetle
0cc9b82e0977cea065880c24f5b5c2df3ba8bce7
2,503
cpp
C++
src_smartcontract_vm/instance/instance_exception/NullPointerExceptionClassDeclare.cpp
alinous-core/codable-cash
32a86a152a146c592bcfd8cc712f4e8cb38ee1a0
[ "MIT" ]
6
2019-01-06T05:02:39.000Z
2020-10-01T11:45:32.000Z
src_smartcontract_vm/instance/instance_exception/NullPointerExceptionClassDeclare.cpp
Codablecash/codablecash
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
[ "MIT" ]
209
2018-05-18T03:07:02.000Z
2022-03-26T11:42:41.000Z
src_smartcontract_vm/instance/instance_exception/NullPointerExceptionClassDeclare.cpp
Codablecash/codablecash
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
[ "MIT" ]
3
2019-07-06T09:16:36.000Z
2020-10-15T08:23:28.000Z
/* * NullPointerExceptionClassDeclare.cpp * * Created on: 2020/04/17 * Author: iizuka */ #include "instance/instance_exception/NullPointerExceptionClassDeclare.h" #include "base/UnicodeString.h" #include "engine/sc_analyze/AnalyzedClass.h" #include "engine/sc_analyze/AnalyzedType.h" #include "engine/sc_analyze/IVmInstanceFactory.h" #include "instance/instance_exception_class/ExceptionInstanceFactory.h" #include "instance/instance_exception_class/ExceptionClassDeclare.h" #include "instance/instance_exception_class/VmExceptionInstance.h" #include "lang/sc_declare/ClassExtends.h" #include "vm/vm_ctrl/ExecControlManager.h" #include "vm/VirtualMachine.h" #include "instance/reserved_classes/ReservedClassRegistory.h" namespace alinous { UnicodeString NullPointerExceptionClassDeclare::NAME{L"NullPointerException"}; NullPointerExceptionClassDeclare::NullPointerExceptionClassDeclare() : AbstractExceptionClassDeclare() { addDefaultConstructor(&NAME); this->extends = new ClassExtends(); this->extends->setClassName(&ExceptionClassDeclare::NAME); } AnalyzedClass* NullPointerExceptionClassDeclare::createAnalyzedClass() noexcept { NullPointerExceptionClassDeclare* classDec = new NullPointerExceptionClassDeclare(); AnalyzedClass* aclass = new AnalyzedClass(classDec); return aclass; } void NullPointerExceptionClassDeclare::throwException(VirtualMachine* vm, const CodeElement* element) noexcept { ExecControlManager* ctrl = vm->getCtrl(); IVmInstanceFactory* factory = ExceptionInstanceFactory::getInstance(); AnalyzedClass* aclass = vm->getReservedClassRegistory()->getAnalyzedClass(&NAME); VmClassInstance* inst = factory->createInstance(aclass, vm); inst->init(vm); VmExceptionInstance* exception = dynamic_cast<VmExceptionInstance*>(inst); vm->throwException(exception, element); } NullPointerExceptionClassDeclare::~NullPointerExceptionClassDeclare() { } const UnicodeString* NullPointerExceptionClassDeclare::getName() noexcept { return &NAME; } const UnicodeString* NullPointerExceptionClassDeclare::getFullQualifiedName() noexcept { return &NAME; } ClassDeclare* NullPointerExceptionClassDeclare::getBaseClass() const noexcept { AnalyzedType* atype = this->extends->getAnalyzedType(); AnalyzedClass* aclass = atype->getAnalyzedClass(); return aclass->getClassDeclare(); } IVmInstanceFactory* NullPointerExceptionClassDeclare::getFactory() const noexcept { return ExceptionInstanceFactory::getInstance(); } } /* namespace alinous */
29.104651
112
0.80863
alinous-core
0cca2dcee75d53b3683ba341da2839bea77c76b2
534
hh
C++
dimensionanalysis/print.hh
dearoneesama/ctut
1a0fe75f435bc7b50dbeefa0ecb5eeed62a89f55
[ "BSL-1.0" ]
null
null
null
dimensionanalysis/print.hh
dearoneesama/ctut
1a0fe75f435bc7b50dbeefa0ecb5eeed62a89f55
[ "BSL-1.0" ]
null
null
null
dimensionanalysis/print.hh
dearoneesama/ctut
1a0fe75f435bc7b50dbeefa0ecb5eeed62a89f55
[ "BSL-1.0" ]
null
null
null
#pragma once #include <ostream> #include "dim.hh" namespace dim { template<unitpw_t s, unitpw_t m, unitpw_t kg, unitpw_t A, unitpw_t K, unitpw_t mol, unitpw_t cd, class T> std::ostream &operator<<(std::ostream &out, const quantity<dimVec<s, m, kg, A, K, mol, cd>, T> &q) { out << q.value << " [s: " << s << ", m: " << m << ", kg: " << kg << ", A: " << A << ", K: " << K << ", mol: " << mol << ", cd: " << cd << ']'; return out; } }
24.272727
104
0.434457
dearoneesama
0ccc3aeae323159016b55441cbbda4c7a228b511
15,978
tcc
C++
flens/lapack/la/laexc.tcc
stip/FLENS
80495fa97dda42a0acafc8f83fc9639ae36d2e10
[ "BSD-3-Clause" ]
98
2015-01-26T20:31:37.000Z
2021-09-09T15:51:37.000Z
flens/lapack/la/laexc.tcc
stip/FLENS
80495fa97dda42a0acafc8f83fc9639ae36d2e10
[ "BSD-3-Clause" ]
16
2015-01-21T07:43:45.000Z
2021-12-06T12:08:36.000Z
flens/lapack/la/laexc.tcc
stip/FLENS
80495fa97dda42a0acafc8f83fc9639ae36d2e10
[ "BSD-3-Clause" ]
31
2015-01-05T08:06:45.000Z
2022-01-26T20:12:00.000Z
/* * Copyright (c) 2011, Michael Lehn * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3) Neither the name of the FLENS development group 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. */ /* Based on * SUBROUTINE DLAEXC( WANTQ, N, T, LDT, Q, LDQ, J1, N1, N2, WORK, $ INFO ) * * -- LAPACK auxiliary routine (version 3.2.2) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * June 2010 */ #ifndef FLENS_LAPACK_LA_LAEXC_TCC #define FLENS_LAPACK_LA_LAEXC_TCC 1 #include <flens/auxiliary/auxiliary.h> #include <flens/blas/blas.h> #include <flens/lapack/lapack.h> namespace flens { namespace lapack { //== generic lapack implementation ============================================= namespace generic { template <typename MT, typename MQ, typename IndexType, typename VWORK> IndexType laexc_impl(bool computeQ, GeMatrix<MT> &T, GeMatrix<MQ> &Q, IndexType j1, IndexType n1, IndexType n2, DenseVector<VWORK> &work) { using std::abs; using flens::max; typedef typename GeMatrix<MT>::View GeMatrixView; typedef typename GeMatrix<MT>::VectorView DenseVectorView; typedef typename GeMatrix<MT>::ElementType ElementType; const ElementType Zero(0), One(1), Ten(10); const IndexType n = T.numRows(); const Underscore<IndexType> _; // // .. Local Arrays .. // ElementType dData_[16], xData_[4]; GeMatrixView D = typename GeMatrixView::Engine(4, 4, dData_, 4); GeMatrixView X = typename GeMatrixView::Engine(2, 2, xData_, 2); ElementType uData_[3], u1Data_[3], u2Data_[3]; DenseVectorView u = typename DenseVectorView::Engine(3, uData_); DenseVectorView u1 = typename DenseVectorView::Engine(3, u1Data_); DenseVectorView u2 = typename DenseVectorView::Engine(3, u2Data_); // // Quick return if possible // if (n==0 || n1==0 || n2==0) { return 0; } if (j1+n1>n) { return 0; } const IndexType j2 = j1 + 1; const IndexType j3 = j1 + 2; const IndexType j4 = j1 + 3; ElementType t11, t22, t33; if (n1==1 && n2==1) { // // Swap two 1-by-1 blocks. // t11 = T(j1,j1); t22 = T(j2,j2); // // Determine the transformation to perform the interchange. // ElementType cs, sn, temp; lartg(T(j1,j2), t22-t11, cs, sn, temp); // // Apply transformation to the matrix T. // if (j3<=n) { blas::rot(T(j1,_(j3,n)), T(j2,_(j3,n)), cs, sn); } blas::rot(T(_(1,j1-1),j1), T(_(1,j1-1),j2), cs, sn); T(j1,j1) = t22; T(j2,j2) = t11; if (computeQ) { // // Accumulate transformation in the matrix Q. // blas::rot(Q(_,j1), Q(_,j2), cs, sn); } } else { // // Swapping involves at least one 2-by-2 block. // // Copy the diagonal block of order N1+N2 to the local array D // and compute its norm. // const IndexType nd = n1 + n2; auto D_ = D(_(1,nd),_(1,nd)); D_ = T(_(j1,j1+nd-1),_(j1,j1+nd-1)); ElementType normD = lan(MaximumNorm, D_); ElementType cs, sn, wr1, wr2, wi1, wi2; ElementType scale, normX, tau, tau1, tau2; // // Compute machine-dependent threshold for test for accepting // swap. // const ElementType eps = lamch<ElementType>(Precision); const ElementType smallNum = lamch<ElementType>(SafeMin) / eps; const ElementType thresh = max(Ten*eps*normD, smallNum); // // Solve T11*X - X*T22 = scale*T12 for X. // const auto T11 = D(_(1,n1),_(1,n1)); const auto T12 = D(_(1,n1),_(n1+1,nd)); const auto T22 = D(_(n1+1,nd),_(n1+1,nd)); auto X_ = X(_(1,n1),_(1,n2)); lasy2(false, false, IndexType(-1), T11, T22, T12, scale, X_, normX); // // Swap the adjacent diagonal blocks. // const IndexType k = n1 + n1 + n2 - 3; switch (k) { // // N1 = 1, N2 = 2: generate elementary reflector H so that: // // ( scale, X11, X12 ) H = ( 0, 0, * ) // case 1: u(1) = scale; u(2) = X(1,1); u(3) = X(1,2); larfg(IndexType(3), u(3), u(_(1,2)), tau); u(3) = One; t11 = T(j1,j1); // // Perform swap provisionally on diagonal block in D. // larfx(Left, u, tau, D_, work(_(1,3))); larfx(Right, u, tau, D_, work(_(1,3))); // // Test whether to reject swap. // if (max(abs(D(3,1)), abs(D(3,2)), abs(D(3,3)-t11))>thresh) { // // Return 1 if swap was rejected. // return 1; } // // Accept swap: apply transformation to the entire matrix T. // larfx(Left, u, tau, T(_(j1,j1+3-1),_(j1,n)), work(_(1,n-j1+1))); larfx(Right, u, tau, T(_(1,j2),_(j1,j1+3-1)), work(_(1,j2))); T(j3,j1) = Zero; T(j3,j2) = Zero; T(j3,j3) = t11; if (computeQ) { // // Accumulate transformation in the matrix Q. // larfx(Right, u, tau, Q(_,_(j1,j1+3-1)), work); } break; case 2: // // N1 = 2, N2 = 1: generate elementary reflector H so that: // // H ( -X11 ) = ( * ) // ( -X21 ) = ( 0 ) // ( scale ) = ( 0 ) // u(1) = -X(1,1); u(2) = -X(2,1); u(3) = scale; larfg(IndexType(3), u(1), u(_(2,3)), tau); u(1) = One; t33 = T(j3,j3); // // Perform swap provisionally on diagonal block in D. // larfx(Left, u, tau, D(_(1,3),_(1,3)), work(_(1,3))); larfx(Right, u, tau, D(_(1,3),_(1,3)), work(_(1,3))); // // Test whether to reject swap. // if (max(abs(D(2,1)), abs(D(3,1)), abs(D(1,1)-t33))>thresh) { // // Return 1 if swap was rejected. // return 1; } // // Accept swap: apply transformation to the entire matrix T. // larfx(Right, u, tau, T(_(1,j3),_(j1, j1+3-1)), work(_(1,j3))); larfx(Left, u, tau, T(_(j1,j1+3-1),_(j2,n)), work(_(1,n-j1))); T(j1,j1) = t33; T(j2,j1) = Zero; T(j3,j1) = Zero; if (computeQ) { // // Accumulate transformation in the matrix Q. // larfx(Right, u, tau, Q(_,_(j1,j1+3-1)), work); } break; case 3: // // N1 = 2, N2 = 2: generate elementary reflectors H(1) and H(2) so // that: // // H(2) H(1) ( -X11 -X12 ) = ( * * ) // ( -X21 -X22 ) ( 0 * ) // ( scale 0 ) ( 0 0 ) // ( 0 scale ) ( 0 0 ) // u1(1) = -X(1,1); u1(2) = -X(2,1); u1(3) = scale; larfg(IndexType(3), u1(1), u1(_(2,3)), tau1); u1(1) = One; const ElementType temp = -tau1*(X(1,2)+u1(2)*X(2,2)); u2(1) = -temp*u1(2) - X(2,2); u2(2) = -temp*u1(3); u2(3) = scale; larfg(IndexType(3), u2(1), u2(_(2,3)), tau2); u2(1) = One; // // Perform swap provisionally on diagonal block in D. // larfx(Left, u1, tau1, D(_(1,3),_(1,4)), work(_(1,4))); larfx(Right, u1, tau1, D(_(1,4),_(1,3)), work(_(1,4))); larfx(Left, u2, tau2, D(_(2,4),_(1,4)), work(_(1,4))); larfx(Right, u2, tau2, D(_(1,4),_(2,4)), work(_(1,4))); // // Test whether to reject swap. // if (max(abs(D(3,1)), abs(D(3,2)), abs(D(4,1)), abs(D(4,2)))>thresh) { // // Return 1 if swap was rejected. // return 1; } // // Accept swap: apply transformation to the entire matrix T. // larfx(Left, u1, tau1, T(_(j1,j1+3-1),_(j1,n)), work(_(1,n-j1+1))); larfx(Right, u1, tau1, T(_(1,j4),_(j1,j1+3-1)), work(_(1,j4))); larfx(Left, u2, tau2, T(_(j2,j2+3-1),_(j1,n)), work(_(1,n-j1+1))); larfx(Right, u2, tau2, T(_(1,j4),_(j2,j2+3-1)), work(_(1,j4))); T(j3,j1) = Zero; T(j3,j2) = Zero; T(j4,j1) = Zero; T(j4,j2) = Zero; if (computeQ) { // // Accumulate transformation in the matrix Q. // larfx(Right, u1, tau1, Q(_,_(j1,j1+3-1)), work); larfx(Right, u2, tau2, Q(_,_(j2,j2+3-1)), work); } } if (n2==2) { // // Standardize new 2-by-2 block T11 // lanv2(T(j1,j1), T(j1,j2), T(j2,j1), T(j2,j2), wr1, wi1, wr2, wi2, cs, sn); blas::rot(T(j1,_(j1+2,n)), T(j2,_(j1+2,n)), cs, sn); blas::rot(T(_(1,j1-1),j1), T(_(1,j1-1),j2), cs, sn); if (computeQ) { blas::rot(Q(_,j1), Q(_,j2), cs, sn); } } if (n1==2) { // // Standardize new 2-by-2 block T22 // const IndexType j3 = j1 + n2; const IndexType j4 = j3 + 1; lanv2(T(j3,j3), T(j3,j4), T(j4,j3), T(j4,j4), wr1, wi1, wr2, wi2, cs, sn); if (j3+2<=n) { blas::rot(T(j3,_(j3+2,n)), T(j4,_(j3+2,n)), cs, sn); } blas::rot(T(_(1,j3-1),j3), T(_(1,j3-1),j4), cs, sn); if (computeQ) { blas::rot(Q(_,j3), Q(_,j4), cs, sn); } } } return 0; } } // namespace generic //== interface for native lapack =============================================== #ifdef USE_CXXLAPACK namespace external { template <typename MT, typename MQ, typename IndexType, typename VWORK> IndexType laexc_impl(bool computeQ, GeMatrix<MT> &T, GeMatrix<MQ> &Q, IndexType j1, IndexType n1, IndexType n2, DenseVector<VWORK> &work) { IndexType info; info = cxxlapack::laexc<IndexType>(computeQ, T.numRows(), T.data(), T.leadingDimension(), Q.data(), Q.leadingDimension(), j1, n1, n2, work.data()); ASSERT(info>=0); return info; } } // namespace external #endif // USE_CXXLAPACK //== public interface ========================================================== template <typename MT, typename MQ, typename IndexType, typename VWORK> IndexType laexc(bool computeQ, GeMatrix<MT> &T, GeMatrix<MQ> &Q, IndexType j1, IndexType n1, IndexType n2, DenseVector<VWORK> &work) { LAPACK_DEBUG_OUT("BEGIN: laexc"); // // Test the input parameters // # ifndef NDEBUG ASSERT(T.firstRow()==1); ASSERT(T.firstCol()==1); ASSERT(T.numRows()==T.numCols()); const IndexType n = T.numRows(); if (computeQ) { ASSERT(Q.firstRow()==1); ASSERT(Q.firstCol()==1); ASSERT(Q.numRows()==Q.numCols()); ASSERT(Q.numRows()==n); } ASSERT(j1>=1); ASSERT((n1==0) || (n1==1) || (n1==2)); ASSERT((n2==0) || (n2==1) || (n2==2)); ASSERT(work.firstIndex()==1); ASSERT(work.length()==n); # endif # ifdef CHECK_CXXLAPACK // // Make copies of output arguments // typename GeMatrix<MT>::NoView T_org = T; typename GeMatrix<MQ>::NoView Q_org = Q; typename DenseVector<VWORK>::NoView work_org = work; # endif // // Call implementation // IndexType info = LAPACK_SELECT::laexc_impl(computeQ, T, Q, j1, n1, n2, work); # ifdef CHECK_CXXLAPACK // // Make copies of results computed by the generic implementation // typename GeMatrix<MT>::NoView T_generic = T; typename GeMatrix<MQ>::NoView Q_generic = Q; typename DenseVector<VWORK>::NoView work_generic = work; // // restore output arguments // T = T_org; Q = Q_org; work = work_org; // // Compare generic results with results from the native implementation // IndexType info_ = external::laexc_impl(computeQ, T, Q, j1, n1, n2, work); bool failed = false; if (! isIdentical(T_generic, T, "T_generic", "T")) { std::cerr << "CXXLAPACK: T_generic = " << T_generic << std::endl; std::cerr << "F77LAPACK: T = " << T << std::endl; failed = true; } if (! isIdentical(Q_generic, Q, "Q_generic", "Q")) { std::cerr << "CXXLAPACK: Q_generic = " << Q_generic << std::endl; std::cerr << "F77LAPACK: Q = " << Q << std::endl; failed = true; } if (! isIdentical(work_generic, work, "work_generic", "work")) { std::cerr << "CXXLAPACK: work_generic = " << work_generic << std::endl; std::cerr << "F77LAPACK: work = " << work << std::endl; failed = true; } if (! isIdentical(info, info_, " info", "info_")) { std::cerr << "CXXLAPACK: info = " << info << std::endl; std::cerr << "F77LAPACK: info_ = " << info_ << std::endl; failed = true; } if (failed) { ASSERT(0); } # endif LAPACK_DEBUG_OUT("END: laexc"); return info; } //-- forwarding ---------------------------------------------------------------- template <typename MT, typename MQ, typename IndexType, typename VWORK> IndexType laexc(bool computeQ, MT &&T, MQ &&Q, IndexType j1, IndexType n1, IndexType n2, VWORK &&work) { CHECKPOINT_ENTER; const IndexType info = laexc(computeQ, T, Q, j1, n1, n2, work); CHECKPOINT_LEAVE; return info; } } } // namespace lapack, flens #endif // FLENS_LAPACK_LA_LAEXC_TCC
30.318786
80
0.493992
stip
0ccf10af95ca2ca06d8dfa73140636014ff6a649
5,939
cpp
C++
particlepm/target.cpp
particletk/particlepm
f30d5d96a045ef65dd8a60ce91ee1fe17b0d54a7
[ "MIT" ]
null
null
null
particlepm/target.cpp
particletk/particlepm
f30d5d96a045ef65dd8a60ce91ee1fe17b0d54a7
[ "MIT" ]
1
2018-09-22T15:16:28.000Z
2018-09-22T15:16:28.000Z
particlepm/target.cpp
particletk/particlepm
f30d5d96a045ef65dd8a60ce91ee1fe17b0d54a7
[ "MIT" ]
null
null
null
#include "libincludes.hpp" #include "target.hpp" #include <functional> #include <mutex> #include <queue> #include <thread> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/regex.hpp> PPM::Target::Target(const std::string& name, const std::string& dir, PPM::Target::Type type) : marked(false) , has_cpp(false) , type_(type) , name_(name) , dir_(dir) , c_("c11") , cpp_("c++11") , c_flags_("") , cpp_flags_("") , is_dynamic_(true) {} void PPM::Target::depends(const PPM::TargetPtr& other) { deps_.insert(other); } void PPM::Target::build() { if (marked) { return; } marked = true; for (PPM::TargetPtr dep : deps_) { dep->build(); } std::cerr << "Building " << name() << "(" << (int) type_ << ")" << std::endl; std::string dbg = PPM::dev ? "-g -ggdb" : ""; auto has_updated_headers = [&] (const std::string& compiler, const std::string& ifile, const std::string& ofile, std::function<void()> do_build) -> bool { std::string flags; std::string std; if (compiler == PPM_CC) { flags = c_flags_; std = c_; } else if (compiler == PPM_CXX) { flags = cpp_flags_; std = cpp_; } PPM::Utils::ExecStatus st = PPM::Utils::exec(compiler + " " + dbg + " " + PPM::envflags + " " + flags + " -fPIC -std=" + std + " -M " + ifile); if (st.code != 0) { std::cerr << st.data << std::endl; exit(1); } std::vector<std::string> files; boost::algorithm::split_regex(files, st.data, boost::regex("[\\\\\\r\\n\\s]+")); files.erase(files.begin(), files.begin() + 2); for (const std::string& file : files) { if (file.empty()) continue; if (access(ofile.c_str(), 0) == 0) { struct stat a, b; ::stat(file.c_str(), &a); ::stat(ofile.c_str(), &b); if (a.st_mtime > b.st_mtime) { do_build(); return true; } } } return false; }; auto runner = [&] (PPM::FilePtr file) { if (file->built) { return; } file->built = true; auto do_build = [&] () { char* p_ = getcwd(NULL, 1024); std::string p(p_); free(p_); PPM::Utils::chdir(dir_); std::string flags; std::string std; if (file->compiler == PPM_CC) { flags = c_flags_; std = c_; } else if (file->compiler == PPM_CXX) { flags = cpp_flags_; std = cpp_; } PPM::Utils::ExecStatus st = PPM::Utils::exec(file->compiler + " " + dbg + " " + PPM::envflags + " " + flags + " -Wl,-rpath='$ORIGIN' -fPIC -std=" + std + " -c " + file->ifile + " -o " + file->ofile); if (st.code != 0) { std::cerr << st.data << std::endl; ::exit(st.code); } PPM::Utils::chdir(p); }; if (::access(file->ofile.c_str(), 0) != 0) { do_build(); } else if (::access(file->ofile.c_str(), 0) == 0) { struct stat a, b; ::stat(file->ifile.c_str(), &a); ::stat(file->ofile.c_str(), &b); if (a.st_mtime > b.st_mtime) { do_build(); } else if (has_updated_headers(file->compiler, file->ifile, file->ofile, do_build)) {} } else if (has_updated_headers(file->compiler, file->ifile, file->ofile, do_build)) { } else { do_build(); } }; std::queue<PPM::FilePtr> q; std::mutex qm; std::vector<std::thread> threads; unsigned n = std::thread::hardware_concurrency(); auto thread_runner = [&] () { while (!q.empty()) { PPM::FilePtr f; { std::lock_guard<std::mutex> ql(qm); if (q.empty()) break; f = q.front(); q.pop(); } runner(f); } }; for (int i = 0; i < n; ++i) { threads.push_back(std::thread(thread_runner)); } for (PPM::FilePtr file : files_) { q.push(file); } for (std::thread& thr : threads) { thr.join(); } std::string compiler = has_cpp ? PPM_CXX : PPM_CC; PPM::Utils::mkdir(PPM::dist_dir); std::string out = PPM::Utils::to_path(std::vector<std::string>{ "dist", ((type_ == PPM::Target::Type::Executable) ? name() : ("lib" + name() + ".so")) }); std::string filenames = ""; for (PPM::FilePtr file : files_) { filenames += (" " + file->ofile); } std::string lt = is_dynamic_ ? "-rdynamic" : ""; PPM::Utils::ExecStatus st; if (type_ == PPM::Target::Type::Executable) { st = PPM::Utils::exec(compiler + " " + dbg + " " + PPM::envflags + " -Wl,-rpath='$ORIGIN' -fPIC -o " + out + " " + filenames + " " + cpp_flags_ + " " + c_flags_); } else { st = PPM::Utils::exec(compiler + " " + dbg + " " + PPM::envflags + " " + lt + " -shared -Wl,-rpath='$ORIGIN' -fPIC -o " + out + " " + filenames + " " + cpp_flags_ + " " + c_flags_); } if (st.code != 0) { std::cerr << st.data << std::endl; ::exit(st.code); } } std::string PPM::Target::name() { return name_; } void PPM::Target::name(const std::string& value) { name_ = value; } std::string PPM::Target::c() { return c_; } void PPM::Target::c(const std::string& value) { c_ = value; } std::string PPM::Target::cpp() { return cpp_; } void PPM::Target::cpp(const std::string& value) { cpp_ = value; } void PPM::Target::c_files(const std::vector<std::string>& filenames) { std::string suffix = (PPM::dev == true ? ".dev.o" : ".o"); for (const std::string& filename : filenames) { std::string f = dir_ + "/" + filename; files_.insert(PPM::FilePtr(new PPM::File(f, f + suffix, PPM_CC))); } } void PPM::Target::cpp_files(const std::vector<std::string>& filenames) { std::string suffix = (PPM::dev == true ? ".dev.o" : ".o"); has_cpp = true; for (const std::string& filename : filenames) { std::string f = dir_ + "/" + filename; files_.insert(PPM::FilePtr(new PPM::File(f, f + suffix, PPM_CXX))); } } void PPM::Target::c_flags(const std::string& flags) { c_flags_ += (" " + flags); } void PPM::Target::cpp_flags(const std::string& flags) { cpp_flags_ += (" " + flags); }
26.632287
205
0.550261
particletk
7b4aed605773f6a95e61f1f67b61d569a69c1b4a
805
hpp
C++
data/train/cpp/7b4aed605773f6a95e61f1f67b61d569a69c1b4aMyQmlWrapper.hpp
harshp8l/deep-learning-lang-detection
2a54293181c1c2b1a2b840ddee4d4d80177efb33
[ "MIT" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
data/train/cpp/7b4aed605773f6a95e61f1f67b61d569a69c1b4aMyQmlWrapper.hpp
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
5
2018-03-29T11:50:46.000Z
2021-04-26T13:33:18.000Z
data/train/cpp/7b4aed605773f6a95e61f1f67b61d569a69c1b4aMyQmlWrapper.hpp
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
24
2017-11-22T08:31:00.000Z
2022-03-27T01:22:31.000Z
#ifndef _TWEEDY_MYQMLWRAPPER_HPP_ #define _TWEEDY_MYQMLWRAPPER_HPP_ #include "Animal.hpp" #include "model.h" #include <QtCore/QObject> #include <boost/lexical_cast.hpp> class MyQmlWrapper : public QObject { Q_OBJECT public: Q_PROPERTY( AnimalModel* animalModel READ getAnimalModel NOTIFY animalModelChanged ) AnimalModel* getAnimalModel() { return &_model; } Q_INVOKABLE void add() { static int i = 0; _model.addAnimal( Animal( ("AAA"+boost::lexical_cast<std::string>(i++)).c_str(), "BBB") ); } // Q_INVOKABLE void modify() // { // _model.getAnimals()[1] // } Q_INVOKABLE void remove() { // _model.beginRemoveRows( _model., 1, 2); _model.removeRow( 1 ); // _model.endRemoveRows(); } Q_SIGNALS: void animalModelChanged(); private: AnimalModel _model; }; #endif
18.72093
92
0.700621
harshp8l
7b4fc4f888c5991277a407c54dbe6a23c1547725
1,388
cpp
C++
073-set-matrix-zeroes/set-matrix-zeroes.cpp
TJUSsr/leetcodesolution
8244de2d76c9e8e5b9d98dd1e8efed4d680d44ee
[ "MIT" ]
null
null
null
073-set-matrix-zeroes/set-matrix-zeroes.cpp
TJUSsr/leetcodesolution
8244de2d76c9e8e5b9d98dd1e8efed4d680d44ee
[ "MIT" ]
2
2021-03-31T19:10:41.000Z
2021-12-13T19:58:15.000Z
073-set-matrix-zeroes/set-matrix-zeroes.cpp
TJUSsr/leetcodesolution
8244de2d76c9e8e5b9d98dd1e8efed4d680d44ee
[ "MIT" ]
null
null
null
// Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. // // Example 1: // // // Input: // [ //   [1,1,1], //   [1,0,1], //   [1,1,1] // ] // Output: // [ //   [1,0,1], //   [0,0,0], //   [1,0,1] // ] // // // Example 2: // // // Input: // [ //   [0,1,2,0], //   [3,4,5,2], //   [1,3,1,5] // ] // Output: // [ //   [0,0,0,0], //   [0,4,5,0], //   [0,3,1,0] // ] // // // Follow up: // // // A straight forward solution using O(mn) space is probably a bad idea. // A simple improvement uses O(m + n) space, but still not the best solution. // Could you devise a constant space solution? // // static const auto _=[](){ std::ios::sync_with_stdio(false); cin.tie(nullptr); return nullptr; }(); class Solution { public: void setZeroes(vector<vector<int>>& matrix) { int col0 = 1, rows = matrix.size(), cols = matrix[0].size(); for (int i = 0; i < rows; i++) { if (matrix[i][0] == 0) col0 = 0; for (int j = 1; j < cols; j++) if (matrix[i][j] == 0) matrix[i][0] = matrix[0][j] = 0; } for (int i = rows - 1; i >= 0; i--) { for (int j = cols - 1; j >= 1; j--) if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0; if (col0 == 0) matrix[i][0] = 0; } } };
19.013699
96
0.43732
TJUSsr
7b50271e902e2ee0a20d71fbc50f29f862bdf926
2,197
cpp
C++
Algorithms/126.Word-Ladder-II/solution.cpp
moranzcw/LeetCode_Solutions
49a7e33b83d8d9ce449c758717f74a69e72f808e
[ "MIT" ]
178
2017-07-09T23:13:11.000Z
2022-02-26T13:35:06.000Z
Algorithms/126.Word-Ladder-II/solution.cpp
cfhyxxj/LeetCode-NOTES
455d33aae54d065635d28ebf37f815dc4ace7e63
[ "MIT" ]
1
2020-10-10T16:38:03.000Z
2020-10-10T16:38:03.000Z
Algorithms/126.Word-Ladder-II/solution.cpp
cfhyxxj/LeetCode-NOTES
455d33aae54d065635d28ebf37f815dc4ace7e63
[ "MIT" ]
82
2017-08-19T07:14:39.000Z
2022-02-17T14:07:55.000Z
class Solution { public: vector<vector<string>> findLadders(string start, string end, unordered_set<string> &dict) { vector<vector<string> >ans; if(start == end) return ans; unordered_set<string>current , next; unordered_set<string> flag; unordered_map<string,vector<string> > father; current.insert(start); bool found = false; while(!current.empty() && !found) { for(const auto &x : current) { flag.insert(x); } for(auto x : current) { for(int i = 0 ; i < x.size() ; ++i) { for(int j = 'a' ; j <= 'z' ; ++j) { if(x[i] == j) continue; string tmp = x; tmp[i] = j; if(tmp == end) found = true; if(dict.find(tmp) != dict.end() && flag.find(tmp) == flag.end()) { next.insert(tmp); father[tmp].push_back(x); } } } } current.clear(); swap(current, next); } if(found) { vector<string> c; dfs(ans , father , c , start , end); } return ans; } private: void dfs(vector<vector<string> >&ans, unordered_map<string,vector<string> >& father , vector<string>& c , string& start , string& now) { c.push_back(now); if(now == start) { ans.push_back(c); reverse(ans.back().begin() , ans.back().end()); c.pop_back(); return; } auto que = father.find(now) -> second; for(auto& x : que) { dfs(ans , father , c , start , x); } c.pop_back(); } };
28.532468
94
0.359126
moranzcw
7b5188433ee2cd8f6515d1dae2da47d8dce1c51d
5,120
cpp
C++
src/console.cpp
hammelm/mempeek
8e9d0de7a6a2313abfbe7e512b5048993a0a2e61
[ "BSD-2-Clause" ]
null
null
null
src/console.cpp
hammelm/mempeek
8e9d0de7a6a2313abfbe7e512b5048993a0a2e61
[ "BSD-2-Clause" ]
18
2015-10-13T04:31:19.000Z
2016-08-18T09:20:21.000Z
src/console.cpp
hammelm/mempeek
8e9d0de7a6a2313abfbe7e512b5048993a0a2e61
[ "BSD-2-Clause" ]
3
2017-03-04T14:14:13.000Z
2020-01-13T08:42:25.000Z
/* Copyright (c) 2015-2018, Martin Hammel All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "console.h" #include <sstream> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef USE_EDITLINE #include <fstream> #include <sys/types.h> #include <unistd.h> #include <pwd.h> #else #include <iostream> #endif using namespace std; ////////////////////////////////////////////////////////////////////////////// // class Console implementation ////////////////////////////////////////////////////////////////////////////// char* Console::s_Prompt = nullptr; Console::Console( string name, string histfile, size_t histsize ) { // only one instance of Console is allowed if( s_Prompt ) abort(); s_Prompt = strcpy( new char[3], "> " ); #ifdef USE_EDITLINE // create histfile name m_Histfile = histfile; if( histfile.length() > 0 && histfile[0] == '~' ) { passwd* pwd = getpwuid( getuid() ); if( pwd ) { m_Histfile = pwd->pw_dir; m_Histfile += histfile.substr(1); } } // init history HistEvent hev; m_History = history_init(); history( m_History, &hev, H_SETSIZE, histsize ); history( m_History, &hev, H_SETUNIQUE, 1 ); if( m_Histfile.length() > 0 ) { ifstream histfile( m_Histfile.c_str() ); for(;;) { string line; std::getline( histfile, line ); if( histfile.bad() || histfile.fail() ) break; line += '\n'; history( m_History, &hev, H_ENTER, line.c_str() ); if( histfile.eof() ) break; } } // init editline m_Editline = el_init( name.c_str(), stdin, stdout, stderr ); el_set( m_Editline, EL_SIGNAL, 1 ); el_set( m_Editline, EL_EDITOR, "emacs" ); el_set( m_Editline, EL_PROMPT, Console::get_prompt ); el_set( m_Editline, EL_HIST, history, m_History ); el_set( m_Editline, EL_ADDFN, "ed-complete", "", completion_callback ); el_set( m_Editline, EL_BIND, "^I", "ed-complete", nullptr ); #else (void)histfile; (void)histsize; #endif } Console::~Console() { #ifdef USE_EDITLINE // save history if( m_Histfile.length() > 0 ) { ofstream histfile( m_Histfile.c_str(), ios::trunc ); HistEvent hev; history( m_History, &hev, H_LAST ); for(;;) { histfile << hev.str; if( history( m_History, &hev, H_PREV ) < 0 ) break; } } // cleanup el_end( m_Editline ); history_end( m_History ); #endif delete[] s_Prompt; s_Prompt = nullptr; } void Console::set_prompt( string prompt ) { delete[] s_Prompt; s_Prompt = strcpy( new char[ prompt.length() + 1 ], prompt.c_str() ); } void Console::set_completion( std::function<unsigned char( EditLine*, int )> completion ) { #ifdef USE_EDITLINE s_Completion = completion; #else (void)completion; #endif } void Console::set_clientdata( void* data ) { #ifdef USE_EDITLINE el_set( m_Editline, EL_CLIENTDATA, data ); #else (void)data; #endif } string Console::get_line() { #ifdef USE_EDITLINE int count; const char* line = el_gets( m_Editline, &count ); // do not add to history if line is empty if( line ) { for( const char* l = line; *l; l++ ) { if( !isspace(*l) ) { HistEvent hev; history( m_History, &hev, H_ENTER, line ); return line; } } } return ""; #else cout << s_Prompt << flush; string ret = ""; getline( cin, ret ); ret += '\n'; return ret; #endif } Console::tokens_t Console::get_tokens() { istringstream line( get_line() ); tokens_t tokens; for(;;) { string token; line >> token; if( line.bad() || line.fail() ) return tokens; tokens.push_back( token ); if( line.eof() ) return tokens; } } #ifdef USE_EDITLINE std::function<unsigned char( EditLine*, int )> Console::s_Completion = nullptr; char* Console::get_prompt( EditLine* ) { return s_Prompt; } unsigned char Console::completion_callback( EditLine* el, int ch ) { if( s_Completion ) return s_Completion( el, ch ); else return CC_NORM; } #endif
24.7343
89
0.666992
hammelm
7b5289576635ef21eaf18cef85647c333164cf88
916
cpp
C++
samples/demo/src/source.cpp
ninjaoflight/appcenter-sdk-cpp
1e14459e3161694da6b8f313ee1cdd088cc21954
[ "BSD-3-Clause" ]
null
null
null
samples/demo/src/source.cpp
ninjaoflight/appcenter-sdk-cpp
1e14459e3161694da6b8f313ee1cdd088cc21954
[ "BSD-3-Clause" ]
null
null
null
samples/demo/src/source.cpp
ninjaoflight/appcenter-sdk-cpp
1e14459e3161694da6b8f313ee1cdd088cc21954
[ "BSD-3-Clause" ]
null
null
null
#include <appcenter/analytics/analytics.hpp> #include <appcenter/appcenter.hpp> #include <string_view> int main(int, char **) { // get the enviroment variable #ifdef APPCENTER_SAMPLE_APP_SECRET const std::string_view appSecret = APPCENTER_SAMPLE_APP_SECRET; #else // if not using meson, you can setup your own app secret here //* NOTE: it is not recommended to have the app secret directly in the //* source code constexpr std::string_view appSecret = "YOUR_APP_SECRET"; #endif // we can control the SDK log level appcenter::AppCenter &appCenterSDK = appcenter::AppCenter::getInstance(); appcenter::analytics::Analytics &analytics = appcenter::analytics::Analytics::getInstance(); appCenterSDK.setLogLevel(appcenter::core::logging::LogLevel::Verbose); // or configure the SDK with an app secret appCenterSDK.configure(appSecret); if (appCenterSDK.isConfigured()){ appCenterSDK.start(&analytics); } }
36.64
93
0.768559
ninjaoflight
7b53a23a7e78b0b580267532415bd627f5a6e84a
469
cpp
C++
problems/T/T1011/std.cpp
Tiphereth-A/problems
78724d2f559bf18b4999c89ef3bf9b8523fc6d49
[ "MIT" ]
1
2022-01-23T09:26:35.000Z
2022-01-23T09:26:35.000Z
problems/T/T1011/std.cpp
Tiphereth-A/problems
78724d2f559bf18b4999c89ef3bf9b8523fc6d49
[ "MIT" ]
null
null
null
problems/T/T1011/std.cpp
Tiphereth-A/problems
78724d2f559bf18b4999c89ef3bf9b8523fc6d49
[ "MIT" ]
1
2022-03-08T07:21:04.000Z
2022-03-08T07:21:04.000Z
#include <iostream> #include <cstring> using namespace std; const int maxn = 1e4+5; const int maxw = 1e7+5; typedef long long ll; ll m[maxn], w[maxn], v[maxn]; ll dp[maxw]; int main() { int n, W; cin>>n>>W; for(int i=1;i<=n;i++) cin>>m[i]>>w[i]>>v[i]; for(int i=1;i<=n;i++) for(int j=W;j>=0;j--) for(int k=0;k*w[i]<=j&&k<=m[i];k++) dp[j]=max(dp[j-k*w[i]]+k*v[i], dp[j]); cout<<dp[W]<<endl; return 0; }
22.333333
54
0.492537
Tiphereth-A
7b54174cd2b5839bb7543172835d95979e8a1aaf
2,817
cpp
C++
keyzz/runners/runner.cpp
DmitryDzz/keyzz
85e63ea465116e0b7f37aa8633a6d6beeabd6779
[ "MIT" ]
null
null
null
keyzz/runners/runner.cpp
DmitryDzz/keyzz
85e63ea465116e0b7f37aa8633a6d6beeabd6779
[ "MIT" ]
6
2021-05-05T18:08:55.000Z
2021-05-15T16:01:00.000Z
keyzz/runners/runner.cpp
DmitryDzz/keyzz
85e63ea465116e0b7f37aa8633a6d6beeabd6779
[ "MIT" ]
null
null
null
// Copyright 2021 DmitryDzz #include "runner.hpp" #include <logger/easylogging++.h> #include <algorithm> #include <minunity/engine.hpp> #include "../tracks/race.hpp" #include "../tracks/track.hpp" using minunity::Engine; using minunity::Layer; using minunity::Sprite; using keyzz::BaseRunner; using keyzz::Race; using keyzz::Runner; using keyzz::Track; Runner::Runner(int x, int y, std::shared_ptr<Track> track_record) : BaseRunner(x, y, track_record) { } void Runner::awake() { BaseRunner::awake(); } void Runner::update() { BaseRunner::update(); if (is_destroyed() || !get_active() || !start_time_) return; uint32_t delta_time = Engine::get_instance()->get_time()->get_time() - start_time_.value(); bool is_previous_lap = false; bool is_next_lap = false; bool is_finish = false; int32_t x = get_start_x() + track_->get_delta_x(delta_time, lap_first_index_, lap_last_index_, &is_previous_lap, &is_next_lap, &is_finish); // LOG(INFO) << "[Runner] " << track_->get_name() << ": x=" << x << " get_start_x()=" << // get_start_x() << " is_finish=" << is_finish; if (get_sprite() != nullptr) { if (is_previous_lap) { get_sprite()->set_frame_index(1); // << } else if (is_next_lap) { get_sprite()->set_frame_index(2); // >> } else { get_sprite()->set_frame_index(is_finish ? 3 : 0); // (x) } } set_x(x); if (is_finish) finish_race(); } void Runner::render_layer(Layer layer) { if (is_destroyed() || get_sprite() == nullptr) return; BaseRunner::render_layer(layer); } void Runner::start_lap(int lap_index, int laps_count) { BaseRunner::start_lap(lap_index, laps_count); if (!start_time_) { start_time_ = Engine::get_instance()->get_time()->get_time(); // LOG(INFO) << "[Runner] n=" << track_->get_name().c_str() << // " start_time_=" << start_time_.value(); } lap_first_index_ = lap_index * Race::LAP_MAX_SIZE; lap_last_index_ = std::min(lap_first_index_ + Race::LAP_MAX_SIZE - 1, track_->get_size() - 2); // LOG(INFO) << "[Runner] n=" << track_->get_name().c_str() << // " li=" << lap_index << " lc=" << laps_count << // " lfi=" << lap_first_index_ << " lli=" << lap_last_index_; } void Runner::finish_race() { start_time_ = std::nullopt; track_->set_finished(true); } Sprite* Runner::create_sprite() { Sprite *result = new Sprite(3, 1, 4); std::wstring name = track_->get_name(); std::wstring upper_name = name; // upper_name is for the finish. std::transform(upper_name.begin(), upper_name.end(), upper_name.begin(), std::towupper); std::wstring res = name + L"<< " + L" >>" + upper_name; result->load(res.c_str()); return result; }
30.290323
98
0.617678
DmitryDzz
7b5632ae2858a2ab540edf2ed8a5590e9828aafa
1,013
cpp
C++
test/Graphics/ConvexShape.cpp
jlmartinnc/SFML
709530d062ac9c452f50b06d37cdd800c2f9ba68
[ "Zlib" ]
1
2020-09-11T06:28:37.000Z
2020-09-11T06:28:37.000Z
test/Graphics/ConvexShape.cpp
jlmartinnc/SFML
709530d062ac9c452f50b06d37cdd800c2f9ba68
[ "Zlib" ]
1
2022-02-04T01:20:06.000Z
2022-02-04T01:20:06.000Z
test/Graphics/ConvexShape.cpp
ChrisThrasher/SFML
757cb36d30cb3090945657580f9b43d511535bc2
[ "Zlib" ]
null
null
null
#include <SFML/Graphics/ConvexShape.hpp> #include "SystemUtil.hpp" #include <doctest.h> TEST_CASE("sf::ConvexShape class - [graphics]") { SUBCASE("Default constructor") { const sf::ConvexShape convex; CHECK(convex.getPointCount() == 0); } SUBCASE("Point count constructor") { const sf::ConvexShape convex(15); CHECK(convex.getPointCount() == 15); for (std::size_t i = 0; i < convex.getPointCount(); ++i) CHECK(convex.getPoint(i) == sf::Vector2f(0, 0)); } SUBCASE("Set point count") { sf::ConvexShape convex; convex.setPointCount(42); CHECK(convex.getPointCount() == 42); for (std::size_t i = 0; i < convex.getPointCount(); ++i) CHECK(convex.getPoint(i) == sf::Vector2f(0, 0)); } SUBCASE("Set point") { sf::ConvexShape convex; convex.setPointCount(1); convex.setPoint(0, {3, 4}); CHECK(convex.getPoint(0) == sf::Vector2f(3, 4)); } }
25.974359
64
0.572557
jlmartinnc
7b6105212e21fdca1626caf6de745b0b2266f941
767
hpp
C++
multiview/multiview_cpp/src/cuda/perceive/graphics/rgb-to-lab.hpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
5
2021-09-03T23:12:08.000Z
2022-03-04T21:43:32.000Z
multiview/multiview_cpp/src/cuda/perceive/graphics/rgb-to-lab.hpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
3
2021-09-08T02:57:46.000Z
2022-02-26T05:33:02.000Z
multiview/multiview_cpp/src/cuda/perceive/graphics/rgb-to-lab.hpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
2
2021-09-26T03:14:40.000Z
2022-01-26T06:42:52.000Z
#pragma once #include "perceive/graphics/image-container.hpp" #include <opencv2/opencv.hpp> #include <type_traits> namespace perceive::cuda { #ifdef WITH_CUDA class ARGBToLABConversion { // Regions of zero copy memory for input and output data. mutable cv::cuda::HostMem input_buffer{cv::cuda::HostMem::AllocType::SHARED}; mutable cv::cuda::HostMem output_buffer{ cv::cuda::HostMem::AllocType::SHARED}; mutable cv::cuda::Stream stream; mutable std::mutex lock; public: Vec3fImage convert(const ARGBImage& argb) const; }; #else class ARGBToLABConversion { public: Vec3fImage convert(const ARGBImage& argb) const { FATAL("Cuda is not available!"); return Vec3fImage{}; } }; #endif } // namespace perceive::cuda
18.707317
80
0.709257
prcvlabs
7b63c64671e7ccccef941ef5e3ec90c99898f461
2,190
cpp
C++
HTTPSYS/HttpQueryRequestQueueProperty.cpp
zYg-sys/Marlin
eeabb4d324c5f8d253a50c106208bb833cb824e8
[ "MIT" ]
23
2016-09-16T11:25:54.000Z
2022-03-03T07:18:57.000Z
HTTPSYS/HttpQueryRequestQueueProperty.cpp
edwig/HTTPSYS
885f94149e7db9fb8c7dad2c42c916d31b80a862
[ "MIT" ]
26
2016-10-21T11:07:54.000Z
2022-03-05T18:27:03.000Z
HTTPSYS/HttpQueryRequestQueueProperty.cpp
zYg-sys/Marlin
eeabb4d324c5f8d253a50c106208bb833cb824e8
[ "MIT" ]
7
2018-09-11T12:17:46.000Z
2021-07-08T09:10:04.000Z
////////////////////////////////////////////////////////////////////////// // // USER-SPACE IMPLEMENTTION OF HTTP.SYS // // 2018 (c) ir. W.E. Huisman // License: MIT // ////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "http_private.h" #include "RequestQueue.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif HTTPAPI_LINKAGE ULONG WINAPI HttpQueryRequestQueueProperty(_In_ HANDLE RequestQueueHandle ,_In_ HTTP_SERVER_PROPERTY Property ,_Out_writes_bytes_to_opt_(PropertyInformationLength, *ReturnLength) PVOID PropertyInformation ,_In_ ULONG PropertyInformationLength ,_Reserved_ _In_ ULONG Reserved1 ,_Out_opt_ PULONG ReturnLength OPTIONAL ,_Reserved_ _In_ PVOID Reserved2) { // Must always be zero if(Reserved1 || Reserved2) { return ERROR_INVALID_PARAMETER; } // Parameters must be given if(PropertyInformationLength == 0) { return ERROR_INVALID_PARAMETER; } // Finding our request queue RequestQueue* queue = GetRequestQueueFromHandle(RequestQueueHandle); if (queue == nullptr) { return ERROR_INVALID_PARAMETER; } if(Property == HttpServer503VerbosityProperty) { if(PropertyInformationLength >= sizeof(HTTP_503_RESPONSE_VERBOSITY)) { *((PHTTP_503_RESPONSE_VERBOSITY)PropertyInformation) = queue->GetVerbosity(); return NO_ERROR; } } else if(Property == HttpServerQueueLengthProperty) { if(PropertyInformationLength == sizeof(ULONG)) { *((PULONG)PropertyInformation) = queue->GetQueueLength(); return NO_ERROR; } } else if(Property == HttpServerStateProperty) { if(PropertyInformationLength >= sizeof(HTTP_STATE_INFO)) { PHTTP_STATE_INFO info = (PHTTP_STATE_INFO)PropertyInformation; info->Flags.Present = 1; info->State = queue->GetEnabledState(); return NO_ERROR; } } return ERROR_INVALID_PARAMETER; }
28.441558
123
0.605479
zYg-sys
7b65ab7af31fb70217575f1e1d3ac1277e15408c
2,213
hpp
C++
compendium/ServiceComponent/include/cppmicroservices/servicecomponent/runtime/dto/ServiceReferenceDTO.hpp
fmilano/CppMicroServices
b7e79edb558a63e45f6788e4a8b4e787cf956689
[ "Apache-2.0" ]
588
2015-10-07T15:55:08.000Z
2022-03-29T00:35:44.000Z
compendium/ServiceComponent/include/cppmicroservices/servicecomponent/runtime/dto/ServiceReferenceDTO.hpp
fmilano/CppMicroServices
b7e79edb558a63e45f6788e4a8b4e787cf956689
[ "Apache-2.0" ]
459
2015-10-05T23:29:59.000Z
2022-03-29T14:13:37.000Z
compendium/ServiceComponent/include/cppmicroservices/servicecomponent/runtime/dto/ServiceReferenceDTO.hpp
fmilano/CppMicroServices
b7e79edb558a63e45f6788e4a8b4e787cf956689
[ "Apache-2.0" ]
218
2015-11-04T08:19:48.000Z
2022-03-24T02:17:08.000Z
/*============================================================================= Library: CppMicroServices Copyright (c) The CppMicroServices developers. See the COPYRIGHT file at the top-level directory of this distribution and at https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT . Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef ServiceReferenceDTO_hpp #define ServiceReferenceDTO_hpp #include <string> #include <unordered_map> #include <vector> #include "cppmicroservices/Any.h" #include "cppmicroservices/servicecomponent/ServiceComponentExport.h" namespace cppmicroservices { namespace framework { namespace dto { /** \defgroup gr_servicereferencedto ServiceReferenceDTO \brief Groups ServiceReferenceDTO related symbols. */ /** * \ingroup gr_servicereferencedto * * A representation of a satisfied reference. */ struct US_ServiceComponent_EXPORT ServiceReferenceDTO { /** * The id of the service. * * @see Constants#SERVICE_ID */ unsigned long id; /** * The id of the bundle that registered the service. * * @see ServiceReference#GetBundle() */ unsigned long bundle; /** * The properties for the service. * * The value type must be a numerical type, Boolean, String or a container * of any of the former. * * @see ServiceReference#GetProperty(String) */ std::unordered_map<std::string, cppmicroservices::Any> properties; /** * The ids of the bundles that are using the service. * * @see ServiceReference#GetUsingBundles() */ std::vector<unsigned long> usingBundles; }; } } } #endif /* ServiceReferenceDTO_hpp */
26.035294
81
0.685495
fmilano
7b68b58045d5fb23c0274ac39917788df9d13bac
1,499
cc
C++
src/ui/a11y/lib/gesture_manager/tests/mocks/mock_gesture_listener.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
src/ui/a11y/lib/gesture_manager/tests/mocks/mock_gesture_listener.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
src/ui/a11y/lib/gesture_manager/tests/mocks/mock_gesture_listener.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
73
2019-03-06T18:55:23.000Z
2022-03-26T12:04:51.000Z
// Copyright 2020 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/ui/a11y/lib/gesture_manager/tests/mocks/mock_gesture_listener.h" namespace accessibility_test { MockGestureListener::MockGestureListener() : binding_(this) { binding_.set_error_handler([this](zx_status_t status) { is_registered_ = false; }); } fidl::InterfaceHandle<fuchsia::accessibility::gesture::Listener> MockGestureListener::NewBinding() { is_registered_ = true; return binding_.NewBinding(); } bool MockGestureListener::is_registered() const { return is_registered_; } void MockGestureListener::OnGesture( fuchsia::accessibility::gesture::Type gesture_type, fuchsia::accessibility::gesture::Listener::OnGestureCallback callback) { gesture_type_ = gesture_type; callback(on_gesture_callback_status_, utterance_); } void MockGestureListener::SetUtterance(std::string utterance) { if (utterance.empty()) { utterance_ = nullptr; return; } utterance_ = fidl::StringPtr(std::move(utterance)); } void MockGestureListener::SetOnGestureCallbackStatus(bool status) { on_gesture_callback_status_ = status; } void MockGestureListener::SetGestureType(fuchsia::accessibility::gesture::Type gesture_type) { gesture_type_ = gesture_type; } fuchsia::accessibility::gesture::Type MockGestureListener::gesture_type() const { return gesture_type_; } } // namespace accessibility_test
30.591837
100
0.776518
allansrc
7b69f349009cebdea5bc92cc227cefe110f64c60
1,214
cpp
C++
data/dailyCodingProblem672.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
2
2020-09-04T20:56:23.000Z
2021-06-11T07:42:26.000Z
data/dailyCodingProblem672.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
data/dailyCodingProblem672.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /* You are given an array of arrays of integers, where each array corresponds to a row in a triangle of numbers. For example, [[1], [2, 3], [1, 5, 1]] represents the triangle: 1 2 3 1 5 1 We define a path in the triangle to start at the top and go down one row at a time to an adjacent value, eventually ending with an entry on the bottom row. For example, 1 -> 3 -> 5. The weight of the path is the sum of the entries. Write a program that returns the weight of the maximum weight path. */ int maxSumPathHelper(int i, int j, int& n, vector<vector<int>>& arr, unordered_map<string, int>& dp){ if(i == n){ return 0; } string find_string = to_string(i) + "$" + to_string(j); if(dp.find(find_string) != dp.end()) return dp[find_string]; dp[find_string] = arr[i][j] + max(maxSumPathHelper(i+1, j, n, arr, dp), maxSumPathHelper(i+1, j+1, n, arr, dp)); return dp[find_string]; } int maxSumPath(vector<vector<int>>& arr){ int n = arr.size(); unordered_map<string, int> dp; return maxSumPathHelper(0, 0, n, arr, dp); } // main function int main(){ vector<vector<int>> arr = {{1}, {2, 3}, {1, 5, 1}}; cout << maxSumPath(arr) << "\n"; return 0; }
25.829787
113
0.666392
vidit1999