hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
8ef60977c3acc029e6540d17f9aef44f5f3376c5
13,949
cpp
C++
source/test/mp-integer-unsigned-arithmetic-test.cpp
CaptainCrowbar/rs-sci
40768e7665c555f28e4b0ca2b1c2d1fa2da9775a
[ "BSL-1.0" ]
null
null
null
source/test/mp-integer-unsigned-arithmetic-test.cpp
CaptainCrowbar/rs-sci
40768e7665c555f28e4b0ca2b1c2d1fa2da9775a
[ "BSL-1.0" ]
null
null
null
source/test/mp-integer-unsigned-arithmetic-test.cpp
CaptainCrowbar/rs-sci
40768e7665c555f28e4b0ca2b1c2d1fa2da9775a
[ "BSL-1.0" ]
null
null
null
#include "rs-sci/mp-integer.hpp" #include "rs-format/format.hpp" #include "rs-unit-test.hpp" #include <string> #include <vector> using namespace RS::Format; using namespace RS::Sci; namespace { using ByteVector = std::vector<uint8_t>; std::string hexdump(const ByteVector& v) { std::string s(reinterpret_cast<const char*>(v.data()), v.size()); return format_string(s, "x"); } } void test_rs_sci_mp_integer_unsigned_arithmetic() { MPN x, y, z, q, r; std::string s; TRY(x = 0); TEST_EQUAL(x.bits(), 0u); TRY(s = x.str("b")); TEST_EQUAL(s, "0"); TRY(s = x.str("n")); TEST_EQUAL(s, "0"); TRY(s = x.str("x")); TEST_EQUAL(s, "0"); TRY(y = x + 15); TEST_EQUAL(y.bits(), 4u); TRY(s = to_string(y)); TEST_EQUAL(s, "15"); TRY(s = y.str("x")); TEST_EQUAL(s, "f"); TRY(y = 15 - x); TEST_EQUAL(y.bits(), 4u); TRY(s = to_string(y)); TEST_EQUAL(s, "15"); TRY(s = y.str("x")); TEST_EQUAL(s, "f"); TRY(x = 0x123456789abcdef0ull); TRY(y = 0xffffffffffffffffull); TEST_EQUAL(x.bits(), 61u); TEST_EQUAL(y.bits(), 64u); TRY(s = to_string(x)); TEST_EQUAL(s, "1311768467463790320"); TRY(s = to_string(y)); TEST_EQUAL(s, "18446744073709551615"); TRY(z = x + 15); TEST_EQUAL(z.bits(), 61u); TRY(s = to_string(z)); TEST_EQUAL(s, "1311768467463790335"); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdeff"); TRY(z = x + y); TEST_EQUAL(z.bits(), 65u); TRY(s = to_string(z)); TEST_EQUAL(s, "19758512541173341935"); TRY(s = z.str("x")); TEST_EQUAL(s, "1123456789abcdeef"); TRY(z = y - 15); TEST_EQUAL(z.bits(), 64u); TRY(s = to_string(z)); TEST_EQUAL(s, "18446744073709551600"); TRY(s = z.str("x")); TEST_EQUAL(s, "fffffffffffffff0"); TRY(z = y - x); TEST_EQUAL(z.bits(), 64u); TRY(s = to_string(z)); TEST_EQUAL(s, "17134975606245761295"); TRY(s = z.str("x")); TEST_EQUAL(s, "edcba9876543210f"); TRY(z = x * y); TEST_EQUAL(z.bits(), 125u); TRY(s = to_string(z)); TEST_EQUAL(s, "24197857203266734862169780735577366800"); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdeefedcba98765432110"); TRY(x = MPN("123456789123456789123456789123456789123456789")); TRY(y = MPN("123456789123456789123456789123456789")); TRY(z = x - y); TEST_EQUAL(z, MPN("123456789000000000000000000000000000000000000")); TRY(y = MPN("123456789123456789123456789123456789000000000")); TRY(z = x - y); TEST_EQUAL(z, MPN("123456789")); TRY(x = MPN("123456789123456789123456789123456789123456789")); TRY(y = MPN("1357913579135791357913579")); TRY(z = x - y); TEST_EQUAL(z, MPN("123456789123456789122098875544320997765543210")); TRY(x = MPN("123456789123456789123456789123456789123456789")); TRY(y = MPN("123456789")); TRY(q = x / y); TRY(r = x % y); TEST_EQUAL(q, MPN("1000000001000000001000000001000000001")); TEST_EQUAL(r, MPN("0")); TRY(y = MPN("987654321")); TRY(q = x / y); TRY(r = x % y); TEST_EQUAL(q, MPN("124999998985937499000175780249997801")); TEST_EQUAL(r, MPN("725308668")); TRY(y = MPN("987654321987654321987654321987654321987654321")); TRY(q = x / y); TRY(r = x % y); TEST_EQUAL(q, MPN("0")); TEST_EQUAL(r, MPN("123456789123456789123456789123456789123456789")); TRY(y = {}); } void test_rs_sci_mp_integer_unsigned_arithmetic_powers() { MPN x, y; std::string s; TRY(x = 0); TRY(y = x.pow(0)); TEST_EQUAL(y.str(), "1"); TRY(x = 0); TRY(y = x.pow(1)); TEST_EQUAL(y.str(), "0"); TRY(x = 0); TRY(y = x.pow(2)); TEST_EQUAL(y.str(), "0"); TRY(x = 0); TRY(y = x.pow(3)); TEST_EQUAL(y.str(), "0"); TRY(x = 1); TRY(y = x.pow(0)); TEST_EQUAL(y.str(), "1"); TRY(x = 1); TRY(y = x.pow(1)); TEST_EQUAL(y.str(), "1"); TRY(x = 1); TRY(y = x.pow(2)); TEST_EQUAL(y.str(), "1"); TRY(x = 1); TRY(y = x.pow(3)); TEST_EQUAL(y.str(), "1"); TRY(x = 10); TRY(y = x.pow(0)); TEST_EQUAL(y.str(), "1"); TRY(x = 10); TRY(y = x.pow(1)); TEST_EQUAL(y.str(), "10"); TRY(x = 10); TRY(y = x.pow(2)); TEST_EQUAL(y.str(), "100"); TRY(x = 10); TRY(y = x.pow(3)); TEST_EQUAL(y.str(), "1000"); TRY(x = 10); TRY(y = x.pow(4)); TEST_EQUAL(y.str(), "10000"); TRY(x = 10); TRY(y = x.pow(5)); TEST_EQUAL(y.str(), "100000"); TRY(x = 10); TRY(y = x.pow(6)); TEST_EQUAL(y.str(), "1000000"); TRY(x = 10); TRY(y = x.pow(7)); TEST_EQUAL(y.str(), "10000000"); TRY(x = 10); TRY(y = x.pow(8)); TEST_EQUAL(y.str(), "100000000"); TRY(x = 10); TRY(y = x.pow(9)); TEST_EQUAL(y.str(), "1000000000"); TRY(x = 10); TRY(y = x.pow(10)); TEST_EQUAL(y.str(), "10000000000"); TRY(x = 10); TRY(y = x.pow(11)); TEST_EQUAL(y.str(), "100000000000"); TRY(x = 10); TRY(y = x.pow(12)); TEST_EQUAL(y.str(), "1000000000000"); TRY(x = 10); TRY(y = x.pow(13)); TEST_EQUAL(y.str(), "10000000000000"); TRY(x = 10); TRY(y = x.pow(14)); TEST_EQUAL(y.str(), "100000000000000"); TRY(x = 10); TRY(y = x.pow(15)); TEST_EQUAL(y.str(), "1000000000000000"); TRY(x = 10); TRY(y = x.pow(16)); TEST_EQUAL(y.str(), "10000000000000000"); TRY(x = 10); TRY(y = x.pow(17)); TEST_EQUAL(y.str(), "100000000000000000"); TRY(x = 10); TRY(y = x.pow(18)); TEST_EQUAL(y.str(), "1000000000000000000"); TRY(x = 10); TRY(y = x.pow(19)); TEST_EQUAL(y.str(), "10000000000000000000"); TRY(x = 10); TRY(y = x.pow(20)); TEST_EQUAL(y.str(), "100000000000000000000"); TRY(x = 10); TRY(y = x.pow(21)); TEST_EQUAL(y.str(), "1000000000000000000000"); TRY(x = 10); TRY(y = x.pow(22)); TEST_EQUAL(y.str(), "10000000000000000000000"); TRY(x = 10); TRY(y = x.pow(23)); TEST_EQUAL(y.str(), "100000000000000000000000"); TRY(x = 10); TRY(y = x.pow(24)); TEST_EQUAL(y.str(), "1000000000000000000000000"); TRY(x = 10); TRY(y = x.pow(25)); TEST_EQUAL(y.str(), "10000000000000000000000000"); TRY(x = 10); TRY(y = x.pow(26)); TEST_EQUAL(y.str(), "100000000000000000000000000"); TRY(x = 10); TRY(y = x.pow(27)); TEST_EQUAL(y.str(), "1000000000000000000000000000"); TRY(x = 10); TRY(y = x.pow(28)); TEST_EQUAL(y.str(), "10000000000000000000000000000"); TRY(x = 10); TRY(y = x.pow(29)); TEST_EQUAL(y.str(), "100000000000000000000000000000"); TRY(x = 10); TRY(y = x.pow(30)); TEST_EQUAL(y.str(), "1000000000000000000000000000000"); } void test_rs_sci_mp_integer_unsigned_bit_operations() { MPN x, y, z; std::string s; TEST_EQUAL(x.bits_set(), 0u); TEST(x.is_even()); TEST(! x.is_odd()); TRY(x = 0x123456789abcdef0ull); TRY(y = 0xffffffffffffffffull); TEST_EQUAL(x.bits(), 61u); TEST_EQUAL(y.bits(), 64u); TEST_EQUAL(x.bits_set(), 32u); TEST_EQUAL(y.bits_set(), 64u); TEST(x.is_even()); TEST(! x.is_odd()); TEST(! y.is_even()); TEST(y.is_odd()); TRY(s = to_string(x)); TEST_EQUAL(s, "1311768467463790320"); TRY(s = to_string(y)); TEST_EQUAL(s, "18446744073709551615"); TRY(z = x & y); TEST_EQUAL(z.bits(), 61u); TRY(s = to_string(z)); TEST_EQUAL(s, "1311768467463790320"); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef0"); TRY(z = x | y); TEST_EQUAL(z.bits(), 64u); TRY(s = to_string(z)); TEST_EQUAL(s, "18446744073709551615"); TRY(s = z.str("x")); TEST_EQUAL(s, "ffffffffffffffff"); TRY(z = x ^ y); TEST_EQUAL(z.bits(), 64u); TRY(s = to_string(z)); TEST_EQUAL(s, "17134975606245761295"); TRY(s = z.str("x")); TEST_EQUAL(s, "edcba9876543210f"); TRY(z = x >> 0); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef0"); TRY(z = x >> 1); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f78"); TRY(z = x >> 2); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc"); TRY(z = x >> 3); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde"); TRY(z = x >> 31); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf1"); TRY(z = x >> 32); TRY(s = z.str("x")); TEST_EQUAL(s, "12345678"); TRY(z = x >> 33); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c"); TRY(z = x >> 58); TRY(s = z.str("x")); TEST_EQUAL(s, "4"); TRY(z = x >> 59); TRY(s = z.str("x")); TEST_EQUAL(s, "2"); TRY(z = x >> 60); TRY(s = z.str("x")); TEST_EQUAL(s, "1"); TRY(z = x >> 61); TRY(s = z.str("x")); TEST_EQUAL(s, "0"); TRY(z = x >> 62); TRY(s = z.str("x")); TEST_EQUAL(s, "0"); TRY(z = x >> 63); TRY(s = z.str("x")); TEST_EQUAL(s, "0"); TRY(z = x >> 64); TRY(s = z.str("x")); TEST_EQUAL(s, "0"); TRY(z = x >> 65); TRY(s = z.str("x")); TEST_EQUAL(s, "0"); TRY(z = x << 0); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef0"); TRY(z = x << 1); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde0"); TRY(z = x << 2); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc0"); TRY(z = x << 3); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f780"); TRY(z = x << 4); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef00"); TRY(z = x << 5); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde00"); TRY(z = x << 6); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc00"); TRY(z = x << 7); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f7800"); TRY(z = x << 8); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef000"); TRY(z = x << 9); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde000"); TRY(z = x << 10); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc000"); TRY(z = x << 11); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f78000"); TRY(z = x << 12); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef0000"); TRY(z = x << 13); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde0000"); TRY(z = x << 14); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc0000"); TRY(z = x << 15); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f780000"); TRY(z = x << 16); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef00000"); TRY(z = x << 17); TRY(s = z.str("x")); TEST_EQUAL(s, "2468acf13579bde00000"); TRY(z = x << 18); TRY(s = z.str("x")); TEST_EQUAL(s, "48d159e26af37bc00000"); TRY(z = x << 19); TRY(s = z.str("x")); TEST_EQUAL(s, "91a2b3c4d5e6f7800000"); TRY(z = x << 20); TRY(s = z.str("x")); TEST_EQUAL(s, "123456789abcdef000000"); TRY(x = {}); TEST(! x.get_bit(0)); TEST(! x.get_bit(100)); TRY(x.set_bit(16)); TEST_EQUAL(x, MPN("0x10000")); TEST(! x.get_bit(15)); TEST(x.get_bit(16)); TEST(! x.get_bit(17)); TRY(x.set_bit(80)); TEST_EQUAL(x, MPN("0x100000000000000010000")); TEST(! x.get_bit(79)); TEST(x.get_bit(80)); TEST(! x.get_bit(81)); TRY(x.set_bit(80, false)); TEST_EQUAL(x, MPN("0x10000")); TEST(! x.get_bit(80)); TRY(x.flip_bit(80)); TEST_EQUAL(x, MPN("0x100000000000000010000")); TEST(x.get_bit(80)); TRY(x.flip_bit(80)); TEST_EQUAL(x, MPN("0x10000")); TEST(! x.get_bit(80)); } void test_rs_sci_mp_integer_unsigned_byte_operations() { MPN a, b; ByteVector v; TEST_EQUAL(a.bytes(), 0u); TRY(a = MPN("0x12")); TEST_EQUAL(a.bytes(), 1u); TRY(a = MPN("0x1234")); TEST_EQUAL(a.bytes(), 2u); TRY(a = MPN("0x123456")); TEST_EQUAL(a.bytes(), 3u); TRY(a = MPN("0x12345678")); TEST_EQUAL(a.bytes(), 4u); TRY(a = MPN("0x123456789a")); TEST_EQUAL(a.bytes(), 5u); TRY(a = MPN("0x123456789abc")); TEST_EQUAL(a.bytes(), 6u); TRY(a = MPN("0x123456789abcde")); TEST_EQUAL(a.bytes(), 7u); TRY(a = MPN("0x123456789abcdef1")); TEST_EQUAL(a.bytes(), 8u); TRY(a = MPN("0x123456789abcdef123")); TEST_EQUAL(a.bytes(), 9u); TRY(a = MPN("0x123456789abcdef12345")); TEST_EQUAL(a.bytes(), 10u); TEST_EQUAL(a.get_byte(0), 0x45); TEST_EQUAL(a.get_byte(1), 0x23); TEST_EQUAL(a.get_byte(2), 0xf1); TEST_EQUAL(a.get_byte(3), 0xde); TEST_EQUAL(a.get_byte(4), 0xbc); TEST_EQUAL(a.get_byte(5), 0x9a); TEST_EQUAL(a.get_byte(6), 0x78); TEST_EQUAL(a.get_byte(7), 0x56); TEST_EQUAL(a.get_byte(8), 0x34); TEST_EQUAL(a.get_byte(9), 0x12); TEST_EQUAL(a.get_byte(10), 0u); TEST_EQUAL(a.get_byte(11), 0u); TEST_EQUAL(a.get_byte(12), 0u); TEST_EQUAL(a.get_byte(13), 0u); TEST_EQUAL(a.get_byte(14), 0u); TEST_EQUAL(a.get_byte(15), 0u); TEST_EQUAL(a.get_byte(16), 0u); TRY(a.set_byte(1, 0xff)); TEST_EQUAL(a.str("x"), "123456789abcdef1ff45"); TRY(a.set_byte(3, 0xff)); TEST_EQUAL(a.str("x"), "123456789abcfff1ff45"); TRY(a.set_byte(5, 0xff)); TEST_EQUAL(a.str("x"), "12345678ffbcfff1ff45"); TRY(a.set_byte(7, 0xff)); TEST_EQUAL(a.str("x"), "1234ff78ffbcfff1ff45"); TRY(a.set_byte(9, 0xff)); TEST_EQUAL(a.str("x"), "ff34ff78ffbcfff1ff45"); TRY(a.set_byte(11, 0xff)); TEST_EQUAL(a.str("x"), "ff00ff34ff78ffbcfff1ff45"); TRY(a.set_byte(13, 0xff)); TEST_EQUAL(a.str("x"), "ff00ff00ff34ff78ffbcfff1ff45"); TRY(a.set_byte(15, 0xff)); TEST_EQUAL(a.str("x"), "ff00ff00ff00ff34ff78ffbcfff1ff45"); TRY(a = 0); TRY(b = MPN("0x123456789abcdef12345")); v.resize(7); TRY(a.write_be(v.data(), v.size())); TEST_EQUAL(hexdump(v), "00 00 00 00 00 00 00"); TRY(b.write_be(v.data(), v.size())); TEST_EQUAL(hexdump(v), "78 9a bc de f1 23 45"); TRY(a.write_le(v.data(), v.size())); TEST_EQUAL(hexdump(v), "00 00 00 00 00 00 00"); TRY(b.write_le(v.data(), v.size())); TEST_EQUAL(hexdump(v), "45 23 f1 de bc 9a 78"); v = {0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xff}; TRY(a = MPN::read_be(v.data(), v.size())); TEST_EQUAL(a.str("x"), "112233445566778899aabbccddeeff"); TRY(a = MPN::read_le(v.data(), v.size())); TEST_EQUAL(a.str("x"), "ffeeddccbbaa998877665544332211"); }
43.590625
105
0.577246
CaptainCrowbar
8ef7b6a4a6cc310bccf1b00824337df2b9ff2966
411
hpp
C++
libs/parse/include/fcppt/parse/tag.hpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
13
2015-02-21T18:35:14.000Z
2019-12-29T14:08:29.000Z
libs/parse/include/fcppt/parse/tag.hpp
cpreh/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
5
2016-08-27T07:35:47.000Z
2019-04-21T10:55:34.000Z
libs/parse/include/fcppt/parse/tag.hpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
8
2015-01-10T09:22:37.000Z
2019-12-01T08:31:12.000Z
// Copyright Carl Philipp Reh 2009 - 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_PARSE_TAG_HPP_INCLUDED #define FCPPT_PARSE_TAG_HPP_INCLUDED namespace fcppt::parse { /** \brief The tag parsers derive from. \ingroup fcpptparse */ struct tag { }; } #endif
18.681818
61
0.717762
freundlich
8ef8d27920731249682d2403bb0520863b51bbcd
2,849
hpp
C++
lib/libcpp/Perulangan/Perulangan/iterativesolvervisitorinterface.hpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
lib/libcpp/Perulangan/Perulangan/iterativesolvervisitorinterface.hpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
1
2019-01-31T10:59:11.000Z
2019-01-31T10:59:11.000Z
lib/libcpp/Perulangan/Perulangan/iterativesolvervisitorinterface.hpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
#ifndef __Perulangan_IterativeSolverVisitorInterface_h #define __Perulangan_IterativeSolverVisitorInterface_h #include "Alat/interfacebase.hpp" #include "Alat/armadillo.hpp" /*--------------------------------------------------------------------------*/ namespace alat { class GhostLinearSolver; class GhostMatrix; class GhostVector; class StringVector; } namespace perulangan { class IterativeSolverVisitorInterface : public alat::InterfaceBase { protected: std::string getInterfaceName() const; public: ~IterativeSolverVisitorInterface(); IterativeSolverVisitorInterface(); IterativeSolverVisitorInterface( const IterativeSolverVisitorInterface& iterativesolvervisitorinterface); IterativeSolverVisitorInterface& operator=( const IterativeSolverVisitorInterface& iterativesolvervisitorinterface); std::string getClassName() const; perulangan::IterativeSolverVisitorInterface* clone() const; // virtual void basicInit(const alat::ParameterFile* parameterfile, std::string blockname); virtual std::ostream& printLoopInformation(std::ostream& os) const; virtual std::string getVectorType() const; // virtual int getVectorLevel() const=0; virtual void newVector(alat::GhostVector* u) = 0; virtual void vectorEqual(alat::GhostVector& r, const alat::GhostVector& f) const; virtual void vectorZero(alat::GhostVector& v) const; virtual void vectorAdd(alat::GhostVector& p, double d, const alat::GhostVector& q) const; virtual void vectorScale(alat::GhostVector& r, double d) const; virtual double vectorDot(const alat::GhostVector& gu, const alat::GhostVector& gv) const; virtual double vectorNorm(const alat::GhostVector& r) const; virtual void residual(const alat::GhostMatrix& A, alat::GhostVector& r, const alat::GhostVector& u, const alat::GhostVector& f) const; virtual void matrixVectorProduct(const alat::GhostMatrix& A, alat::GhostVector& r, const alat::GhostVector& u, double d) const; virtual void postProcess(alat::GhostVector& u) const; // virtual const alat::armaivec& getDomainsPermutation(int iteration) const; // virtual void solveOnDomain(int idomain, const alat::GhostLinearSolver& linearsolverdomain, const alat::GhostMatrix& ghostmatrix, alat::GhostVector& u, const alat::GhostVector& f) const; // virtual void vectorEqualOnDomain(int idomain, alat::GhostVector& u, const alat::GhostVector& f) const; // virtual void matrixVectorProductCoupling(int i, const alat::GhostMatrix& ghostmatrix, alat::GhostVector& u, const alat::GhostVector& f, double d) const; // virtual void smoothInterface(int idomain, alat::GhostVector& u) const; // virtual void smoothInterfaceOnLevel(int level, alat::GhostVector& u) const; }; } /*--------------------------------------------------------------------------*/ #endif
47.483333
192
0.724465
beckerrh
8eff0a67d91b7eb211ff45a1703d34d455e17e9e
3,951
cpp
C++
duds/data/Unit.cpp
jjackowski/duds
0fc4eec0face95c13575672f2a2d8625517c9469
[ "BSD-2-Clause" ]
null
null
null
duds/data/Unit.cpp
jjackowski/duds
0fc4eec0face95c13575672f2a2d8625517c9469
[ "BSD-2-Clause" ]
null
null
null
duds/data/Unit.cpp
jjackowski/duds
0fc4eec0face95c13575672f2a2d8625517c9469
[ "BSD-2-Clause" ]
null
null
null
/* * This file is part of the DUDS project. It is subject to the BSD-style * license terms in the LICENSE file found in the top-level directory of this * distribution and at https://github.com/jjackowski/duds/blob/master/LICENSE. * No part of DUDS, including this file, may be copied, modified, propagated, * or distributed except according to the terms contained in the LICENSE file. * * Copyright (C) 2017 Jeff Jackowski */ #include <duds/data/Unit.hpp> #include <duds/general/Errors.hpp> namespace duds { namespace data { void Unit::setAmpere(int e) { int v = general::SignExtend<4>(e); if (v != e) { DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) << BadUnit("Ampere")); } u = (u & 0xFFFFFFF0) | v; } void Unit::setCandela(int e) { int v = general::SignExtend<4>(e); if (v != e) { DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) << BadUnit("Candela")); } u = (u & 0xFFFFFF0F) | (v << 4); } void Unit::setKelvin(int e) { int v = general::SignExtend<4>(e); if (v != e) { DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) << BadUnit("Kelvin")); } u = (u & 0xFFFFF0FF) | (v << 8); } void Unit::setKilogram(int e) { int v = general::SignExtend<4>(e); if (v != e) { DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) << BadUnit("Kilogram")); } u = (u & 0xFFFF0FFF) | (v << 12); } void Unit::setMeter(int e) { int v = general::SignExtend<4>(e); if (v != e) { DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) << BadUnit("Meter")); } u = (u & 0xFFF0FFFF) | (v << 16); } void Unit::setMole(int e) { int v = general::SignExtend<4>(e); if (v != e) { DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) << BadUnit("Mole")); } u = (u & 0xFF0FFFFF) | (v << 20); } void Unit::setSecond(int e) { int v = general::SignExtend<4>(e); if (v != e) { DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) << BadUnit("Second")); } u = (u & 0xF0FFFFFF) | (v << 24); } void Unit::setRadian(int e) { int v = general::SignExtend<2>(e); if (v != e) { DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) << BadUnit("Radian")); } u = (u & 0xCFFFFFFF) | (v << 28); } void Unit::setSteradian(int e) { int v = general::SignExtend<2>(e); if (v != e) { DUDS_THROW_EXCEPTION(UnitRangeError() << BadUnitExponent(e) << BadUnit("Steradian")); } u = (u & 0x3FFFFFFF) | (v << 30); } Unit::Unit(int A, int cd, int K, int kg, int m, int mol, int s, int rad, int sr) { setAmpere(A); setCandela(cd); setKelvin(K); setKilogram(kg); setMeter(m); setMole(mol); setSecond(s); setRadian(rad); setSteradian(sr); } const Unit Unit::operator * (const Unit &U) const { // the result Unit r; // set the result; may fail with exception r.setAmpere(ampere() + U.ampere()); r.setCandela(candela() + U.candela()); r.setKelvin(kelvin() + U.kelvin()); r.setKilogram(kilogram() + U.kilogram()); r.setMeter(meter() + U.meter()); r.setMole(mole() + U.mole()); r.setSecond(second() + U.second()); r.setRadian(radian() + U.radian()); r.setSteradian(steradian() + U.steradian()); // return the result return r; } const Unit Unit::operator / (const Unit &U) const { // the result Unit r; // set the result; may fail with exception r.setAmpere(ampere() - U.ampere()); r.setCandela(candela() - U.candela()); r.setKelvin(kelvin() - U.kelvin()); r.setKilogram(kilogram() - U.kilogram()); r.setMeter(meter() - U.meter()); r.setMole(mole() - U.mole()); r.setSecond(second() - U.second()); r.setRadian(radian() - U.radian()); r.setSteradian(steradian() - U.steradian()); // return the result return r; } Unit &Unit::operator *= (const Unit &U) { // a temporary Unit n(*this * U); // may throw // keep the new value u = n.value(); return *this; } Unit &Unit::operator /= (const Unit &U) { // a temporary Unit n(*this / U); // may throw // keep the new value u = n.value(); return *this; } } }
24.69375
78
0.632498
jjackowski
f102ceb88409595e3e0ee48f71065afc42677212
829
hpp
C++
PrEngineSwitch/Game_Engine/include/SpriteLayer.hpp
aprithul/Prengine
7aff20bb73ab21e9e11dda1985e6b22992479f0d
[ "BSD-3-Clause" ]
1
2019-10-08T05:20:30.000Z
2019-10-08T05:20:30.000Z
PrEngineSwitch/Game_Engine/include/SpriteLayer.hpp
aprithul/PrEngine
7aff20bb73ab21e9e11dda1985e6b22992479f0d
[ "BSD-3-Clause" ]
null
null
null
PrEngineSwitch/Game_Engine/include/SpriteLayer.hpp
aprithul/PrEngine
7aff20bb73ab21e9e11dda1985e6b22992479f0d
[ "BSD-3-Clause" ]
null
null
null
#ifndef SPRITE_LAYER_HPP #define SPRITE_LAYER_HPP #include "GlAssert.hpp" #include "RenderLayer.hpp" #include "Graphics.hpp" #include "EntityManagementSystemModule.hpp" #include "DirectionalLight.hpp" #include "Camera3D.hpp" #include "Matrix4x4f.hpp" #include <vector> #include "Sprite.hpp" #include "Transform3D.hpp" namespace PrEngine { void insertion_sort(std::vector<Sprite*>& arr, Int_32 n); //extern RendererOpenGL2D* renderer; class SpriteLayer : public RenderLayer { public: SpriteLayer(); ~SpriteLayer() override; void start() override; void update() override; void end() override; std::vector<Sprite*> sprite_list; private: void UpdateTransforms(Transform3D* transform); }; } // namespace Pringin #endif
21.815789
61
0.670688
aprithul
f10648e5e4555887d3f3edb4cf771ecf7b04e628
13,938
inl
C++
source/bsys/geometry/geometry_vertex_3.inl
bluebackblue/brownie
917fcc71e5b0a807c0a8dab22a9ca7f3b0d60917
[ "MIT" ]
null
null
null
source/bsys/geometry/geometry_vertex_3.inl
bluebackblue/brownie
917fcc71e5b0a807c0a8dab22a9ca7f3b0d60917
[ "MIT" ]
null
null
null
source/bsys/geometry/geometry_vertex_3.inl
bluebackblue/brownie
917fcc71e5b0a807c0a8dab22a9ca7f3b0d60917
[ "MIT" ]
null
null
null
#pragma once /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/brownie/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief ジオメトリ。 */ /** include */ #pragma warning(push) #pragma warning(disable:4464) #include "../types/types.h" #pragma warning(pop) /** include */ #include "./geometry_vector.h" /** NBsys::NGeometry */ #if(BSYS_GEOMETRY_ENABLE) #pragma warning(push) #pragma warning(disable:4514 4710) namespace NBsys{namespace NGeometry { /** x */ inline const f32& Geometry_Vector3::x() const { return this->raw.v.xx; } /** x */ inline f32& Geometry_Vector3::x() { return this->raw.v.xx; } /** y */ inline const f32& Geometry_Vector3::y() const { return this->raw.v.yy; } /** y */ inline f32& Geometry_Vector3::y() { return this->raw.v.yy; } /** z */ inline const f32& Geometry_Vector3::z() const { return this->raw.v.zz; } /** z */ inline f32& Geometry_Vector3::z() { return this->raw.v.zz; } /** constructor */ inline Geometry_Vector3::Geometry_Vector3() noexcept { } /** constructor */ inline Geometry_Vector3::Geometry_Vector3(f32 a_xx,f32 a_yy,f32 a_zz) noexcept { this->raw.v.xx = a_xx; this->raw.v.yy = a_yy; this->raw.v.zz = a_zz; } /** constructor */ inline Geometry_Vector3::Geometry_Vector3(f32 a_value) noexcept { this->raw.v.xx = a_value; this->raw.v.yy = a_value; this->raw.v.zz = a_value; } /** constructor */ inline Geometry_Vector3::Geometry_Vector3(const f32* a_value_pointer) noexcept { this->raw.v.xx = a_value_pointer[0]; this->raw.v.yy = a_value_pointer[1]; this->raw.v.zz = a_value_pointer[2]; } /** copy constructor */ inline Geometry_Vector3::Geometry_Vector3(const Geometry_Vector3& a_vector) noexcept { this->raw.v.xx = a_vector.raw.v.xx; this->raw.v.yy = a_vector.raw.v.yy; this->raw.v.zz = a_vector.raw.v.zz; } /** constructor */ inline Geometry_Vector3::Geometry_Vector3(const Geometry_Identity_Type& /*a_identity*/) noexcept { this->Set_Zero(); } /** destructor */ inline Geometry_Vector3::~Geometry_Vector3() { } /** t_1 = t_2; */ inline Geometry_Vector3& Geometry_Vector3::operator =(const Geometry_Vector3& a_right) { this->raw.v.xx = a_right.raw.v.xx; this->raw.v.yy = a_right.raw.v.yy; this->raw.v.zz = a_right.raw.v.zz; return *this; } /** t_1 = +t_2; */ inline Geometry_Vector3 Geometry_Vector3::operator +() const { return *this; } /** t_1 = -t_2; */ inline Geometry_Vector3 Geometry_Vector3::operator -() const { return Geometry_Vector3(-this->raw.v.xx,-this->raw.v.yy,-this->raw.v.zz); } /** t_1 += t_2; */ inline Geometry_Vector3& Geometry_Vector3::operator +=(const Geometry_Vector3& a_right) { this->raw.v.xx += a_right.raw.v.xx; this->raw.v.yy += a_right.raw.v.yy; this->raw.v.zz += a_right.raw.v.zz; return *this; } /** t_1 -= t_2; */ inline Geometry_Vector3& Geometry_Vector3::operator -=(const Geometry_Vector3& a_right) { this->raw.v.xx -= a_right.raw.v.xx; this->raw.v.yy -= a_right.raw.v.yy; this->raw.v.zz -= a_right.raw.v.zz; return *this; } /** t_1 *= t_2; */ inline Geometry_Vector3& Geometry_Vector3::operator *=(const Geometry_Vector3& a_right) { this->raw.v.xx *= a_right.raw.v.xx; this->raw.v.yy *= a_right.raw.v.yy; this->raw.v.zz *= a_right.raw.v.zz; return *this; } /** t_1 /= t_2; */ inline Geometry_Vector3& Geometry_Vector3::operator /=(const Geometry_Vector3& a_right) { this->raw.v.xx /= a_right.raw.v.xx; this->raw.v.yy /= a_right.raw.v.yy; this->raw.v.zz /= a_right.raw.v.zz; return *this; } /** t_1 = 2; */ inline Geometry_Vector3& Geometry_Vector3::operator =(f32 a_right_value) { this->raw.v.xx = a_right_value; this->raw.v.yy = a_right_value; this->raw.v.zz = a_right_value; return *this; } /** t_1 += 2; */ inline Geometry_Vector3& Geometry_Vector3::operator +=(f32 a_right_value) { this->raw.v.xx += a_right_value; this->raw.v.yy += a_right_value; this->raw.v.zz += a_right_value; return *this; } /** t_1 -= 2; */ inline Geometry_Vector3& Geometry_Vector3::operator -=(f32 a_right_value) { this->raw.v.xx -= a_right_value; this->raw.v.yy -= a_right_value; this->raw.v.zz -= a_right_value; return *this; } /** t_1 *= 2; */ inline Geometry_Vector3& Geometry_Vector3::operator *=(f32 a_right_value) { this->raw.v.xx *= a_right_value; this->raw.v.yy *= a_right_value; this->raw.v.zz *= a_right_value; return *this; } /** t_1 /= 2; */ inline Geometry_Vector3& Geometry_Vector3::operator /=(f32 a_right_value) { this->raw.v.xx /= a_right_value; this->raw.v.yy /= a_right_value; this->raw.v.zz /= a_right_value; return *this; } /** [static]Zero。 */ inline const Geometry_Vector3& Geometry_Vector3::Zero() { static const NGeometry::Geometry_Vector3 s_zero(0.0f,0.0f,0.0f); return s_zero; } /** [static]One。 */ inline const Geometry_Vector3& Geometry_Vector3::One() { static const NGeometry::Geometry_Vector3 s_one(1.0f,1.0f,1.0f); return s_one; } /** [設定]。 */ inline Geometry_Vector3& Geometry_Vector3::Set(f32 a_xx,f32 a_yy,f32 a_zz) { this->raw.v.xx = a_xx; this->raw.v.yy = a_yy; this->raw.v.zz = a_zz; return *this; } /** [設定]。 */ inline Geometry_Vector3& Geometry_Vector3::Set_X(f32 a_xx) { this->raw.v.xx = a_xx; return *this; } /** [設定]。 */ inline Geometry_Vector3& Geometry_Vector3::Set_Y(f32 a_yy) { this->raw.v.yy = a_yy; return *this; } /** [設定]。 */ inline Geometry_Vector3& Geometry_Vector3::Set_Z(f32 a_zz) { this->raw.v.zz = a_zz; return *this; } /** [設定]。 */ inline Geometry_Vector3& Geometry_Vector3::Set(const Geometry_Vector3& a_vector) { this->raw.v.xx = a_vector.raw.v.xx; this->raw.v.yy = a_vector.raw.v.yy; this->raw.v.zz = a_vector.raw.v.zz; return *this; } /** [設定]Set_Zero。 */ inline Geometry_Vector3& Geometry_Vector3::Set_Zero() { *this = Geometry_Vector3::Zero(); return *this; } /** [取得]。 */ inline f32 Geometry_Vector3::Get_X() { return this->raw.v.xx; } /** [取得]。 */ inline f32 Geometry_Vector3::Get_Y() { return this->raw.v.yy; } /** [取得]。 */ inline f32 Geometry_Vector3::Get_Z() { return this->raw.v.zz; } /** [作成]外積。 */ inline Geometry_Vector3 Geometry_Vector3::Make_Cross(const Geometry_Vector3& a_vector) const { Geometry_Vector3 t_temp; { t_temp.raw.v.xx = (this->raw.v.yy * a_vector.raw.v.zz) - (this->raw.v.zz * a_vector.raw.v.yy); t_temp.raw.v.yy = (this->raw.v.zz * a_vector.raw.v.xx) - (this->raw.v.xx * a_vector.raw.v.zz); t_temp.raw.v.zz = (this->raw.v.xx * a_vector.raw.v.yy) - (this->raw.v.yy * a_vector.raw.v.xx); } return t_temp; } /** [設定]外積。 */ inline Geometry_Vector3& Geometry_Vector3::Set_Cross(const Geometry_Vector3& a_vector) { f32 t_temp_x = (this->raw.v.yy * a_vector.raw.v.zz) - (this->raw.v.zz * a_vector.raw.v.yy); f32 t_temp_y = (this->raw.v.zz * a_vector.raw.v.xx) - (this->raw.v.xx * a_vector.raw.v.zz); f32 t_temp_z = (this->raw.v.xx * a_vector.raw.v.yy) - (this->raw.v.yy * a_vector.raw.v.xx); this->raw.v.xx = t_temp_x; this->raw.v.yy = t_temp_y; this->raw.v.zz = t_temp_z; return *this; } /** [設定]外積。 */ inline Geometry_Vector3& Geometry_Vector3::Set_Cross(const Geometry_Vector3& a_vector_1,const Geometry_Vector3& a_vector_2) { f32 t_temp_x = (a_vector_1.raw.v.yy * a_vector_2.raw.v.zz) - (a_vector_1.raw.v.zz * a_vector_2.raw.v.yy); f32 t_temp_y = (a_vector_1.raw.v.zz * a_vector_2.raw.v.xx) - (a_vector_1.raw.v.xx * a_vector_2.raw.v.zz); f32 t_temp_z = (a_vector_1.raw.v.xx * a_vector_2.raw.v.yy) - (a_vector_1.raw.v.yy * a_vector_2.raw.v.xx); this->raw.v.xx = t_temp_x; this->raw.v.yy = t_temp_y; this->raw.v.zz = t_temp_z; return *this; } /** [設定]正規化。 */ inline Geometry_Vector3& Geometry_Vector3::Set_Normalize() { f32 t_value = this->SquareLength(); ASSERT(t_value != 0.0f); t_value = NMath::sqrt_f(t_value); ASSERT(t_value != 0.0f); t_value = 1.0f / t_value; this->raw.v.xx *= t_value; this->raw.v.yy *= t_value; this->raw.v.zz *= t_value; return *this; } /** [設定]正規化。 */ inline Geometry_Vector3& Geometry_Vector3::Set_Normalize_Safe(const Geometry_Vector3& a_vector_safe) { f32 t_value = this->SquareLength(); if(t_value == 0.0f){ *this = a_vector_safe; return *this; } t_value = NMath::sqrt_f(t_value); if(t_value == 0.0f){ *this = a_vector_safe; return *this; } t_value = 1.0f / t_value; this->raw.v.xx *= t_value; this->raw.v.yy *= t_value; this->raw.v.zz *= t_value; return *this; } /** [設定]正規化。 */ inline f32 Geometry_Vector3::Set_Normalize_GetLength() { f32 t_value = this->SquareLength(); if(t_value == 0.0f){ return 0.0f; } t_value = NMath::sqrt_f(t_value); if(t_value == 0.0f){ return 0.0f; } f32 t_length = t_value; t_value = 1.0f / t_value; this->raw.v.xx *= t_value; this->raw.v.yy *= t_value; this->raw.v.zz *= t_value; return t_length; } /** [作成]正規化。 */ inline Geometry_Vector3 Geometry_Vector3::Make_Normalize() const { Geometry_Vector3 t_temp; { f32 t_value = this->SquareLength(); ASSERT(t_value != 0.0f); t_value = NMath::sqrt_f(t_value); ASSERT(t_value != 0.0f); t_value = 1.0f / t_value; t_temp.raw.v.xx = this->raw.v.xx * t_value; t_temp.raw.v.yy = this->raw.v.yy * t_value; t_temp.raw.v.zz = this->raw.v.zz * t_value; } return t_temp; } /** [作成]正規化。 */ inline Geometry_Vector3 Geometry_Vector3::Make_Normalize_Safe(const Geometry_Vector3& a_vector_safe) const { Geometry_Vector3 t_temp; { f32 t_value = this->SquareLength(); if(t_value == 0.0f){ return a_vector_safe; } t_value = NMath::sqrt_f(t_value); if(t_value == 0.0f){ return a_vector_safe; } t_value = 1.0f / t_value; t_temp.raw.v.xx = this->raw.v.xx * t_value; t_temp.raw.v.yy = this->raw.v.yy * t_value; t_temp.raw.v.zz = this->raw.v.zz * t_value; } return t_temp; } /** [内積]length(this)*length(a_vector)*cos(θ)。 */ inline f32 Geometry_Vector3::Dot(const Geometry_Vector3& a_vector) const { f32 t_value = (this->raw.v.xx * a_vector.raw.v.xx) + (this->raw.v.yy * a_vector.raw.v.yy) + (this->raw.v.zz * a_vector.raw.v.zz); return t_value; } /** [チェック]。 */ inline bool Geometry_Vector3::IsZero() const { return (this->raw.v.xx == 0.0f)&&(this->raw.v.yy == 0.0f)&&(this->raw.v.zz == 0.0f); } /** [作成]長さ。 */ inline f32 Geometry_Vector3::Length() const { f32 t_value = this->SquareLength(); t_value = NMath::sqrt_f(t_value); return t_value; } /** [作成]長さの2乗。 */ inline f32 Geometry_Vector3::SquareLength() const { return (this->raw.v.xx * this->raw.v.xx) + (this->raw.v.yy * this->raw.v.yy) + (this->raw.v.zz * this->raw.v.zz); } /** [作成]2点間の距離の2乗。 */ inline f32 Geometry_Vector3::SquareDistance(const Geometry_Vector3& a_vector) const { f32 t_temp_x = (this->raw.v.xx - a_vector.raw.v.xx); f32 t_temp_y = (this->raw.v.yy - a_vector.raw.v.yy); f32 t_temp_z = (this->raw.v.zz - a_vector.raw.v.zz); f32 t_value = (t_temp_x * t_temp_x) + (t_temp_y * t_temp_y) + (t_temp_z * t_temp_z); return t_value; } /** [作成]Make_Lerp。 a_per = 0.0f : return = this a_per = 1.0f : return = a_vector */ inline Geometry_Vector3 Geometry_Vector3::Make_Lerp(const Geometry_Vector3& a_vector,f32 a_per) const { Geometry_Vector3 t_temp; { t_temp.raw.v.xx = this->raw.v.xx + (a_vector.raw.v.xx - this->raw.v.xx) * a_per; t_temp.raw.v.yy = this->raw.v.yy + (a_vector.raw.v.yy - this->raw.v.yy) * a_per; t_temp.raw.v.zz = this->raw.v.zz + (a_vector.raw.v.zz - this->raw.v.zz) * a_per; } return t_temp; } /** [static][作成]Lerp a_per = 0.0f : return = this a_per = 1.0f : return = a_vector */ inline Geometry_Vector3 Geometry_Vector3::Make_Lerp(const Geometry_Vector3& a_vector_1,const Geometry_Vector3& a_vector_2,f32 a_per) { Geometry_Vector3 t_temp; { t_temp.raw.v.xx = a_vector_1.raw.v.xx + (a_vector_2.raw.v.xx - a_vector_1.raw.v.xx) * a_per; t_temp.raw.v.yy = a_vector_1.raw.v.yy + (a_vector_2.raw.v.yy - a_vector_1.raw.v.yy) * a_per; t_temp.raw.v.zz = a_vector_1.raw.v.zz + (a_vector_2.raw.v.zz - a_vector_1.raw.v.zz) * a_per; } return t_temp; } /** [設定]Set_Lerp。 a_per = 0.0f : this = this a_per = 1.0f : this = a_vector */ inline void Geometry_Vector3::Set_Lerp(const Geometry_Vector3& a_vector,f32 a_per) { this->raw.v.xx += (a_vector.raw.v.xx - this->raw.v.xx) * a_per; this->raw.v.yy += (a_vector.raw.v.yy - this->raw.v.yy) * a_per; this->raw.v.zz += (a_vector.raw.v.zz - this->raw.v.zz) * a_per; } /** [設定]Lerp。 a_per = 0.0f : this = a_vector_1 a_per = 1.0f : this = a_vector_2 */ inline void Geometry_Vector3::Set_Lerp(const Geometry_Vector3& a_vector_1,const Geometry_Vector3& a_vector_2,f32 a_per) { this->raw.v.xx = a_vector_1.raw.v.xx + (a_vector_2.raw.v.xx - a_vector_1.raw.v.xx) * a_per; this->raw.v.yy = a_vector_1.raw.v.yy + (a_vector_2.raw.v.yy - a_vector_1.raw.v.yy) * a_per; this->raw.v.zz = a_vector_1.raw.v.zz + (a_vector_2.raw.v.zz - a_vector_1.raw.v.zz) * a_per; } }} #pragma warning(pop) #endif
21.054381
134
0.617305
bluebackblue
f1064af791209147bd47565f3703d6aeab1c6d83
914
cpp
C++
ststring.cpp
ohmyjons/SPOJ-1
870ae3b072a3fbc89149b35fe5649a74512a8f60
[ "Unlicense" ]
264
2015-01-08T10:07:01.000Z
2022-03-26T04:11:51.000Z
ststring.cpp
ohmyjons/SPOJ-1
870ae3b072a3fbc89149b35fe5649a74512a8f60
[ "Unlicense" ]
17
2016-04-15T03:38:07.000Z
2020-10-30T00:33:57.000Z
ststring.cpp
ohmyjons/SPOJ-1
870ae3b072a3fbc89149b35fe5649a74512a8f60
[ "Unlicense" ]
127
2015-01-08T04:56:44.000Z
2022-02-25T18:40:37.000Z
// 2008-10-22 #include <iostream> #include <algorithm> #include <cstring> using namespace std; void inc(char* s) { int cur=0; bool ok=false; while (!ok) { s[cur]++; if (s[cur]=='K') s[cur++]='A'; else ok=true; } if (s[cur]==1) { s[cur]='A'; s[cur+1]=0; } } int ok(char* s) { int i=1; while (s[i]) { if (s[i]==s[i-1]||s[i]==s[i-1]-1||s[i]==s[i-1]+1) return 0; i++; } return 1; } int hash(char* s) { int x=1; int i=0; int res=0; while (s[i]) { res+=x*(s[i++]-'A'+1); x*=11; } return res; } int ans[2000000]; int main() { //precompute answers char s1[10]="A",s2[10]="AAAAAAA"; int sum=0; while (strcmp(s1,s2)) { if (ok(s1)) sum++; ans[hash(s1)]=sum; inc(s1); } for(;;) { s1[0]=0; scanf("%s %s",s1,s2); if (!s1[0]) return 0; reverse(s1,s1+strlen(s1)); reverse(s2,s2+strlen(s2)); printf("%d\n",max(ans[hash(s2)]-ans[hash(s1)]-ok(s2),0)); } }
13.057143
59
0.514223
ohmyjons
f1071f2a2259d40223c641fdcc79d9d6fc9e2942
1,700
cpp
C++
leetcode_0721_unionfind.cpp
xiaoxiaoxiang-Wang/01-leetcode
5a9426dd70c3dd6725444783aaa8cefc27196779
[ "MIT" ]
3
2021-01-18T06:26:10.000Z
2021-01-29T07:52:49.000Z
leetcode_0721_unionfind.cpp
xiaoxiaoxiang-Wang/leetcode
5a9426dd70c3dd6725444783aaa8cefc27196779
[ "MIT" ]
null
null
null
leetcode_0721_unionfind.cpp
xiaoxiaoxiang-Wang/leetcode
5a9426dd70c3dd6725444783aaa8cefc27196779
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) { vector<pair<string, int>> emails; for (int i = 0; i < accounts.size(); i++) { for (int j = 1; j < accounts[i].size(); j++) { emails.push_back({ accounts[i][j],i }); } } sort(emails.begin(), emails.end()); vector<int> uf(accounts.size(),-1); unordered_map<int, int> um; for (int i = 0; i < emails.size() - 1; i++){ if (emails[i].first == emails[i + 1].first) { unionFind(uf, emails[i].second, emails[i+1].second); } } int idx = 0; for (int i = 0; i < accounts.size(); i++) { setIndex(uf, um, i, idx); } vector<vector<string>> res(idx); emails.push_back({ "",0 }); for (int i = 0; i<emails.size() - 1; i++) { if (res[um[emails[i].second]].empty()) { // 插入名字 res[um[emails[i].second]].push_back(accounts[emails[i].second][0]); } if (emails[i].first == emails[i + 1].first) { auto iter2 = um.find(emails[i + 1].second); if (iter2 == um.end()) { um[emails[i+1].second] = um[emails[i].second]; } } else { // 插入元素 res[um[emails[i].second]].push_back(emails[i].first); } } return res; } int unionFind(vector<int>& uf, int a,int b) { a = find(uf,a); b = find(uf,b); if (a == b) { return false; } uf[a] = b; return true; } int find(vector<int>& uf, int a) { while (uf[a] != -1) { a = uf[a]; } return a; } int setIndex(vector<int>& uf, unordered_map<int, int>& um,int i,int& idx) { auto iter = um.find(i); if (iter != um.end()) { return iter->second; } if (uf[i] == -1) { um[i] = idx; return idx++; } return um[i] = setIndex(uf, um, uf[i], idx); } };
23.943662
76
0.545294
xiaoxiaoxiang-Wang
f1088921c111614dc731eba6e955608389cbe272
982
cpp
C++
src/Utils.cpp
bsmithcompsci/Experiment-EmbedSystems-Playground
fcf72d6e3500c8cfea9446fcbc777be3e28cd86f
[ "MIT" ]
null
null
null
src/Utils.cpp
bsmithcompsci/Experiment-EmbedSystems-Playground
fcf72d6e3500c8cfea9446fcbc777be3e28cd86f
[ "MIT" ]
null
null
null
src/Utils.cpp
bsmithcompsci/Experiment-EmbedSystems-Playground
fcf72d6e3500c8cfea9446fcbc777be3e28cd86f
[ "MIT" ]
null
null
null
#include "global/Utils.h" std::vector<std::string> splitStrs(const std::string &_str, char _delimiter) { std::vector<std::string> output; std::string::size_type prev_pos = 0, cur_pos = 0; while ((cur_pos = _str.find(_delimiter, cur_pos)) != std::string::npos) { std::string substring(_str.substr(prev_pos, cur_pos - prev_pos)); output.push_back(substring); prev_pos = ++cur_pos; } output.push_back(_str.substr(prev_pos, cur_pos - prev_pos)); // Catch the last bits. return output; } std::vector<int> splitInts(const std::string &_str, char _delimiter) { std::vector<int> output; std::string::size_type prev_pos = 0, cur_pos = 0; while ((cur_pos = _str.find(_delimiter, cur_pos)) != std::string::npos) { std::string substring(_str.substr(prev_pos, cur_pos - prev_pos)); output.push_back(atoi(substring.c_str())); prev_pos = ++cur_pos; } output.push_back(atoi(_str.substr(prev_pos, cur_pos - prev_pos).c_str())); // Catch the last bits. return output; }
30.6875
99
0.705703
bsmithcompsci
f1094fbea6cdbe832dff1f5bd659025df443c301
1,970
hpp
C++
src/registry.hpp
rcabot/codscape
5619b40d7857066818c8409d3db4371d3c8f758c
[ "Unlicense" ]
null
null
null
src/registry.hpp
rcabot/codscape
5619b40d7857066818c8409d3db4371d3c8f758c
[ "Unlicense" ]
null
null
null
src/registry.hpp
rcabot/codscape
5619b40d7857066818c8409d3db4371d3c8f758c
[ "Unlicense" ]
null
null
null
#ifndef REGISTRY_H #define REGISTRY_H #pragma once #include "dialogue_initiator.hpp" #include "Map.h" #include "Person.h" #include "interactable.hpp" #include "dialogue_ui.hpp" #include "rect_transform.hpp" #include <sstream> #include <limits> template<typename T> using uvector = std::vector<std::unique_ptr<T>>; class registry { private: public: uvector<Map> maps_; uvector<person> people_; std::vector<interactable> interactables_; player_state_machine player_state_machine_; dialogue_state dialogue_state_; dialogue_initiator dialogue_initiator_; dialogue_ui dialogue_ui_; rect_transform dialogue_ui_transform_; registry() : maps_{}, people_{}, interactables_{}, player_state_machine_{}, dialogue_state_{*this}, dialogue_initiator_{player_state_machine_, dialogue_state_}, dialogue_ui_transform_{} , dialogue_ui_{*this,dialogue_ui_transform_,dialogue_state_} {} void add_new_person_at(const Vector2& position, const std::string name, int map_index_) { auto start_dialogue_with_person = std::function([name](registry& r){ r.dialogue_initiator_.start_dialogue_with(name); }); people_.emplace_back(std::make_unique<person>(name, maps_[map_index_].get(), position)); interactables_.emplace_back(position,std::move(start_dialogue_with_person),*this); } template<class...Params> void add_map(Params&&... args) { maps_.emplace_back(std::make_unique<Map>(args...)); } interactable* try_get_nearest_interactable_object_in_radius(const Vector2 center, const float radius) { interactable* nearest_interactable = nullptr; float min_distance{std::numeric_limits<float>::max()}; for(auto& interactable : interactables_) { float distance = center.distance(interactable.position_); if(radius > distance && distance < min_distance) { min_distance = distance; nearest_interactable = &interactable; } } return nearest_interactable; } }; #endif
25.25641
102
0.744162
rcabot
f10cd8557ccd76ef1c08f38c105009ce9e26196e
650
cpp
C++
Spline/Source.cpp
Fahersto/Spline
cbe4645aedd9b6e53c9c3393b1c7f2fc0040666d
[ "MIT" ]
null
null
null
Spline/Source.cpp
Fahersto/Spline
cbe4645aedd9b6e53c9c3393b1c7f2fc0040666d
[ "MIT" ]
null
null
null
Spline/Source.cpp
Fahersto/Spline
cbe4645aedd9b6e53c9c3393b1c7f2fc0040666d
[ "MIT" ]
null
null
null
#include "ParametricSpline.h" int main() { ParametricSpline parametricSpline = ParametricSpline(); const int VALUE_COUNT = 3; double* x = new double[VALUE_COUNT]{ 0, 1, 2 }; double* y = new double[VALUE_COUNT]{ 0, 3, 0 }; double* z = new double[VALUE_COUNT]{ 1, 2, 3 }; parametricSpline.Compute(x, y, z, VALUE_COUNT); const int STEPS = 10; for (int i = 0; i < parametricSpline.GetSegmentCount(); i++) { for (int j = 0; j < STEPS; j++) { double t = i + (double)j / (STEPS); double* position = parametricSpline.eval(t); printf("new Vector3(%ff, %ff, %ff),\n", position[0], position[1], position[2]); } } return 0; }
21.666667
82
0.629231
Fahersto
f10f1c8509669062f615ca8b59fe48ba8955c30e
1,443
cc
C++
project/core/id/test/SequentialIdGenerator.cc
letsmake-games/engine
b40559037353e000adf2f18ca9ead16529f932c6
[ "MIT" ]
null
null
null
project/core/id/test/SequentialIdGenerator.cc
letsmake-games/engine
b40559037353e000adf2f18ca9ead16529f932c6
[ "MIT" ]
null
null
null
project/core/id/test/SequentialIdGenerator.cc
letsmake-games/engine
b40559037353e000adf2f18ca9ead16529f932c6
[ "MIT" ]
null
null
null
// // (c) LetsMakeGames 2019 // http://www.letsmake.games // #include "core/id/IdClass.hh" #include "core/id/SequentialIdGenerator.hh" #include "gtest/gtest.h" // // types ////////////////////////////////////////////////////////////////////// // DECLARE_IDCLASS(BasicId, uint8_t); // // Generator ////////////////////////////////////////////////////////////////// // TEST(Test_SequentialIdGenerator, Generation ) { // // generate an id // Engine::SequentialIdGenerator<BasicId> generator; BasicId id1 = generator.next(); EXPECT_NE(id1, BasicId::InvalidId); EXPECT_EQ(id1.getRawId(), 0); // // the last id should be the id we just generated // BasicId id1_2 = generator.prev(); EXPECT_EQ(id1, id1_2); // // generate another id // BasicId id2 = generator.next(); EXPECT_NE(id2, BasicId::InvalidId); EXPECT_NE(id1, id2); // // once we run out of numbers, we generate only InvalidIds // for(size_t i = 0; i != 256; ++i ) { generator.next(); } EXPECT_EQ(generator.next(), BasicId::InvalidId); EXPECT_EQ(generator.next(), BasicId::InvalidId); // // prev always returns the last VALID id // EXPECT_EQ(BasicId(BasicId::InvalidValue-1), generator.prev()); // // we can reset a generator to recycle old ids // generator.reset(); BasicId id1_3 = generator.next(); EXPECT_EQ(id1, id1_3); }
21.220588
79
0.559252
letsmake-games
f111b50b2ed434352fe1d8198b05939082989892
1,215
cpp
C++
Tree/589-n-ary-tree-preorder-traversal.cpp
wandsX/LeetCodeExperience
8502e6e8ce911045f45f0075bcf3ee751a4558c7
[ "MIT" ]
null
null
null
Tree/589-n-ary-tree-preorder-traversal.cpp
wandsX/LeetCodeExperience
8502e6e8ce911045f45f0075bcf3ee751a4558c7
[ "MIT" ]
null
null
null
Tree/589-n-ary-tree-preorder-traversal.cpp
wandsX/LeetCodeExperience
8502e6e8ce911045f45f0075bcf3ee751a4558c7
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; //leetcode submit region begin(Prohibit modification and deletion) class Solution { public: vector<int> preorder(Node *root) { stack < Node * > s; std::vector<int> ans; Node *cur = nullptr; if (root != nullptr) { s.push(root); } while(!s.empty()) { cur = s.top(); s.pop(); ans.emplace_back(cur->val); for (int i = cur->children.size() - 1; i >= 0; --i) s.push(cur->children[i]); } return ans; } }; // 递归 class Solution1 { public: vector<int> preorder(Node *root) { std::vector<int> ans; traverse(root, ans); return ans; } void traverse(Node *cur, vector<int> &ans) { if (cur == nullptr) { return; } ans.push_back(cur->val); for (auto &e : cur->children) { traverse(e, ans); } } }; //leetcode submit region end(Prohibit modification and deletion)
19.596774
67
0.443621
wandsX
47dbd807a98370edc068e9a4687d752e159c0fea
2,389
cpp
C++
LeetCode/200/148.cpp
K-ona/C-_Training
d54970f7923607bdc54fc13677220d1b3daf09e5
[ "Apache-2.0" ]
null
null
null
LeetCode/200/148.cpp
K-ona/C-_Training
d54970f7923607bdc54fc13677220d1b3daf09e5
[ "Apache-2.0" ]
null
null
null
LeetCode/200/148.cpp
K-ona/C-_Training
d54970f7923607bdc54fc13677220d1b3daf09e5
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode* next) : val(x), next(next) {} }; class Solution { tuple<ListNode*, ListNode*> partition(ListNode* begin, ListNode* end) { int sep = begin->val; ListNode* res = begin; ListNode* head = begin; ListNode* tail = begin; while (begin != end) { // cout << begin->val << " "; auto next = begin->next; if (begin->val <= sep) { begin->next = head; head = begin; } else { begin->next = nullptr; tail->next = begin; tail = begin; } begin = next; } // cout << endl; tail->next = end; return {res, head}; } tuple<ListNode*, ListNode*> quick_sort(ListNode* begin, ListNode* end) { if (begin->next == end) return {begin, begin}; auto [sep, head] = partition(begin, end); if (sep == head) { auto [h, t] = quick_sort(sep->next, end); sep->next = h; return {sep, t}; } auto [h1, t1] = quick_sort(head, sep); if (sep->next != end) { auto [h2, t2] = quick_sort(sep->next, end); t1->next = sep; sep->next = h2; return {h1, t2}; } else { t1->next = sep; return {h1, sep}; } } public: ListNode* sortList(ListNode* head) { if (head) return std::get<0>(quick_sort(head, nullptr)); return nullptr; } }; class Solution { public: ListNode* sortList(ListNode* head) { if (!head || !head->next) return head; auto slow = head, fast = head; while (fast->next && fast->next->next) slow = slow->next, fast = fast->next->next; // 切链 fast = slow->next, slow->next = nullptr; return merge(sortList(head), sortList(fast)); } private: ListNode* merge(ListNode* l1, ListNode* l2) { ListNode sub(0), *ptr = &sub; while (l1 && l2) { auto &node = l1->val < l2->val ? l1 : l2; ptr = ptr->next = node, node = node->next; } ptr->next = l1 ? l1 : l2; return sub.next; } }; int main() { ListNode e(0); ListNode d(4, &e); ListNode c(3, &d); ListNode b(5, &c); ListNode a(-1, &b); Solution().sortList(&a); }
23.421569
74
0.518627
K-ona
47e158798760a23cd391c2952c00eed2e8f5ee4c
265
cpp
C++
libs/core/render/src/vulkan/detail/bksge_core_render_vulkan_detail_cull_mode.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/core/render/src/vulkan/detail/bksge_core_render_vulkan_detail_cull_mode.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/core/render/src/vulkan/detail/bksge_core_render_vulkan_detail_cull_mode.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file bksge_core_render_vulkan_detail_cull_mode.cpp * * @brief CullMode クラスの定義 * * @author myoukaku */ #include <bksge/fnd/config.hpp> #if !defined(BKSGE_HEADER_ONLY) #include <bksge/core/render/vulkan/detail/inl/cull_mode_inl.hpp> #endif
20.384615
65
0.713208
myoukaku
47e22f8b52fb7c6425212e051080062f04e3f07e
5,905
cpp
C++
src/mercury.cpp
darkedge/mercury
5bdf857b38f68b2a8c6ae1455f7623313ad0af71
[ "MIT" ]
null
null
null
src/mercury.cpp
darkedge/mercury
5bdf857b38f68b2a8c6ae1455f7623313ad0af71
[ "MIT" ]
null
null
null
src/mercury.cpp
darkedge/mercury
5bdf857b38f68b2a8c6ae1455f7623313ad0af71
[ "MIT" ]
null
null
null
#include <codeanalysis/warnings.h> #pragma warning( push, 0 ) #pragma warning( disable : ALL_CODE_ANALYSIS_WARNINGS ) #include "glad/glad.h" #include "glad.c" #include "GLFW/glfw3.h" #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include <stdint.h> // ImGui #include "imgui.cpp" #include "imgui_demo.cpp" #include "imgui_draw.cpp" #pragma warning( pop ) #include "mercury.h" #include "mercury_imgui.cpp" #include "mercury_input.cpp" #include "mercury_game.cpp" #include "mercury_program.cpp" #include "mercury_math.cpp" // Tell Optimus to use the high-performance NVIDIA processor // option if it's on auto-select (we cannot override it) extern "C" { _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001; } static GLFWwindow *s_window; static float s_deltaTime = 0.0f; static int32_t s_width = 1280; static int32_t s_height = 720; static const char *s_name = "Hello World!"; inline float GetDeltaTime() { return s_deltaTime; } inline GLFWwindow *GetWindow() { return s_window; } inline int32_t GetWindowWidth() { return s_width; } inline int32_t GetWindowHeight() { return s_height; } void CALLBACK debugCallbackARB( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, GLvoid *userParam ) { if (type == GL_DEBUG_TYPE_OTHER) return; Log("Type: "); switch (type) { case GL_DEBUG_TYPE_ERROR: Log("ERROR"); break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: Log("DEPRECATED_BEHAVIOR"); break; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: Log("UNDEFINED_BEHAVIOR"); break; case GL_DEBUG_TYPE_PORTABILITY: Log("PORTABILITY"); break; case GL_DEBUG_TYPE_PERFORMANCE: Log("PERFORMANCE"); break; case GL_DEBUG_TYPE_OTHER: Log("OTHER"); break; } Log(" - id: %d", id); Log(" - Severity: "); switch (severity) { case GL_DEBUG_SEVERITY_LOW: Log("LOW"); break; case GL_DEBUG_SEVERITY_MEDIUM: Log("MEDIUM"); break; case GL_DEBUG_SEVERITY_HIGH: Log("HIGH"); break; } Log(" - %s\n", message); } void GlfwErrorCallback( int32_t, const char *description ) { Log("%s\n", description); } void GlfwKeyCallBack( GLFWwindow* window, int32_t key, int32_t scancode, int32_t action, int32_t mods ) { if ( key == GLFW_KEY_ESCAPE && action == GLFW_PRESS ) { glfwSetWindowShouldClose( window, GL_TRUE ); } if ( action == GLFW_PRESS ) { Input::SetKey( key, true ); } if ( action == GLFW_RELEASE ) { Input::SetKey( key, false ); } ImGui_ImplGlfwGL3_KeyCallback(window, key, scancode, action, mods); } void GlfwMouseButtonCallback( GLFWwindow *window, int32_t button, int32_t action, int32_t mods ) { if ( action == GLFW_PRESS ) { Input::SetMouseButton( button, true ); } if ( action == GLFW_RELEASE ) { Input::SetMouseButton( button, false ); } if(!Input::IsMouseGrabbed()) { ImGui_ImplGlfwGL3_MouseButtonCallback(window, button, action, mods); } } void GlfwScrollCallback( GLFWwindow *window, double xoffset, double yoffset ) { ImGui_ImplGlfwGL3_ScrollCallback(window, xoffset, yoffset); } void GlfwCharCallback( GLFWwindow *window, uint32_t codepoint ) { ImGui_ImplGlfwGL3_CharCallback(window, codepoint); } void GlfwCursorPosCallback( GLFWwindow *window, double xpos, double ypos ) { Input::SetMousePosition( float2 { (float) xpos, (float) ypos } ); } void GlfwWindowSizeCallBack( GLFWwindow *window, int32_t width, int32_t height ) { // TODO //Application::SetWidth( width ); //Application::SetHeight( height ); } void EnterWindowLoop() { Init(); // Slow double lastTime = glfwGetTime(); while ( !glfwWindowShouldClose( s_window ) ) { double now = glfwGetTime(); s_deltaTime = (float) ( now - lastTime ); lastTime = now; glfwPollEvents(); Input::Tick(); Tick(); Input::PostTick(); glfwSwapBuffers( s_window ); } glfwDestroyWindow( s_window ); glfwTerminate(); std::exit( EXIT_SUCCESS ); } int CALLBACK WinMain( _In_ HINSTANCE hInstance, _In_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow ) { glfwSetErrorCallback( GlfwErrorCallback ); if ( glfwInit() ) { // Window hints glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 4 ); glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 5 ); glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE ); s_window = glfwCreateWindow( s_width, s_height, s_name, nullptr, nullptr ); glfwMakeContextCurrent( s_window ); // TODO: Callbacks glfwSetKeyCallback( s_window, GlfwKeyCallBack ); glfwSetMouseButtonCallback( s_window, GlfwMouseButtonCallback ); glfwSetScrollCallback( s_window, GlfwScrollCallback ); glfwSetCharCallback( s_window, GlfwCharCallback ); glfwSetCursorPosCallback( s_window, GlfwCursorPosCallback ); glfwSetWindowSizeCallback( s_window, GlfwWindowSizeCallBack ); ImGui_ImplGlfwGL3_Init(s_window, false); // Sync to monitor refresh rate glfwSwapInterval( 1 ); /************************************************************************/ /* OpenGL */ /************************************************************************/ if ( gladLoadGLLoader((GLADloadproc) glfwGetProcAddress) ) { Log("OpenGL %d.%d\n", GLVersion.major, GLVersion.minor); glEnable( GL_BLEND ); glEnable( GL_MULTISAMPLE ); glEnable( GL_CULL_FACE ); glEnable( GL_DEPTH_TEST ); glClearColor( 0.192156862745098f, 0.3019607843137255f, 0.4745098039215686f, 1.0f ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glDepthFunc( GL_LEQUAL ); // https://www.opengl.org/wiki/Debug_Output glDebugMessageCallback( (GLDEBUGPROC) debugCallbackARB, nullptr ); glEnable( GL_DEBUG_OUTPUT ); glEnable( GL_DEBUG_OUTPUT_SYNCHRONOUS ); EnterWindowLoop(); } else { printf( "Failed to init glad!\n" ); std::exit( EXIT_FAILURE ); } } else { printf( "Failed to init GLFW!\n" ); std::exit( EXIT_FAILURE ); } }
25.343348
105
0.695512
darkedge
47e9bfdb27625f3517d82ddced901e0cc185a5da
182
cpp
C++
docs/mfc/codesnippet/CPP/cfontdialog-class_8.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
14
2018-01-28T18:10:55.000Z
2021-11-16T13:21:18.000Z
docs/mfc/codesnippet/CPP/cfontdialog-class_8.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
null
null
null
docs/mfc/codesnippet/CPP/cfontdialog-class_8.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
2
2018-11-01T12:33:08.000Z
2021-11-16T13:21:19.000Z
// Is the selected font bold? CFontDialog dlg; if (dlg.DoModal() == IDOK) { BOOL bold = dlg.IsBold(); TRACE(_T("Is the selected font bold? %d\n"), bold); }
26
57
0.56044
jmittert
47ea935abdcb6cafecbcd071877e2c7547f5d0c5
17,028
cpp
C++
partman/loader.cpp
XplosiveLugnut/3d-pinball-space-cadet
5bf9b86f379a3d28321a4d29df03965ff1245fad
[ "MIT" ]
1
2021-04-23T12:50:21.000Z
2021-04-23T12:50:21.000Z
partman/loader.cpp
XplosiveLugnut/3d-pinball-space-cadet
5bf9b86f379a3d28321a4d29df03965ff1245fad
[ "MIT" ]
null
null
null
partman/loader.cpp
XplosiveLugnut/3d-pinball-space-cadet
5bf9b86f379a3d28321a4d29df03965ff1245fad
[ "MIT" ]
null
null
null
// // Created by neo on 2019-08-15. // #include "../pinball.h" //----- (01008F7A) -------------------------------------------------------- signed int loader_error(int a1, int a2) { int v2; // eax const CHAR *v3; // esi const CHAR *v4; // edi int v5; // edx int v6; // ecx v2 = loader_errors[0]; v3 = 0; v4 = 0; v5 = 0; if ( loader_errors[0] < 0 ) goto LABEL_13; v6 = 0; do { if ( a1 == v2 ) v3 = off_10235FC[v6]; if ( a2 == v2 ) v4 = off_10235FC[v6]; v6 = 2 * ++v5; v2 = loader_errors[2 * v5]; } while ( v2 >= 0 ); if ( !v3 ) LABEL_13: v3 = off_10235FC[2 * v5]; MessageBoxA(0, v3, v4, 0x2000u); return -1; } // 10235F8: using guessed type int loader_errors[]; //----- (01008FE0) -------------------------------------------------------- DWORD *loader_default_vsi(DWORD *a1) { DWORD *result; // eax result = a1; a1[13] = 0; a1[5] = 1369940824; a1[12] = 0; *a1 = 1064514355; a1[1] = 1058642330; a1[2] = 0; a1[4] = 0; a1[16] = 0; a1[17] = 0; a1[15] = 0; a1[14] = 0; return result; } //----- (0100901F) -------------------------------------------------------- signed int loader_get_sound_id(int a1) { signed int v1; // dx signed int v2; // eax signed int result; // eax signed int v4; // edi int v5; // esi int v6; // eax WORD *v7; // eax const CHAR *lpName; // ST18_4 HFILE hFile; // ST1C_4 int v10; // [esp+10h] [ebp+8h] v1 = 1; if ( sound_count <= 1 ) { LABEL_5: loader_error(25, 26); result = -1; } else { v2 = 1; while ( dword_1027C24[5 * v2] != a1 ) { v2 = ++v1; if ( v1 >= sound_count ) goto LABEL_5; } v4 = v1; v5 = 5 * v1; if ( !dword_1027C28[v5] && !sound_list[v5] ) { v6 = dword_1027C24[v5]; *(float *)&algn_1027C2C[20 * v1] = 0.0; v10 = v6; if ( v6 > 0 && !play_midi_music ) { v7 = (WORD *)partman_field(loader_table, v6, 0); if ( v7 ) { if ( *v7 == 202 ) { lpName = (const CHAR *)partman_field(loader_table, v10, 9); hFile = _lopen(lpName, 0); *(float *)(v5 * 4 + 16940076) = (double)_llseek(hFile, 0, 2) * 0.0000909090909090909; _lclose(hFile); sound_list[v5] = (int)Sound_LoadWaveFile(lpName); } } } } ++dword_1027C28[v5]; result = v4; } return result; } // 10236D8: using guessed type int sound_count; // 102556C: using guessed type int play_midi_music; // 1027C20: using guessed type int sound_list[]; // 1027C24: using guessed type int dword_1027C24[]; // 1027C28: using guessed type int dword_1027C28[]; //----- (0100911D) -------------------------------------------------------- void loader_unload() { signed int v0; // esi LPCVOID *v1; // edi v0 = 1; if ( sound_count > 1 ) { v1 = (LPCVOID *)&unk_1027C34; do { Sound_FreeSound(*v1); ++v0; v1 += 5; } while ( v0 < sound_count ); } if ( dword_1027C30[5 * v0] ) memoryfree(dword_1027C30[5 * v0]); sound_count = 1; } // 10236D8: using guessed type int sound_count; // 1027C30: using guessed type int dword_1027C30[]; //----- (0100916A) -------------------------------------------------------- int loader_loadfrom(WORD *a1) { WORD *v1; // edx int v2; // di WORD *v3; // eax int result; // eax int v5; // ecx v1 = a1; v2 = 0; loader_table = (int)a1; if ( *a1 <= 0 ) { result = sound_count; } else { do { v3 = (WORD *)partman_field((int)v1, v2, 0); v1 = (WORD *)loader_table; if ( v3 && *v3 == 202 ) { result = sound_count; sound_record_table = loader_table; if ( sound_count < 65 ) { v5 = 5 * sound_count; sound_list[v5] = 0; ++result; dword_1027C24[v5] = v2; sound_count = result; } } else { result = sound_count; } ++v2; } while ( v2 < *v1 ); } loader_sound_count = result; return result; } // 10236D8: using guessed type int sound_count; // 1027C10: using guessed type int sound_record_table; // 1027C20: using guessed type int sound_list[]; // 1027C24: using guessed type int dword_1027C24[]; // 1028134: using guessed type int loader_sound_count; //----- (010091EB) -------------------------------------------------------- int loader_query_handle(const char * lpString) { return partman_record_labeled(loader_table, lpString); } //----- (01009207) -------------------------------------------------------- signed int loader_query_visual_states(int a1) { signed int result; // eax WORD *v2; // eax if ( a1 < 0 ) return loader_error(0, 17); v2 = (WORD *)partman_field(loader_table, a1, 10); if ( v2 && *v2 == 100 ) result = (signed int)v2[1]; else result = 1; return result; } //----- (01009249) -------------------------------------------------------- signed int loader_material(int a1, DWORD *a2) { int v2; // edi WORD *v4; // eax float *v5; // esi unsigned int v6; // ebx double v7; // st7 DWORD *v8; // esi double v9; // st7 signed __int64 v10; // rax int v11; // [esp+1Ch] [ebp+8h] int v12; // [esp+1Ch] [ebp+8h] v2 = a1; if ( a1 < 0 ) return loader_error(0, 21); v4 = (WORD *)partman_field(loader_table, a1, 0); if ( !v4 ) return loader_error(1, 21); if ( *v4 == 300 ) { v5 = (float *)partman_field(loader_table, a1, 11); if ( !v5 ) return loader_error(11, 21); v11 = 0; v6 = (unsigned int)partman_field_size(loader_table, v2, 11) >> 2; if ( (signed int)v6 <= 0 ) return 0; while ( 1 ) { v7 = *v5; v8 = v5 + 1; v12 = v11 + 1; v9 = _floor(v7); switch ( (signed int)(signed __int64)v9 ) { case 301: *a2 = *v8; break; case 302: a2[1] = *v8; break; case 304: v10 = (signed __int64)_floor(*(float *)v8); a2[4] = loader_get_sound_id((signed int)v10); break; default: return loader_error(9, 21); } v5 = (float *)(v8 + 1); v11 = v12 + 1; if ( (signed int)v11 >= (signed int)v6 ) return 0; } } return loader_error(3, 21); } //----- (01009349) -------------------------------------------------------- signed int loader_kicker(int a1, DWORD *a2) { WORD *v3; // eax float *v4; // esi double v5; // st7 DWORD *v6; // esi double v7; // st7 signed __int64 v8; // rax int v9; // eax DWORD *v10; // esi int v11; // eax int v12; // eax unsigned int v13; // [esp+14h] [ebp-4h] int v14; // [esp+20h] [ebp+8h] int v15; // [esp+20h] [ebp+8h] if ( a1 < 0 ) return loader_error(0, 20); v3 = (WORD *)partman_field(loader_table, a1, 0); if ( !v3 ) return loader_error(1, 20); if ( *v3 != 400 ) return loader_error(4, 20); v4 = (float *)partman_field(loader_table, a1, 11); if ( !v4 ) return loader_error(11, 20); v13 = (unsigned int)partman_field_size(loader_table, a1, 11) >> 2; v14 = 0; if ( (signed int)v13 <= 0 ) return 0; while ( 1 ) { v5 = *v4; v6 = v4 + 1; v15 = v14 + 1; v7 = _floor(v5); switch ( (signed int)(signed __int64)v7 ) { case 401: *a2 = *v6; goto LABEL_24; case 402: a2[1] = *v6; goto LABEL_24; case 403: a2[2] = *v6; goto LABEL_24; } if ( (signed int)(signed __int64)v7 != 404 ) break; v9 = *v6; v10 = v6 + 1; a2[3] = v9; v11 = *v10; ++v10; a2[4] = v11; v12 = *v10; v4 = (float *)(v10 + 1); v14 = v15 + 3; a2[5] = v12; LABEL_25: if ( (signed int)v14 >= (signed int)v13 ) return 0; } if ( (signed int)(signed __int64)v7 == 405 ) { a2[6] = *v6; goto LABEL_24; } if ( (signed int)(signed __int64)v7 == 406 ) { v8 = (signed __int64)_floor(*(float *)v6); a2[7] = loader_get_sound_id((signed int)v8); LABEL_24: v4 = (float *)(v6 + 1); v14 = v15 + 1; goto LABEL_25; } return loader_error(10, 20); } //----- (01009486) -------------------------------------------------------- signed int loader_state_id(int a1, signed int a2) { int v2; // esi int v3; // di WORD *v5; // eax WORD *v6; // eax v2 = a1; v3 = loader_query_visual_states(a1); if ( v3 <= 0 ) return loader_error(12, 24); v5 = (WORD *)partman_field(loader_table, a1, 0); if ( !v5 ) return loader_error(1, 24); if ( *v5 != 200 ) return loader_error(5, 24); if ( a2 > v3 ) return loader_error(12, 24); if ( !a2 ) return v2; v2 = a2 + a1; v6 = (WORD *)partman_field(loader_table, a2 + a1, 0); if ( !v6 ) return loader_error(1, 24); if ( *v6 == 201 ) return v2; return loader_error(6, 24); } //----- (0100950A) -------------------------------------------------------- signed int loader_query_visual(int a1, signed int a2, DWORD *a3) { DWORD *v3; // edi int v5; // eax int v6; // ebx int v7; // eax signed int *v8; // esi unsigned int v9; // eax int v10; // ebx signed int v11; // ecx _BYTE *v12; // esi int v13; // ebx int v14; // ecx int v15; // ecx int v16; // ecx int v17; // ecx int v18; // ecx int v19; // ecx float *v20; // eax float *v21; // esi signed __int64 v22; // rax int v23; // esi int v24; // [esp+1Ch] [ebp+8h] unsigned int v25; // [esp+24h] [ebp+10h] v3 = a3; loader_default_vsi(a3); if ( a1 < 0 ) return loader_error(0, 18); v5 = loader_state_id(a1, a2); v6 = v5; v24 = v5; if ( v5 < 0 ) return loader_error(16, 18); a3[16] = partman_field(loader_table, v5, 1); v7 = partman_field(loader_table, v6, 12); a3[17] = v7; if ( v7 ) { *(DWORD *)(v7 + 6) = v7 + 14; *(DWORD *)(a3[17] + 10) = *(DWORD *)(a3[17] + 6); } v8 = (signed int *)partman_field(loader_table, v6, 10); if ( v8 ) { v9 = partman_field_size(loader_table, v6, 10); v10 = 0; v25 = v9 >> 1; if ( (signed int)(v9 >> 1) > 0 ) { while ( 1 ) { v11 = *v8; v12 = v8 + 1; v13 = v10 + 1; if ( v11 <= 406 ) { if ( v11 == 406 ) { v3[12] = loader_get_sound_id(*(signed int *)v12); } else { v14 = v11 - 100; if ( v14 ) { v15 = v14 - 200; if ( v15 ) { v16 = v15 - 4; if ( v16 ) { if ( v16 != 96 ) return loader_error(9, 18); if ( loader_kicker(*(signed int *)v12, v3 + 5) ) return loader_error(14, 18); } else { v3[4] = loader_get_sound_id(*(signed int *)v12); } } else if ( loader_material(*(signed int *)v12, v3) ) { return loader_error(15, 18); } } else if ( a2 ) { return loader_error(7, 18); } } goto LABEL_32; } v17 = v11 - 602; if ( !v17 ) { v3[13] |= 1 << *v12; goto LABEL_32; } v18 = v17 - 498; if ( !v18 ) break; v19 = v18 - 1; if ( !v19 ) { v3[15] = loader_get_sound_id(*(signed int *)v12); LABEL_32: v8 = (signed int *)(v12 + 2); v10 = v13 + 1; goto LABEL_33; } if ( v19 != 399 ) return loader_error(9, 18); v8 = (signed int *)(v12 + 16); v10 = v13 + 8; LABEL_33: if ( (signed int)v10 >= (signed int)v25 ) goto LABEL_34; } v3[14] = loader_get_sound_id(*(signed int *)v12); goto LABEL_32; } } LABEL_34: if ( !v3[13] ) v3[13] = 1; v20 = (float *)partman_field(loader_table, v24, 11); if ( !v20 ) return 0; v21 = v20 + 1; if ( *v20 != 600.0 ) return 0; v3[2] = (signed int)((unsigned int)partman_field_size(loader_table, v24, 11) >> 2) / 2 - 2; v22 = (signed __int64)(_floor(*v21) - 1.0); v23 = (int)(v21 + 1); if ( !(WORD)v22 ) { v3[2] = 1; LABEL_40: v3[3] = v23; return 0; } if ( (WORD)v22 == 1 ) { v3[2] = 2; goto LABEL_40; } if ( (signed int)v22 == v3[2] ) goto LABEL_40; return loader_error(8, 18); } //----- (0100975D) -------------------------------------------------------- int loader_query_name(int a1) { if ( a1 >= 0 ) return partman_field(loader_table, a1, 3); loader_error(0, 19); return 0; } //----- (0100978E) -------------------------------------------------------- int loader_query_float_attribute(int a1, signed int a2, int a3) { int v3; // bx int result; // eax int v5; // edi float *v6; // eax float *v7; // esi v3 = 0; if ( a1 >= 0 ) { v5 = loader_state_id(a1, a2); if ( v5 >= 0 ) { while ( 1 ) { v6 = (float *)partman_field_nth(loader_table, v5, 11, v3); v7 = v6; if ( !v6 ) break; if ( (signed int)(signed __int64)_floor(*v6) == a3 ) return (int)(v7 + 1); ++v3; } loader_error(13, 22); result = 0; } else { loader_error(16, 22); result = 0; } } else { loader_error(0, 22); result = 0; } return result; } //----- (0100981A) -------------------------------------------------------- int loader_query_iattribute(int a1, int a2, DWORD *a3) { int v3; // di int result; // eax signed int *v5; // eax signed int *v6; // esi v3 = 0; if ( a1 >= 0 ) { while ( 1 ) { v5 = (signed int *)partman_field_nth(loader_table, a1, 10, v3); v6 = v5; if ( !v5 ) break; if ( *v5 == a2 ) { *a3 = partman_field_size(loader_table, a1, 10) / 2 - 1; return (int)(v6 + 1); } ++v3; } loader_error(2, 23); *a3 = 0; result = 0; } else { loader_error(0, 22); result = 0; } return result; } //----- (01009895) -------------------------------------------------------- double loader_play_sound(int a1) { if ( a1 <= 0 ) return 0.0; Sound_PlaySound(sound_list[5 * a1], 0, 7, 5u, 0); return *(float *)&algn_1027C2C[20 * a1]; } // 1027C20: using guessed type int sound_list[];
26.4
109
0.401926
XplosiveLugnut
47ed68f919d084e86deeb009c4dcdffcbf520811
50,330
cpp
C++
includes/mfbt/tests/TestTextUtils.cpp
gregtatum/spec-cpp
ebd40fa119a302f82ab10a2b8ddd52671f92e2ef
[ "MIT" ]
5
2018-02-01T18:25:35.000Z
2018-02-12T14:09:22.000Z
includes/mfbt/tests/TestTextUtils.cpp
gregtatum/spec-cpp
ebd40fa119a302f82ab10a2b8ddd52671f92e2ef
[ "MIT" ]
null
null
null
includes/mfbt/tests/TestTextUtils.cpp
gregtatum/spec-cpp
ebd40fa119a302f82ab10a2b8ddd52671f92e2ef
[ "MIT" ]
1
2019-03-15T06:01:40.000Z
2019-03-15T06:01:40.000Z
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "./Assertions.h" #include "./TextUtils.h" using mozilla::AsciiAlphanumericToNumber; using mozilla::IsAscii; using mozilla::IsAsciiAlpha; using mozilla::IsAsciiAlphanumeric; using mozilla::IsAsciiDigit; using mozilla::IsAsciiLowercaseAlpha; using mozilla::IsAsciiNullTerminated; using mozilla::IsAsciiUppercaseAlpha; static void TestIsAscii() { // char static_assert(!IsAscii(char(-1)), "char(-1) isn't ASCII"); static_assert(IsAscii('\0'), "nul is ASCII"); static_assert(IsAscii('A'), "'A' is ASCII"); static_assert(IsAscii('B'), "'B' is ASCII"); static_assert(IsAscii('M'), "'M' is ASCII"); static_assert(IsAscii('Y'), "'Y' is ASCII"); static_assert(IsAscii('Z'), "'Z' is ASCII"); static_assert(IsAscii('['), "'[' is ASCII"); static_assert(IsAscii('`'), "'`' is ASCII"); static_assert(IsAscii('a'), "'a' is ASCII"); static_assert(IsAscii('b'), "'b' is ASCII"); static_assert(IsAscii('m'), "'m' is ASCII"); static_assert(IsAscii('y'), "'y' is ASCII"); static_assert(IsAscii('z'), "'z' is ASCII"); static_assert(IsAscii('{'), "'{' is ASCII"); static_assert(IsAscii('5'), "'5' is ASCII"); static_assert(IsAscii('\x7F'), "'\\x7F' is ASCII"); static_assert(!IsAscii('\x80'), "'\\x80' isn't ASCII"); // char16_t static_assert(!IsAscii(char16_t(-1)), "char16_t(-1) isn't ASCII"); static_assert(IsAscii(u'\0'), "nul is ASCII"); static_assert(IsAscii(u'A'), "u'A' is ASCII"); static_assert(IsAscii(u'B'), "u'B' is ASCII"); static_assert(IsAscii(u'M'), "u'M' is ASCII"); static_assert(IsAscii(u'Y'), "u'Y' is ASCII"); static_assert(IsAscii(u'Z'), "u'Z' is ASCII"); static_assert(IsAscii(u'['), "u'[' is ASCII"); static_assert(IsAscii(u'`'), "u'`' is ASCII"); static_assert(IsAscii(u'a'), "u'a' is ASCII"); static_assert(IsAscii(u'b'), "u'b' is ASCII"); static_assert(IsAscii(u'm'), "u'm' is ASCII"); static_assert(IsAscii(u'y'), "u'y' is ASCII"); static_assert(IsAscii(u'z'), "u'z' is ASCII"); static_assert(IsAscii(u'{'), "u'{' is ASCII"); static_assert(IsAscii(u'5'), "u'5' is ASCII"); static_assert(IsAscii(u'\x7F'), "u'\\x7F' is ASCII"); static_assert(!IsAscii(u'\x80'), "u'\\x80' isn't ASCII"); // char32_t static_assert(!IsAscii(char32_t(-1)), "char32_t(-1) isn't ASCII"); static_assert(IsAscii(U'\0'), "nul is ASCII"); static_assert(IsAscii(U'A'), "U'A' is ASCII"); static_assert(IsAscii(U'B'), "U'B' is ASCII"); static_assert(IsAscii(U'M'), "U'M' is ASCII"); static_assert(IsAscii(U'Y'), "U'Y' is ASCII"); static_assert(IsAscii(U'Z'), "U'Z' is ASCII"); static_assert(IsAscii(U'['), "U'[' is ASCII"); static_assert(IsAscii(U'`'), "U'`' is ASCII"); static_assert(IsAscii(U'a'), "U'a' is ASCII"); static_assert(IsAscii(U'b'), "U'b' is ASCII"); static_assert(IsAscii(U'm'), "U'm' is ASCII"); static_assert(IsAscii(U'y'), "U'y' is ASCII"); static_assert(IsAscii(U'z'), "U'z' is ASCII"); static_assert(IsAscii(U'{'), "U'{' is ASCII"); static_assert(IsAscii(U'5'), "U'5' is ASCII"); static_assert(IsAscii(U'\x7F'), "U'\\x7F' is ASCII"); static_assert(!IsAscii(U'\x80'), "U'\\x80' isn't ASCII"); } static void TestIsAsciiNullTerminated() { // char constexpr char allChar[] = "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\0x0C\x0D\x0E\x0F" "\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\0x1C\x1D\x1E\x1F" "\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\0x2C\x2D\x2E\x2F" "\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\0x3C\x3D\x3E\x3F" "\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\0x4C\x4D\x4E\x4F" "\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\0x5C\x5D\x5E\x5F" "\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\0x6C\x6D\x6E\x6F" "\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\0x7C\x7D\x7E\x7F"; static_assert(IsAsciiNullTerminated(allChar), "allChar is ASCII"); constexpr char loBadChar[] = "\x80"; static_assert(!IsAsciiNullTerminated(loBadChar), "loBadChar isn't ASCII"); constexpr char hiBadChar[] = "\xFF"; static_assert(!IsAsciiNullTerminated(hiBadChar), "hiBadChar isn't ASCII"); // char16_t constexpr char16_t allChar16[] = u"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\0x0C\x0D\x0E\x0F" "\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\0x1C\x1D\x1E\x1F" "\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\0x2C\x2D\x2E\x2F" "\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\0x3C\x3D\x3E\x3F" "\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\0x4C\x4D\x4E\x4F" "\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\0x5C\x5D\x5E\x5F" "\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\0x6C\x6D\x6E\x6F" "\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\0x7C\x7D\x7E\x7F"; static_assert(IsAsciiNullTerminated(allChar16), "allChar16 is ASCII"); constexpr char16_t loBadChar16[] = u"\x80"; static_assert(!IsAsciiNullTerminated(loBadChar16), "loBadChar16 isn't ASCII"); constexpr char16_t hiBadChar16[] = u"\xFF"; static_assert(!IsAsciiNullTerminated(hiBadChar16), "hiBadChar16 isn't ASCII"); constexpr char16_t highestChar16[] = u"\uFFFF"; static_assert(!IsAsciiNullTerminated(highestChar16), "highestChar16 isn't ASCII"); // char32_t constexpr char32_t allChar32[] = U"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\0x0C\x0D\x0E\x0F" "\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\0x1C\x1D\x1E\x1F" "\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\0x2C\x2D\x2E\x2F" "\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\0x3C\x3D\x3E\x3F" "\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\0x4C\x4D\x4E\x4F" "\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\0x5C\x5D\x5E\x5F" "\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\0x6C\x6D\x6E\x6F" "\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\0x7C\x7D\x7E\x7F"; static_assert(IsAsciiNullTerminated(allChar32), "allChar32 is ASCII"); constexpr char32_t loBadChar32[] = U"\x80"; static_assert(!IsAsciiNullTerminated(loBadChar32), "loBadChar32 isn't ASCII"); constexpr char32_t hiBadChar32[] = U"\xFF"; static_assert(!IsAsciiNullTerminated(hiBadChar32), "hiBadChar32 isn't ASCII"); constexpr char32_t highestChar32[] = {static_cast<char32_t>(-1), 0}; static_assert(!IsAsciiNullTerminated(highestChar32), "highestChar32 isn't ASCII"); } static void TestIsAsciiAlpha() { // char static_assert(!IsAsciiAlpha('@'), "'@' isn't ASCII alpha"); static_assert('@' == 0x40, "'@' has value 0x40"); static_assert('A' == 0x41, "'A' has value 0x41"); static_assert(IsAsciiAlpha('A'), "'A' is ASCII alpha"); static_assert(IsAsciiAlpha('B'), "'B' is ASCII alpha"); static_assert(IsAsciiAlpha('M'), "'M' is ASCII alpha"); static_assert(IsAsciiAlpha('Y'), "'Y' is ASCII alpha"); static_assert(IsAsciiAlpha('Z'), "'Z' is ASCII alpha"); static_assert('Z' == 0x5A, "'Z' has value 0x5A"); static_assert('[' == 0x5B, "'[' has value 0x5B"); static_assert(!IsAsciiAlpha('['), "'[' isn't ASCII alpha"); static_assert(!IsAsciiAlpha('`'), "'`' isn't ASCII alpha"); static_assert('`' == 0x60, "'`' has value 0x60"); static_assert('a' == 0x61, "'a' has value 0x61"); static_assert(IsAsciiAlpha('a'), "'a' is ASCII alpha"); static_assert(IsAsciiAlpha('b'), "'b' is ASCII alpha"); static_assert(IsAsciiAlpha('m'), "'m' is ASCII alpha"); static_assert(IsAsciiAlpha('y'), "'y' is ASCII alpha"); static_assert(IsAsciiAlpha('z'), "'z' is ASCII alpha"); static_assert('z' == 0x7A, "'z' has value 0x7A"); static_assert('{' == 0x7B, "'{' has value 0x7B"); static_assert(!IsAsciiAlpha('{'), "'{' isn't ASCII alpha"); static_assert(!IsAsciiAlpha('5'), "'5' isn't ASCII alpha"); // char16_t static_assert(!IsAsciiAlpha(u'@'), "u'@' isn't ASCII alpha"); static_assert(u'@' == 0x40, "u'@' has value 0x40"); static_assert(u'A' == 0x41, "u'A' has value 0x41"); static_assert(IsAsciiAlpha(u'A'), "u'A' is ASCII alpha"); static_assert(IsAsciiAlpha(u'B'), "u'B' is ASCII alpha"); static_assert(IsAsciiAlpha(u'M'), "u'M' is ASCII alpha"); static_assert(IsAsciiAlpha(u'Y'), "u'Y' is ASCII alpha"); static_assert(IsAsciiAlpha(u'Z'), "u'Z' is ASCII alpha"); static_assert(u'Z' == 0x5A, "u'Z' has value 0x5A"); static_assert(u'[' == 0x5B, "u'[' has value 0x5B"); static_assert(!IsAsciiAlpha(u'['), "u'[' isn't ASCII alpha"); static_assert(!IsAsciiAlpha(u'`'), "u'`' isn't ASCII alpha"); static_assert(u'`' == 0x60, "u'`' has value 0x60"); static_assert(u'a' == 0x61, "u'a' has value 0x61"); static_assert(IsAsciiAlpha(u'a'), "u'a' is ASCII alpha"); static_assert(IsAsciiAlpha(u'b'), "u'b' is ASCII alpha"); static_assert(IsAsciiAlpha(u'm'), "u'm' is ASCII alpha"); static_assert(IsAsciiAlpha(u'y'), "u'y' is ASCII alpha"); static_assert(IsAsciiAlpha(u'z'), "u'z' is ASCII alpha"); static_assert(u'z' == 0x7A, "u'z' has value 0x7A"); static_assert(u'{' == 0x7B, "u'{' has value 0x7B"); static_assert(!IsAsciiAlpha(u'{'), "u'{' isn't ASCII alpha"); static_assert(!IsAsciiAlpha(u'5'), "u'5' isn't ASCII alpha"); // char32_t static_assert(!IsAsciiAlpha(U'@'), "U'@' isn't ASCII alpha"); static_assert(U'@' == 0x40, "U'@' has value 0x40"); static_assert(U'A' == 0x41, "U'A' has value 0x41"); static_assert(IsAsciiAlpha(U'A'), "U'A' is ASCII alpha"); static_assert(IsAsciiAlpha(U'B'), "U'B' is ASCII alpha"); static_assert(IsAsciiAlpha(U'M'), "U'M' is ASCII alpha"); static_assert(IsAsciiAlpha(U'Y'), "U'Y' is ASCII alpha"); static_assert(IsAsciiAlpha(U'Z'), "U'Z' is ASCII alpha"); static_assert(U'Z' == 0x5A, "U'Z' has value 0x5A"); static_assert(U'[' == 0x5B, "U'[' has value 0x5B"); static_assert(!IsAsciiAlpha(U'['), "U'[' isn't ASCII alpha"); static_assert(!IsAsciiAlpha(U'`'), "U'`' isn't ASCII alpha"); static_assert(U'`' == 0x60, "U'`' has value 0x60"); static_assert(U'a' == 0x61, "U'a' has value 0x61"); static_assert(IsAsciiAlpha(U'a'), "U'a' is ASCII alpha"); static_assert(IsAsciiAlpha(U'b'), "U'b' is ASCII alpha"); static_assert(IsAsciiAlpha(U'm'), "U'm' is ASCII alpha"); static_assert(IsAsciiAlpha(U'y'), "U'y' is ASCII alpha"); static_assert(IsAsciiAlpha(U'z'), "U'z' is ASCII alpha"); static_assert(U'z' == 0x7A, "U'z' has value 0x7A"); static_assert(U'{' == 0x7B, "U'{' has value 0x7B"); static_assert(!IsAsciiAlpha(U'{'), "U'{' isn't ASCII alpha"); static_assert(!IsAsciiAlpha(U'5'), "U'5' isn't ASCII alpha"); } static void TestIsAsciiUppercaseAlpha() { // char static_assert(!IsAsciiUppercaseAlpha('@'), "'@' isn't ASCII alpha uppercase"); static_assert('@' == 0x40, "'@' has value 0x40"); static_assert('A' == 0x41, "'A' has value 0x41"); static_assert(IsAsciiUppercaseAlpha('A'), "'A' is ASCII alpha uppercase"); static_assert(IsAsciiUppercaseAlpha('B'), "'B' is ASCII alpha uppercase"); static_assert(IsAsciiUppercaseAlpha('M'), "'M' is ASCII alpha uppercase"); static_assert(IsAsciiUppercaseAlpha('Y'), "'Y' is ASCII alpha uppercase"); static_assert(IsAsciiUppercaseAlpha('Z'), "'Z' is ASCII alpha uppercase"); static_assert('Z' == 0x5A, "'Z' has value 0x5A"); static_assert('[' == 0x5B, "'[' has value 0x5B"); static_assert(!IsAsciiUppercaseAlpha('['), "'[' isn't ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha('`'), "'`' isn't ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha('a'), "'a' is ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha('b'), "'b' is ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha('m'), "'m' is ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha('y'), "'y' is ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha('z'), "'z' is ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha('{'), "'{' isn't ASCII alpha uppercase"); // char16_t static_assert(!IsAsciiUppercaseAlpha(u'@'), "u'@' isn't ASCII alpha uppercase"); static_assert(u'@' == 0x40, "u'@' has value 0x40"); static_assert(u'A' == 0x41, "u'A' has value 0x41"); static_assert(IsAsciiUppercaseAlpha(u'A'), "u'A' is ASCII alpha uppercase"); static_assert(IsAsciiUppercaseAlpha(u'B'), "u'B' is ASCII alpha uppercase"); static_assert(IsAsciiUppercaseAlpha(u'M'), "u'M' is ASCII alpha uppercase"); static_assert(IsAsciiUppercaseAlpha(u'Y'), "u'Y' is ASCII alpha uppercase"); static_assert(IsAsciiUppercaseAlpha(u'Z'), "u'Z' is ASCII alpha uppercase"); static_assert(u'Z' == 0x5A, "u'Z' has value 0x5A"); static_assert(u'[' == 0x5B, "u'[' has value 0x5B"); static_assert(!IsAsciiUppercaseAlpha(u'['), "u'[' isn't ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha(u'`'), "u'`' isn't ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha(u'a'), "u'a' is ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha(u'b'), "u'b' is ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha(u'm'), "u'm' is ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha(u'y'), "u'y' is ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha(u'z'), "u'z' is ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha(u'{'), "u'{' isn't ASCII alpha uppercase"); // char32_t static_assert(!IsAsciiUppercaseAlpha(U'@'), "U'@' isn't ASCII alpha uppercase"); static_assert(U'@' == 0x40, "U'@' has value 0x40"); static_assert(U'A' == 0x41, "U'A' has value 0x41"); static_assert(IsAsciiUppercaseAlpha(U'A'), "U'A' is ASCII alpha uppercase"); static_assert(IsAsciiUppercaseAlpha(U'B'), "U'B' is ASCII alpha uppercase"); static_assert(IsAsciiUppercaseAlpha(U'M'), "U'M' is ASCII alpha uppercase"); static_assert(IsAsciiUppercaseAlpha(U'Y'), "U'Y' is ASCII alpha uppercase"); static_assert(IsAsciiUppercaseAlpha(U'Z'), "U'Z' is ASCII alpha uppercase"); static_assert(U'Z' == 0x5A, "U'Z' has value 0x5A"); static_assert(U'[' == 0x5B, "U'[' has value 0x5B"); static_assert(!IsAsciiUppercaseAlpha(U'['), "U'[' isn't ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha(U'`'), "U'`' isn't ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha(U'a'), "U'a' is ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha(U'b'), "U'b' is ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha(U'm'), "U'm' is ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha(U'y'), "U'y' is ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha(U'z'), "U'z' is ASCII alpha uppercase"); static_assert(!IsAsciiUppercaseAlpha(U'{'), "U'{' isn't ASCII alpha uppercase"); } static void TestIsAsciiLowercaseAlpha() { // char static_assert(!IsAsciiLowercaseAlpha('`'), "'`' isn't ASCII alpha lowercase"); static_assert('`' == 0x60, "'`' has value 0x60"); static_assert('a' == 0x61, "'a' has value 0x61"); static_assert(IsAsciiLowercaseAlpha('a'), "'a' is ASCII alpha lowercase"); static_assert(IsAsciiLowercaseAlpha('b'), "'b' is ASCII alpha lowercase"); static_assert(IsAsciiLowercaseAlpha('m'), "'m' is ASCII alpha lowercase"); static_assert(IsAsciiLowercaseAlpha('y'), "'y' is ASCII alpha lowercase"); static_assert(IsAsciiLowercaseAlpha('z'), "'z' is ASCII alpha lowercase"); static_assert('z' == 0x7A, "'z' has value 0x7A"); static_assert('{' == 0x7B, "'{' has value 0x7B"); static_assert(!IsAsciiLowercaseAlpha('{'), "'{' isn't ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha('@'), "'@' isn't ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha('A'), "'A' is ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha('B'), "'B' is ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha('M'), "'M' is ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha('Y'), "'Y' is ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha('Z'), "'Z' is ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha('['), "'[' isn't ASCII alpha lowercase"); // char16_t static_assert(!IsAsciiLowercaseAlpha(u'`'), "u'`' isn't ASCII alpha lowercase"); static_assert(u'`' == 0x60, "u'`' has value 0x60"); static_assert(u'a' == 0x61, "u'a' has value 0x61"); static_assert(IsAsciiLowercaseAlpha(u'a'), "u'a' is ASCII alpha lowercase"); static_assert(IsAsciiLowercaseAlpha(u'b'), "u'b' is ASCII alpha lowercase"); static_assert(IsAsciiLowercaseAlpha(u'm'), "u'm' is ASCII alpha lowercase"); static_assert(IsAsciiLowercaseAlpha(u'y'), "u'y' is ASCII alpha lowercase"); static_assert(IsAsciiLowercaseAlpha(u'z'), "u'z' is ASCII alpha lowercase"); static_assert(u'z' == 0x7A, "u'z' has value 0x7A"); static_assert(u'{' == 0x7B, "u'{' has value 0x7B"); static_assert(!IsAsciiLowercaseAlpha(u'{'), "u'{' isn't ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha(u'@'), "u'@' isn't ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha(u'A'), "u'A' is ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha(u'B'), "u'B' is ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha(u'M'), "u'M' is ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha(u'Y'), "u'Y' is ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha(u'Z'), "u'Z' is ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha(u'['), "u'[' isn't ASCII alpha lowercase"); // char32_t static_assert(!IsAsciiLowercaseAlpha(U'`'), "U'`' isn't ASCII alpha lowercase"); static_assert(U'`' == 0x60, "U'`' has value 0x60"); static_assert(U'a' == 0x61, "U'a' has value 0x61"); static_assert(IsAsciiLowercaseAlpha(U'a'), "U'a' is ASCII alpha lowercase"); static_assert(IsAsciiLowercaseAlpha(U'b'), "U'b' is ASCII alpha lowercase"); static_assert(IsAsciiLowercaseAlpha(U'm'), "U'm' is ASCII alpha lowercase"); static_assert(IsAsciiLowercaseAlpha(U'y'), "U'y' is ASCII alpha lowercase"); static_assert(IsAsciiLowercaseAlpha(U'z'), "U'z' is ASCII alpha lowercase"); static_assert(U'z' == 0x7A, "U'z' has value 0x7A"); static_assert(U'{' == 0x7B, "U'{' has value 0x7B"); static_assert(!IsAsciiLowercaseAlpha(U'{'), "U'{' isn't ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha(U'@'), "U'@' isn't ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha(U'A'), "U'A' is ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha(U'B'), "U'B' is ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha(U'M'), "U'M' is ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha(U'Y'), "U'Y' is ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha(U'Z'), "U'Z' is ASCII alpha lowercase"); static_assert(!IsAsciiLowercaseAlpha(U'['), "U'[' isn't ASCII alpha lowercase"); } static void TestIsAsciiAlphanumeric() { // char static_assert(!IsAsciiAlphanumeric('/'), "'/' isn't ASCII alphanumeric"); static_assert('/' == 0x2F, "'/' has value 0x2F"); static_assert('0' == 0x30, "'0' has value 0x30"); static_assert(IsAsciiAlphanumeric('0'), "'0' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric('1'), "'1' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric('5'), "'5' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric('8'), "'8' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric('9'), "'9' is ASCII alphanumeric"); static_assert('9' == 0x39, "'9' has value 0x39"); static_assert(':' == 0x3A, "':' has value 0x3A"); static_assert(!IsAsciiAlphanumeric(':'), "':' isn't ASCII alphanumeric"); static_assert(!IsAsciiAlphanumeric('@'), "'@' isn't ASCII alphanumeric"); static_assert('@' == 0x40, "'@' has value 0x40"); static_assert('A' == 0x41, "'A' has value 0x41"); static_assert(IsAsciiAlphanumeric('A'), "'A' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric('B'), "'B' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric('M'), "'M' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric('Y'), "'Y' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric('Z'), "'Z' is ASCII alphanumeric"); static_assert('Z' == 0x5A, "'Z' has value 0x5A"); static_assert('[' == 0x5B, "'[' has value 0x5B"); static_assert(!IsAsciiAlphanumeric('['), "'[' isn't ASCII alphanumeric"); static_assert(!IsAsciiAlphanumeric('`'), "'`' isn't ASCII alphanumeric"); static_assert('`' == 0x60, "'`' has value 0x60"); static_assert('a' == 0x61, "'a' has value 0x61"); static_assert(IsAsciiAlphanumeric('a'), "'a' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric('b'), "'b' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric('m'), "'m' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric('y'), "'y' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric('z'), "'z' is ASCII alphanumeric"); static_assert('z' == 0x7A, "'z' has value 0x7A"); static_assert('{' == 0x7B, "'{' has value 0x7B"); static_assert(!IsAsciiAlphanumeric('{'), "'{' isn't ASCII alphanumeric"); // char16_t static_assert(!IsAsciiAlphanumeric(u'/'), "u'/' isn't ASCII alphanumeric"); static_assert(u'/' == 0x2F, "u'/' has value 0x2F"); static_assert(u'0' == 0x30, "u'0' has value 0x30"); static_assert(IsAsciiAlphanumeric(u'0'), "u'0' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(u'1'), "u'1' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(u'5'), "u'5' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(u'8'), "u'8' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(u'9'), "u'9' is ASCII alphanumeric"); static_assert(u'9' == 0x39, "u'9' has value 0x39"); static_assert(u':' == 0x3A, "u':' has value 0x3A"); static_assert(!IsAsciiAlphanumeric(u':'), "u':' isn't ASCII alphanumeric"); static_assert(!IsAsciiAlphanumeric(u'@'), "u'@' isn't ASCII alphanumeric"); static_assert(u'@' == 0x40, "u'@' has value 0x40"); static_assert(u'A' == 0x41, "u'A' has value 0x41"); static_assert(IsAsciiAlphanumeric(u'A'), "u'A' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(u'B'), "u'B' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(u'M'), "u'M' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(u'Y'), "u'Y' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(u'Z'), "u'Z' is ASCII alphanumeric"); static_assert(u'Z' == 0x5A, "u'Z' has value 0x5A"); static_assert(u'[' == 0x5B, "u'[' has value 0x5B"); static_assert(!IsAsciiAlphanumeric(u'['), "u'[' isn't ASCII alphanumeric"); static_assert(!IsAsciiAlphanumeric(u'`'), "u'`' isn't ASCII alphanumeric"); static_assert(u'`' == 0x60, "u'`' has value 0x60"); static_assert(u'a' == 0x61, "u'a' has value 0x61"); static_assert(IsAsciiAlphanumeric(u'a'), "u'a' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(u'b'), "u'b' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(u'm'), "u'm' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(u'y'), "u'y' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(u'z'), "u'z' is ASCII alphanumeric"); static_assert(u'z' == 0x7A, "u'z' has value 0x7A"); static_assert(u'{' == 0x7B, "u'{' has value 0x7B"); static_assert(!IsAsciiAlphanumeric(u'{'), "u'{' isn't ASCII alphanumeric"); // char32_t static_assert(!IsAsciiAlphanumeric(U'/'), "U'/' isn't ASCII alphanumeric"); static_assert(U'/' == 0x2F, "U'/' has value 0x2F"); static_assert(U'0' == 0x30, "U'0' has value 0x30"); static_assert(IsAsciiAlphanumeric(U'0'), "U'0' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(U'1'), "U'1' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(U'5'), "U'5' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(U'8'), "U'8' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(U'9'), "U'9' is ASCII alphanumeric"); static_assert(U'9' == 0x39, "U'9' has value 0x39"); static_assert(U':' == 0x3A, "U':' has value 0x3A"); static_assert(!IsAsciiAlphanumeric(U':'), "U':' isn't ASCII alphanumeric"); static_assert(!IsAsciiAlphanumeric(U'@'), "U'@' isn't ASCII alphanumeric"); static_assert(U'@' == 0x40, "U'@' has value 0x40"); static_assert(U'A' == 0x41, "U'A' has value 0x41"); static_assert(IsAsciiAlphanumeric(U'A'), "U'A' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(U'B'), "U'B' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(U'M'), "U'M' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(U'Y'), "U'Y' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(U'Z'), "U'Z' is ASCII alphanumeric"); static_assert(U'Z' == 0x5A, "U'Z' has value 0x5A"); static_assert(U'[' == 0x5B, "U'[' has value 0x5B"); static_assert(!IsAsciiAlphanumeric(U'['), "U'[' isn't ASCII alphanumeric"); static_assert(!IsAsciiAlphanumeric(U'`'), "U'`' isn't ASCII alphanumeric"); static_assert(U'`' == 0x60, "U'`' has value 0x60"); static_assert(U'a' == 0x61, "U'a' has value 0x61"); static_assert(IsAsciiAlphanumeric(U'a'), "U'a' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(U'b'), "U'b' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(U'm'), "U'm' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(U'y'), "U'y' is ASCII alphanumeric"); static_assert(IsAsciiAlphanumeric(U'z'), "U'z' is ASCII alphanumeric"); static_assert(U'z' == 0x7A, "U'z' has value 0x7A"); static_assert(U'{' == 0x7B, "U'{' has value 0x7B"); static_assert(!IsAsciiAlphanumeric(U'{'), "U'{' isn't ASCII alphanumeric"); } static void TestAsciiAlphanumericToNumber() { // When AsciiAlphanumericToNumber becomes constexpr, make sure to convert all // these to just static_assert. // char MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('0') == 0, "'0' converts to 0"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('1') == 1, "'1' converts to 1"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('2') == 2, "'2' converts to 2"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('3') == 3, "'3' converts to 3"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('4') == 4, "'4' converts to 4"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('5') == 5, "'5' converts to 5"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('6') == 6, "'6' converts to 6"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('7') == 7, "'7' converts to 7"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('8') == 8, "'8' converts to 8"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('9') == 9, "'9' converts to 9"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('A') == 10, "'A' converts to 10"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('B') == 11, "'B' converts to 11"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('C') == 12, "'C' converts to 12"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('D') == 13, "'D' converts to 13"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('E') == 14, "'E' converts to 14"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('F') == 15, "'F' converts to 15"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('G') == 16, "'G' converts to 16"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('H') == 17, "'H' converts to 17"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('I') == 18, "'I' converts to 18"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('J') == 19, "'J' converts to 19"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('K') == 20, "'K' converts to 20"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('L') == 21, "'L' converts to 21"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('M') == 22, "'M' converts to 22"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('N') == 23, "'N' converts to 23"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('O') == 24, "'O' converts to 24"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('P') == 25, "'P' converts to 25"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('Q') == 26, "'Q' converts to 26"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('R') == 27, "'R' converts to 27"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('S') == 28, "'S' converts to 28"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('T') == 29, "'T' converts to 29"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('U') == 30, "'U' converts to 30"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('V') == 31, "'V' converts to 31"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('W') == 32, "'W' converts to 32"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('X') == 33, "'X' converts to 33"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('Y') == 34, "'Y' converts to 34"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('Z') == 35, "'Z' converts to 35"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('a') == 10, "'a' converts to 10"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('b') == 11, "'b' converts to 11"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('c') == 12, "'c' converts to 12"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('d') == 13, "'d' converts to 13"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('e') == 14, "'e' converts to 14"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('f') == 15, "'f' converts to 15"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('g') == 16, "'g' converts to 16"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('h') == 17, "'h' converts to 17"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('i') == 18, "'i' converts to 18"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('j') == 19, "'j' converts to 19"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('k') == 20, "'k' converts to 20"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('l') == 21, "'l' converts to 21"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('m') == 22, "'m' converts to 22"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('n') == 23, "'n' converts to 23"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('o') == 24, "'o' converts to 24"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('p') == 25, "'p' converts to 25"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('q') == 26, "'q' converts to 26"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('r') == 27, "'r' converts to 27"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('s') == 28, "'s' converts to 28"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('t') == 29, "'t' converts to 29"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('u') == 30, "'u' converts to 30"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('v') == 31, "'v' converts to 31"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('w') == 32, "'w' converts to 32"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('x') == 33, "'x' converts to 33"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('y') == 34, "'y' converts to 34"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber('z') == 35, "'z' converts to 35"); // char16_t MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'0') == 0, "u'0' converts to 0"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'1') == 1, "u'1' converts to 1"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'2') == 2, "u'2' converts to 2"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'3') == 3, "u'3' converts to 3"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'4') == 4, "u'4' converts to 4"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'5') == 5, "u'5' converts to 5"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'6') == 6, "u'6' converts to 6"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'7') == 7, "u'7' converts to 7"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'8') == 8, "u'8' converts to 8"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'9') == 9, "u'9' converts to 9"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'A') == 10, "u'A' converts to 10"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'B') == 11, "u'B' converts to 11"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'C') == 12, "u'C' converts to 12"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'D') == 13, "u'D' converts to 13"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'E') == 14, "u'E' converts to 14"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'F') == 15, "u'F' converts to 15"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'G') == 16, "u'G' converts to 16"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'H') == 17, "u'H' converts to 17"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'I') == 18, "u'I' converts to 18"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'J') == 19, "u'J' converts to 19"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'K') == 20, "u'K' converts to 20"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'L') == 21, "u'L' converts to 21"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'M') == 22, "u'M' converts to 22"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'N') == 23, "u'N' converts to 23"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'O') == 24, "u'O' converts to 24"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'P') == 25, "u'P' converts to 25"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'Q') == 26, "u'Q' converts to 26"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'R') == 27, "u'R' converts to 27"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'S') == 28, "u'S' converts to 28"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'T') == 29, "u'T' converts to 29"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'U') == 30, "u'U' converts to 30"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'V') == 31, "u'V' converts to 31"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'W') == 32, "u'W' converts to 32"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'X') == 33, "u'X' converts to 33"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'Y') == 34, "u'Y' converts to 34"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'Z') == 35, "u'Z' converts to 35"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'a') == 10, "u'a' converts to 10"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'b') == 11, "u'b' converts to 11"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'c') == 12, "u'c' converts to 12"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'd') == 13, "u'd' converts to 13"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'e') == 14, "u'e' converts to 14"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'f') == 15, "u'f' converts to 15"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'g') == 16, "u'g' converts to 16"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'h') == 17, "u'h' converts to 17"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'i') == 18, "u'i' converts to 18"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'j') == 19, "u'j' converts to 19"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'k') == 20, "u'k' converts to 20"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'l') == 21, "u'l' converts to 21"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'm') == 22, "u'm' converts to 22"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'n') == 23, "u'n' converts to 23"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'o') == 24, "u'o' converts to 24"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'p') == 25, "u'p' converts to 25"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'q') == 26, "u'q' converts to 26"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'r') == 27, "u'r' converts to 27"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u's') == 28, "u's' converts to 28"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u't') == 29, "u't' converts to 29"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'u') == 30, "u'u' converts to 30"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'v') == 31, "u'v' converts to 31"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'w') == 32, "u'w' converts to 32"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'x') == 33, "u'x' converts to 33"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'y') == 34, "u'y' converts to 34"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(u'z') == 35, "u'z' converts to 35"); // char32_t MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'0') == 0, "U'0' converts to 0"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'1') == 1, "U'1' converts to 1"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'2') == 2, "U'2' converts to 2"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'3') == 3, "U'3' converts to 3"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'4') == 4, "U'4' converts to 4"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'5') == 5, "U'5' converts to 5"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'6') == 6, "U'6' converts to 6"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'7') == 7, "U'7' converts to 7"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'8') == 8, "U'8' converts to 8"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'9') == 9, "U'9' converts to 9"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'A') == 10, "U'A' converts to 10"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'B') == 11, "U'B' converts to 11"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'C') == 12, "U'C' converts to 12"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'D') == 13, "U'D' converts to 13"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'E') == 14, "U'E' converts to 14"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'F') == 15, "U'F' converts to 15"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'G') == 16, "U'G' converts to 16"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'H') == 17, "U'H' converts to 17"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'I') == 18, "U'I' converts to 18"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'J') == 19, "U'J' converts to 19"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'K') == 20, "U'K' converts to 20"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'L') == 21, "U'L' converts to 21"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'M') == 22, "U'M' converts to 22"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'N') == 23, "U'N' converts to 23"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'O') == 24, "U'O' converts to 24"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'P') == 25, "U'P' converts to 25"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'Q') == 26, "U'Q' converts to 26"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'R') == 27, "U'R' converts to 27"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'S') == 28, "U'S' converts to 28"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'T') == 29, "U'T' converts to 29"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'U') == 30, "U'U' converts to 30"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'V') == 31, "U'V' converts to 31"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'W') == 32, "U'W' converts to 32"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'X') == 33, "U'X' converts to 33"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'Y') == 34, "U'Y' converts to 34"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'Z') == 35, "U'Z' converts to 35"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'a') == 10, "U'a' converts to 10"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'b') == 11, "U'b' converts to 11"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'c') == 12, "U'c' converts to 12"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'd') == 13, "U'd' converts to 13"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'e') == 14, "U'e' converts to 14"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'f') == 15, "U'f' converts to 15"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'g') == 16, "U'g' converts to 16"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'h') == 17, "U'h' converts to 17"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'i') == 18, "U'i' converts to 18"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'j') == 19, "U'j' converts to 19"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'k') == 20, "U'k' converts to 20"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'l') == 21, "U'l' converts to 21"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'm') == 22, "U'm' converts to 22"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'n') == 23, "U'n' converts to 23"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'o') == 24, "U'o' converts to 24"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'p') == 25, "U'p' converts to 25"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'q') == 26, "U'q' converts to 26"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'r') == 27, "U'r' converts to 27"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U's') == 28, "U's' converts to 28"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U't') == 29, "U't' converts to 29"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'u') == 30, "U'u' converts to 30"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'v') == 31, "U'v' converts to 31"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'w') == 32, "U'w' converts to 32"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'x') == 33, "U'x' converts to 33"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'y') == 34, "U'y' converts to 34"); MOZ_RELEASE_ASSERT(AsciiAlphanumericToNumber(U'z') == 35, "U'z' converts to 35"); } static void TestIsAsciiDigit() { // char static_assert(!IsAsciiDigit('/'), "'/' isn't an ASCII digit"); static_assert('/' == 0x2F, "'/' has value 0x2F"); static_assert('0' == 0x30, "'0' has value 0x30"); static_assert(IsAsciiDigit('0'), "'0' is an ASCII digit"); static_assert(IsAsciiDigit('1'), "'1' is an ASCII digit"); static_assert(IsAsciiDigit('5'), "'5' is an ASCII digit"); static_assert(IsAsciiDigit('8'), "'8' is an ASCII digit"); static_assert(IsAsciiDigit('9'), "'9' is an ASCII digit"); static_assert('9' == 0x39, "'9' has value 0x39"); static_assert(':' == 0x3A, "':' has value 0x3A"); static_assert(!IsAsciiDigit(':'), "':' isn't an ASCII digit"); static_assert(!IsAsciiDigit('@'), "'@' isn't an ASCII digit"); static_assert(!IsAsciiDigit('A'), "'A' isn't an ASCII digit"); static_assert(!IsAsciiDigit('B'), "'B' isn't an ASCII digit"); static_assert(!IsAsciiDigit('M'), "'M' isn't an ASCII digit"); static_assert(!IsAsciiDigit('Y'), "'Y' isn't an ASCII digit"); static_assert(!IsAsciiDigit('Z'), "'Z' isn't an ASCII digit"); static_assert(!IsAsciiDigit('['), "'[' isn't an ASCII digit"); static_assert(!IsAsciiDigit('`'), "'`' isn't an ASCII digit"); static_assert(!IsAsciiDigit('a'), "'a' isn't an ASCII digit"); static_assert(!IsAsciiDigit('b'), "'b' isn't an ASCII digit"); static_assert(!IsAsciiDigit('m'), "'m' isn't an ASCII digit"); static_assert(!IsAsciiDigit('y'), "'y' isn't an ASCII digit"); static_assert(!IsAsciiDigit('z'), "'z' isn't an ASCII digit"); static_assert(!IsAsciiDigit('{'), "'{' isn't an ASCII digit"); // char16_t static_assert(!IsAsciiDigit(u'/'), "u'/' isn't an ASCII digit"); static_assert(u'/' == 0x2F, "u'/' has value 0x2F"); static_assert(u'0' == 0x30, "u'0' has value 0x30"); static_assert(IsAsciiDigit(u'0'), "u'0' is an ASCII digit"); static_assert(IsAsciiDigit(u'1'), "u'1' is an ASCII digit"); static_assert(IsAsciiDigit(u'5'), "u'5' is an ASCII digit"); static_assert(IsAsciiDigit(u'8'), "u'8' is an ASCII digit"); static_assert(IsAsciiDigit(u'9'), "u'9' is an ASCII digit"); static_assert(u'9' == 0x39, "u'9' has value 0x39"); static_assert(u':' == 0x3A, "u':' has value 0x3A"); static_assert(!IsAsciiDigit(u':'), "u':' isn't an ASCII digit"); static_assert(!IsAsciiDigit(u'@'), "u'@' isn't an ASCII digit"); static_assert(!IsAsciiDigit(u'A'), "u'A' isn't an ASCII digit"); static_assert(!IsAsciiDigit(u'B'), "u'B' isn't an ASCII digit"); static_assert(!IsAsciiDigit(u'M'), "u'M' isn't an ASCII digit"); static_assert(!IsAsciiDigit(u'Y'), "u'Y' isn't an ASCII digit"); static_assert(!IsAsciiDigit(u'Z'), "u'Z' isn't an ASCII digit"); static_assert(!IsAsciiDigit(u'['), "u'[' isn't an ASCII digit"); static_assert(!IsAsciiDigit(u'`'), "u'`' isn't an ASCII digit"); static_assert(!IsAsciiDigit(u'a'), "u'a' isn't an ASCII digit"); static_assert(!IsAsciiDigit(u'b'), "u'b' isn't an ASCII digit"); static_assert(!IsAsciiDigit(u'm'), "u'm' isn't an ASCII digit"); static_assert(!IsAsciiDigit(u'y'), "u'y' isn't an ASCII digit"); static_assert(!IsAsciiDigit(u'z'), "u'z' isn't an ASCII digit"); static_assert(!IsAsciiDigit(u'{'), "u'{' isn't an ASCII digit"); // char32_t static_assert(!IsAsciiDigit(U'/'), "U'/' isn't an ASCII digit"); static_assert(U'/' == 0x2F, "U'/' has value 0x2F"); static_assert(U'0' == 0x30, "U'0' has value 0x30"); static_assert(IsAsciiDigit(U'0'), "U'0' is an ASCII digit"); static_assert(IsAsciiDigit(U'1'), "U'1' is an ASCII digit"); static_assert(IsAsciiDigit(U'5'), "U'5' is an ASCII digit"); static_assert(IsAsciiDigit(U'8'), "U'8' is an ASCII digit"); static_assert(IsAsciiDigit(U'9'), "U'9' is an ASCII digit"); static_assert(U'9' == 0x39, "U'9' has value 0x39"); static_assert(U':' == 0x3A, "U':' has value 0x3A"); static_assert(!IsAsciiDigit(U':'), "U':' isn't an ASCII digit"); static_assert(!IsAsciiDigit(U'@'), "U'@' isn't an ASCII digit"); static_assert(!IsAsciiDigit(U'A'), "U'A' isn't an ASCII digit"); static_assert(!IsAsciiDigit(U'B'), "U'B' isn't an ASCII digit"); static_assert(!IsAsciiDigit(U'M'), "U'M' isn't an ASCII digit"); static_assert(!IsAsciiDigit(U'Y'), "U'Y' isn't an ASCII digit"); static_assert(!IsAsciiDigit(U'Z'), "U'Z' isn't an ASCII digit"); static_assert(!IsAsciiDigit(U'['), "U'[' isn't an ASCII digit"); static_assert(!IsAsciiDigit(U'`'), "U'`' isn't an ASCII digit"); static_assert(!IsAsciiDigit(U'a'), "U'a' isn't an ASCII digit"); static_assert(!IsAsciiDigit(U'b'), "U'b' isn't an ASCII digit"); static_assert(!IsAsciiDigit(U'm'), "U'm' isn't an ASCII digit"); static_assert(!IsAsciiDigit(U'y'), "U'y' isn't an ASCII digit"); static_assert(!IsAsciiDigit(U'z'), "U'z' isn't an ASCII digit"); static_assert(!IsAsciiDigit(U'{'), "U'{' isn't an ASCII digit"); } int main() { TestIsAscii(); TestIsAsciiNullTerminated(); TestIsAsciiAlpha(); TestIsAsciiUppercaseAlpha(); TestIsAsciiLowercaseAlpha(); TestIsAsciiAlphanumeric(); TestAsciiAlphanumericToNumber(); TestIsAsciiDigit(); }
47.258216
80
0.63638
gregtatum
47f21e4f6679cab3af02c95b4f10ba36b13abc46
1,280
cpp
C++
src/Example/CubeExample.cpp
slicgun/ray_tracing
913f8a03887c20ca4fbad1fb38395b9f70fe54d4
[ "Apache-2.0" ]
null
null
null
src/Example/CubeExample.cpp
slicgun/ray_tracing
913f8a03887c20ca4fbad1fb38395b9f70fe54d4
[ "Apache-2.0" ]
null
null
null
src/Example/CubeExample.cpp
slicgun/ray_tracing
913f8a03887c20ca4fbad1fb38395b9f70fe54d4
[ "Apache-2.0" ]
null
null
null
#include "CubeExample.h" #include<vector> #include<glm/geometric.hpp> #include"Log.h" std::vector<Material> mat; Vertex v1 = {0, {0, 1, -3}, {0, 0, 1}, {0, 0}}; Vertex v2 = {0, {-1, 1, -3}, {0, 0, 1}, {0, 0}}; Vertex v3 = {0, {0, 0, -3}, {0, 0, 1}, {0, 0}}; CubeExample::CubeExample(Image& img) :Example(img, "res/models/cube/cube.obj", {0, 0, 3}, 1, 3), m_texture("res/textures/test.png"), m_triangle(v1, v2, v3, mat) { m_camera.position = {0, 0, 0}; m_camera.target = {0, 0, -1}; m_camera.lookAt = glm::normalize(m_camera.target - m_camera.position); m_camera.right = glm::normalize(glm::cross({0, 1, 0}, m_camera.lookAt)); m_camera.up = glm::cross(m_camera.lookAt, m_camera.right); } void CubeExample::draw() { for(unsigned y = 0; y < m_image.height; y++) for(unsigned x = 0; x < m_image.width; x++) { glm::ivec2 pixel; Ray r = getRayThroughPixel(pixel.x, pixel.y); float u, v, t; if(m_triangle.intersection(r, t, u, v)) { float depth = r(t).z; int depthBufferIndex = index(pixel.x, pixel.y); glm::vec3 color = {1, 1, 1}; //m_texture.getColor((1 - v - u) * m_triangle[0].uv + u * m_triangle[1].uv + v * m_triangle[2].uv); setPixelColor(x, y, color); } } writeImage("cube"); }
28.444444
133
0.585938
slicgun
47f22170c5228eac4b407b78897ae5c4e93e9d35
3,772
cpp
C++
source/common/lua/performance.cpp
xiaobodu/breeze
e74f0cd680274fd431118104d1fdb45926da6328
[ "Apache-2.0" ]
1
2020-08-13T08:10:15.000Z
2020-08-13T08:10:15.000Z
source/common/lua/performance.cpp
xiaobodu/breeze
e74f0cd680274fd431118104d1fdb45926da6328
[ "Apache-2.0" ]
null
null
null
source/common/lua/performance.cpp
xiaobodu/breeze
e74f0cd680274fd431118104d1fdb45926da6328
[ "Apache-2.0" ]
1
2017-04-30T14:25:25.000Z
2017-04-30T14:25:25.000Z
/* * zsummerX License * ----------- * * zsummerX is licensed under the terms of the MIT license reproduced below. * This means that zsummerX is free software and can be used for both academic * and commercial purposes at absolutely no cost. * * * =============================================================================== * * Copyright (C) 2010-2015 YaweiZhang <yawei.zhang@foxmail.com>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * =============================================================================== * * (end of COPYRIGHT) */ #include "performance.h" static void hook_run_fn(lua_State *L, lua_Debug *ar); static int newindex(lua_State * L) { lua_pushvalue(L, 1); lua_pushvalue(L, 2); lua_pushvalue(L, 3); lua_rawset(L, 4); lua_pop(L, 1); const char * key = luaL_checkstring(L, 2); const char * v = luaL_typename(L, 3); std::stringstream ss; ss << "catch one operation that it's set a global value. key=" << key << ", type(v)=" << v << ", is it correct ?"; if (lua_getglobal(L, "summer") == LUA_TTABLE && lua_getfield(L, -1, "logw") == LUA_TFUNCTION) { lua_pushstring(L, ss.str().c_str()); lua_pcall(L, 1, 0, 0); } else if (lua_getglobal(L, "print") == LUA_TFUNCTION) { lua_pushstring(L, ss.str().c_str()); lua_pcall(L, 1, 0, 0); } lua_pop(L, lua_gettop(L) - 3); return 0; } zsummer::Performence __perf; void luaopen_performence(lua_State * L) { //lua_Hook oldhook = lua_gethook(L); //int oldmask = lua_gethookmask(L); lua_sethook(L, &hook_run_fn, LUA_MASKCALL | LUA_MASKRET, 0); lua_getglobal(L, "_G"); lua_newtable(L); lua_pushcclosure(L, newindex, 0); lua_setfield(L, -2, "__newindex"); lua_setmetatable(L, -2); } void hook_run_fn(lua_State *L, lua_Debug *ar) { // 获取Lua调用信息 lua_getinfo(L, "Snl", ar); std::string key; if (ar->source) { key += ar->source; } key += "_"; if (ar->what) { key += ar->what; } key += "_"; if (ar->namewhat) { key += ar->namewhat; } key += "_"; if (ar->name) { key += ar->name; } if (ar->event == LUA_HOOKCALL) { __perf._stack.push(key, lua_gc(L, LUA_GCCOUNT, 0) * 1024 + lua_gc(L, LUA_GCCOUNTB, 0)); } else if (ar->event == LUA_HOOKRET) { //lua_gc(L, LUA_GCCOLLECT, 0); auto t = __perf._stack.pop(key, lua_gc(L, LUA_GCCOUNT, 0) * 1024 + lua_gc(L, LUA_GCCOUNTB, 0)); if (std::get<0>(t)) { __perf.call(key, std::get<1>(t), std::get<2>(t)); } if (__perf.expire(50000.0)) { __perf.dump(100); } } }
30.176
118
0.595175
xiaobodu
47f7e140f4798a78082e3cbee4103984473522bd
1,021
cpp
C++
src/atomic.cpp
sriramch/thirdparty-libcxx
a97a7380c76346c22bb67b93695bed19592afad2
[ "Apache-2.0" ]
2
2020-09-03T03:36:36.000Z
2020-09-03T08:09:10.000Z
src/atomic.cpp
sriramch/thirdparty-libcxx
a97a7380c76346c22bb67b93695bed19592afad2
[ "Apache-2.0" ]
1
2019-12-27T02:42:26.000Z
2019-12-27T02:42:26.000Z
src/atomic.cpp
sriramch/thirdparty-libcxx
a97a7380c76346c22bb67b93695bed19592afad2
[ "Apache-2.0" ]
3
2019-09-25T21:43:35.000Z
2020-03-27T19:12:47.000Z
//===------------------------- atomic.cpp ---------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifdef _LIBCPP_SIMT #include <details/__config> #else #include "__config" #endif #ifndef _LIBCPP_HAS_NO_THREADS #ifdef _LIBCPP_SIMT #include <simt/atomic> #else #include "atomic" #endif _LIBCPP_BEGIN_NAMESPACE_STD #if !defined(_LIBCPP_HAS_NO_THREAD_CONTENTION_TABLE) __libcpp_contention_t __libcpp_contention_state_[ 256 /* < there's no magic in this number */ ]; _LIBCPP_FUNC_VIS __libcpp_contention_t * __libcpp_contention_state(void const volatile * p) _NOEXCEPT { return __libcpp_contention_state_ + ((std::uintptr_t)p & 255); } #endif //_LIBCPP_HAS_NO_THREAD_CONTENTION_TABLE _LIBCPP_END_NAMESPACE_STD #endif //_LIBCPP_HAS_NO_THREADS
26.868421
96
0.676787
sriramch
47fbba07d41575b11562d65477c18a9b23314a7b
173
cpp
C++
assec-renderer/src/renderer/shader.cpp
TeamVistic/assec-renderer
5c6fc9a46fc3f6302471a22bfd2bdf2942b794db
[ "Apache-2.0" ]
null
null
null
assec-renderer/src/renderer/shader.cpp
TeamVistic/assec-renderer
5c6fc9a46fc3f6302471a22bfd2bdf2942b794db
[ "Apache-2.0" ]
null
null
null
assec-renderer/src/renderer/shader.cpp
TeamVistic/assec-renderer
5c6fc9a46fc3f6302471a22bfd2bdf2942b794db
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "shader.h" namespace assec::renderer { shader::shader(const std::wstring& source, SHADER_TYPE type) : m_source(source), m_shader_type(type) {} }
21.625
104
0.728324
TeamVistic
9a0df3b530d67be768a82f6b0b440593cccdff56
11,699
hpp
C++
src/vanillaswap.hpp
quantlibnode/quantlibnode
b50348131af77a2b6c295f44ef3245daf05c4afc
[ "MIT" ]
27
2016-11-19T16:51:21.000Z
2021-09-08T16:44:15.000Z
src/vanillaswap.hpp
quantlibnode/quantlibnode
b50348131af77a2b6c295f44ef3245daf05c4afc
[ "MIT" ]
1
2016-12-28T16:38:38.000Z
2017-02-17T05:32:13.000Z
src/vanillaswap.hpp
quantlibnode/quantlibnode
b50348131af77a2b6c295f44ef3245daf05c4afc
[ "MIT" ]
10
2016-12-28T02:31:38.000Z
2021-06-15T09:02:07.000Z
/* Copyright (C) 2016 -2017 Jerry Jin */ #ifndef vanillaswap_h #define vanillaswap_h #include <nan.h> #include <string> #include <queue> #include <utility> #include "../quantlibnode.hpp" #include <oh/objecthandler.hpp> using namespace node; using namespace v8; using namespace std; class VanillaSwapWorker : public Nan::AsyncWorker { public: string mObjectID; string mPayerReceiver; double mNominal; string mFixSchedule; double mFixedRate; string mFixDayCounter; string mFloatingLegSchedule; string mIborIndex; double mSpread; string mFloatingLegDayCounter; string mPaymentConvention; string mReturnValue; string mError; VanillaSwapWorker( Nan::Callback *callback ,string ObjectID ,string PayerReceiver ,double Nominal ,string FixSchedule ,double FixedRate ,string FixDayCounter ,string FloatingLegSchedule ,string IborIndex ,double Spread ,string FloatingLegDayCounter ,string PaymentConvention ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mPayerReceiver(PayerReceiver) ,mNominal(Nominal) ,mFixSchedule(FixSchedule) ,mFixedRate(FixedRate) ,mFixDayCounter(FixDayCounter) ,mFloatingLegSchedule(FloatingLegSchedule) ,mIborIndex(IborIndex) ,mSpread(Spread) ,mFloatingLegDayCounter(FloatingLegDayCounter) ,mPaymentConvention(PaymentConvention) { }; //~VanillaSwapWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class MakeVanillaSwapWorker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mSettlDays; string mSwapTenor; string mIborIndex; double mFixedRate; string mForwardStart; string mFixDayCounter; double mSpread; string mPricingEngineID; string mReturnValue; string mError; MakeVanillaSwapWorker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t SettlDays ,string SwapTenor ,string IborIndex ,double FixedRate ,string ForwardStart ,string FixDayCounter ,double Spread ,string PricingEngineID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mSettlDays(SettlDays) ,mSwapTenor(SwapTenor) ,mIborIndex(IborIndex) ,mFixedRate(FixedRate) ,mForwardStart(ForwardStart) ,mFixDayCounter(FixDayCounter) ,mSpread(Spread) ,mPricingEngineID(PricingEngineID) { }; //~MakeVanillaSwapWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class MakeIMMSwapWorker : public Nan::AsyncWorker { public: string mObjectID; string mSwapTenor; string mIborIndex; double mFixedRate; ObjectHandler::property_t mFirstImmDate; string mFixDayCounter; double mSpread; string mPricingEngineID; string mReturnValue; string mError; MakeIMMSwapWorker( Nan::Callback *callback ,string ObjectID ,string SwapTenor ,string IborIndex ,double FixedRate ,ObjectHandler::property_t FirstImmDate ,string FixDayCounter ,double Spread ,string PricingEngineID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mSwapTenor(SwapTenor) ,mIborIndex(IborIndex) ,mFixedRate(FixedRate) ,mFirstImmDate(FirstImmDate) ,mFixDayCounter(FixDayCounter) ,mSpread(Spread) ,mPricingEngineID(PricingEngineID) { }; //~MakeIMMSwapWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapFromSwapIndexWorker : public Nan::AsyncWorker { public: string mObjectID; string mSwapIndex; ObjectHandler::property_t mFixingDate; string mReturnValue; string mError; VanillaSwapFromSwapIndexWorker( Nan::Callback *callback ,string ObjectID ,string SwapIndex ,ObjectHandler::property_t FixingDate ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mSwapIndex(SwapIndex) ,mFixingDate(FixingDate) { }; //~VanillaSwapFromSwapIndexWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapFromSwapRateHelperWorker : public Nan::AsyncWorker { public: string mObjectID; string mSwapRateHelper; string mReturnValue; string mError; VanillaSwapFromSwapRateHelperWorker( Nan::Callback *callback ,string ObjectID ,string SwapRateHelper ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mSwapRateHelper(SwapRateHelper) { }; //~VanillaSwapFromSwapRateHelperWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapFixedLegBPSWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; VanillaSwapFixedLegBPSWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~VanillaSwapFixedLegBPSWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapFixedLegNPVWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; VanillaSwapFixedLegNPVWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~VanillaSwapFixedLegNPVWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapFairRateWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; VanillaSwapFairRateWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~VanillaSwapFairRateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapFloatingLegBPSWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; VanillaSwapFloatingLegBPSWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~VanillaSwapFloatingLegBPSWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapFloatingLegNPVWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; VanillaSwapFloatingLegNPVWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~VanillaSwapFloatingLegNPVWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapFairSpreadWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; VanillaSwapFairSpreadWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~VanillaSwapFairSpreadWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapTypeWorker : public Nan::AsyncWorker { public: string mObjectID; string mReturnValue; string mError; VanillaSwapTypeWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~VanillaSwapTypeWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapNominalWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; VanillaSwapNominalWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~VanillaSwapNominalWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapFixedRateWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; VanillaSwapFixedRateWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~VanillaSwapFixedRateWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapFixedDayCountWorker : public Nan::AsyncWorker { public: string mObjectID; string mReturnValue; string mError; VanillaSwapFixedDayCountWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~VanillaSwapFixedDayCountWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapSpreadWorker : public Nan::AsyncWorker { public: string mObjectID; double mReturnValue; string mError; VanillaSwapSpreadWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~VanillaSwapSpreadWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapFloatingDayCountWorker : public Nan::AsyncWorker { public: string mObjectID; string mReturnValue; string mError; VanillaSwapFloatingDayCountWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~VanillaSwapFloatingDayCountWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapPaymentConventionWorker : public Nan::AsyncWorker { public: string mObjectID; string mReturnValue; string mError; VanillaSwapPaymentConventionWorker( Nan::Callback *callback ,string ObjectID ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) { }; //~VanillaSwapPaymentConventionWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapFixedLegAnalysisWorker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mAfterDate; std::vector< std::vector<string> > mReturnValue; string mError; VanillaSwapFixedLegAnalysisWorker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t AfterDate ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mAfterDate(AfterDate) { }; //~VanillaSwapFixedLegAnalysisWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; class VanillaSwapFloatingLegAnalysisWorker : public Nan::AsyncWorker { public: string mObjectID; ObjectHandler::property_t mAfterDate; std::vector< std::vector<string> > mReturnValue; string mError; VanillaSwapFloatingLegAnalysisWorker( Nan::Callback *callback ,string ObjectID ,ObjectHandler::property_t AfterDate ): Nan::AsyncWorker(callback) ,mObjectID(ObjectID) ,mAfterDate(AfterDate) { }; //~VanillaSwapFloatingLegAnalysisWorker(); //void Destroy(); void Execute(); void HandleOKCallback(); }; #endif
17.409226
70
0.651081
quantlibnode
9a18a9a0f986855045c83f581bcf07ec3460d0a4
7,376
cpp
C++
server.cpp
AnuragDPawar/Centralized-Multi-User-Concurrent-Bank-Account-Manager
c7a8f0b7a61636855c1207f50f82ab554fe89a5f
[ "MIT" ]
null
null
null
server.cpp
AnuragDPawar/Centralized-Multi-User-Concurrent-Bank-Account-Manager
c7a8f0b7a61636855c1207f50f82ab554fe89a5f
[ "MIT" ]
null
null
null
server.cpp
AnuragDPawar/Centralized-Multi-User-Concurrent-Bank-Account-Manager
c7a8f0b7a61636855c1207f50f82ab554fe89a5f
[ "MIT" ]
null
null
null
#include <arpa/inet.h> #include <libexplain/read.h> #include <netdb.h> #include <pthread.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include <fstream> #include <iomanip> //to format the float value #include <iostream> #include <sstream> //for appending operations #include <string> #define MAX 200 pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; using namespace std; int s_accout_number[MAX]; float s_amount[MAX]; string name[MAX]; char *c_ip; int filectr; void *calculate_interest(void *arg) { while (true) { sleep(60); cout << "\nAdding 10% Interest in every account after every 60 seconds\n"; for (int i = 0; i < filectr; i++) { pthread_mutex_lock(&lock); s_amount[i] = s_amount[i] * 1.1; pthread_mutex_unlock(&lock); } } } void *operations(void *arg) { stringstream amt_stream; stringstream amt_stream1; int *client_socket = (int *)arg; int accout_number; int timestamp; int amount; char transaction_type[1]; char buff[4096]; string msg_to_client; cout << "Client connected" << " " << *client_socket << " " << "Thread ID" << " " << pthread_self() << endl; int n; bzero(buff, 4096); int locked = 0; while (n = read(*client_socket, buff, 4096)) { if (n < 0) { cout << "Error" << endl; break; } c_ip = strtok(buff, " "); if (c_ip) { timestamp = atoi(c_ip); } c_ip = strtok(NULL, " "); if (c_ip) { accout_number = atoi(c_ip); } c_ip = strtok(NULL, " "); if (c_ip) { strcpy(transaction_type, c_ip); } c_ip = strtok(NULL, " "); if (c_ip) { amount = stof(c_ip); } int current_account = -1; for (int i = 0; i < filectr; i++) { if (s_accout_number[i] == accout_number) { current_account = i; break; } } pthread_mutex_lock(&lock); if (current_account != -1) { if (strcmp(transaction_type, "d") == 0) { s_amount[current_account] = s_amount[current_account] + amount; string amt; string msg; amt.clear(); msg.clear(); std::stringstream stream; stream << std::fixed << std::setprecision(2) << s_amount[current_account]; std::string s = stream.str(); amt = s; msg = "Updated balence after deposite: \n"; msg_to_client = msg+amt; write(*client_socket, msg_to_client.c_str(), msg_to_client.size() + 1); } else if (strcmp(transaction_type, "w") == 0) { if ((s_amount[current_account] - amount) < 0) { msg_to_client = "Insufficient balence\n"; write(*client_socket, msg_to_client.c_str(), msg_to_client.size() + 1); } else { s_amount[current_account] = s_amount[current_account] - amount; string amt; string msg; amt.clear(); msg.clear(); std::stringstream stream; stream << std::fixed << std::setprecision(2) << s_amount[current_account]; std::string s = stream.str(); amt = s; msg = "Updated balence after withdrawal: \n"; msg_to_client = msg+amt; write(*client_socket, msg_to_client.c_str(), msg_to_client.size() + 1); } } else { msg_to_client = "Invalid transaction type\n"; write(*client_socket, msg_to_client.c_str(), msg_to_client.size() + 1); } } else { msg_to_client = "Account number doesn't exist\n"; write(*client_socket, msg_to_client.c_str(), msg_to_client.size() + 1); } pthread_mutex_unlock(&lock); } } int main() { //For socket part I have referred below video //https://www.youtube.com/watch?v=cNdlrbZSkyQ pthread_t newthread[200]; //Reading the file fstream accounts; accounts.open("./accounts"); if (accounts.fail()) { cout << "Unable to read the file\n" << endl; exit(1); } string line; filectr = 0; while (getline(accounts, line)) { filectr++; } accounts.close(); accounts.open("./accounts"); for (size_t i = 0; i < filectr; i++) { accounts >> s_accout_number[i]; accounts >> name[i]; accounts >> s_amount[i]; } accounts.close(); //Create a server socket int listening = 0; listening = socket(AF_INET, SOCK_STREAM, 0); if (listening == -1) { cerr << "socket not created\n"; } else { cout << "Socket created with FD: " << listening << "\n"; } int reuse_address = 1; //Below code is referred from: https://pubs.opengroup.org/onlinepubs/000095399/functions/setsockopt.html //To reuse the address /*if(setsockopt(listening, SOL_SOCKET, SO_REUSEADDR, &reuse_address, sizeof(reuse_address)) != 0){ cout<<"Failed to reuse the address"<<endl; }*/ //To reuse the port if (setsockopt(listening, SOL_SOCKET, SO_REUSEPORT, &reuse_address, sizeof(reuse_address)) != 0) { cout << "Failed to reuse the port" << endl; } //Bind socket on ip & port sockaddr_in hint; hint.sin_family = AF_INET; hint.sin_port = htons(54004); inet_pton(AF_INET, "127.0.0.1", &hint.sin_addr); if (bind(listening, (sockaddr *)&hint, sizeof(hint)) == -1) { cerr << "Binding failed\n"; } //Make the socket listen if (listen(listening, 4) == -1) { cerr << "Listening failed\n"; } //accpet the connection sockaddr_in client; socklen_t clientsize = sizeof(client); char host[NI_MAXHOST]; char svc[NI_MAXSERV]; int clientsocket[200]; for (int j =0; j < 200; j++) { clientsocket[j] = 0; } pthread_t interest; int i = 0; pthread_create(&interest, NULL, calculate_interest, NULL); while (true) { while (clientsocket[i] = accept(listening, (struct sockaddr *)&client, (socklen_t *)&clientsize)) { if (clientsocket[i] == -1) { cerr << "Unable to connect with client\n"; continue; } else { pthread_create(&newthread[i], NULL, operations, &clientsocket[i]); i++; } } cout << "closing " << clientsocket << endl; close(clientsocket[i]); close(listening); } return 0; }
30.229508
119
0.50583
AnuragDPawar
9a1a2b02e904868e53e4ad156e1936048ba7c46c
1,050
cpp
C++
libs/camera/src/camera/coordinate_system/identity.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/camera/src/camera/coordinate_system/identity.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/camera/src/camera/coordinate_system/identity.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <sge/camera/coordinate_system/forward.hpp> #include <sge/camera/coordinate_system/identity.hpp> #include <sge/camera/coordinate_system/object.hpp> #include <sge/camera/coordinate_system/position.hpp> #include <sge/camera/coordinate_system/right.hpp> #include <sge/camera/coordinate_system/up.hpp> #include <sge/renderer/vector3.hpp> sge::camera::coordinate_system::object sge::camera::coordinate_system::identity() { return sge::camera::coordinate_system::object( sge::camera::coordinate_system::right(sge::renderer::vector3(1.0F, 0.0F, 0.0F)), sge::camera::coordinate_system::up(sge::renderer::vector3(0.0F, 1.0F, 0.0F)), sge::camera::coordinate_system::forward(sge::renderer::vector3(0.0F, 0.0F, 1.0F)), sge::camera::coordinate_system::position(sge::renderer::vector3(0.0F, 0.0F, 0.0F))); }
47.727273
90
0.730476
cpreh
9a2386687d9ee5240b21cf272e063af465e06284
1,097
cpp
C++
ConsoleGameEngine/KeyEvents.cpp
sirjavlux/ConsoleGameEngine
04ece4053d7ad4566aef356fdb6e76233e8dd714
[ "MIT" ]
3
2021-01-03T12:44:08.000Z
2021-01-08T14:02:50.000Z
ConsoleGameEngine/KeyEvents.cpp
sirjavlux/ConsoleGameEngine
04ece4053d7ad4566aef356fdb6e76233e8dd714
[ "MIT" ]
null
null
null
ConsoleGameEngine/KeyEvents.cpp
sirjavlux/ConsoleGameEngine
04ece4053d7ad4566aef356fdb6e76233e8dd714
[ "MIT" ]
null
null
null
#include <iostream> #include "SEngine.h" using namespace std; void keyAUpdateEvent(KeyState state, SEngine* engine) { if (state == KeyState::down) { if (engine->hasCameraObjectAttatched()) { GameObject* obj = engine->getCameraFollowObject(); Vector2D vel(-1, 0); obj->addForce(vel); } } } void keyWUpdateEvent(KeyState state, SEngine* engine) { if (state == KeyState::down) { if (engine->hasCameraObjectAttatched()) { GameObject* obj = engine->getCameraFollowObject(); Vector2D vel(0, 1); obj->addForce(vel); } } } void keySUpdateEvent(KeyState state, SEngine* engine) { if (state == KeyState::down) { if (engine->hasCameraObjectAttatched()) { GameObject* obj = engine->getCameraFollowObject(); Vector2D vel(0, -1); obj->addForce(vel); } } } void keyDUpdateEvent(KeyState state, SEngine* engine) { if (state == KeyState::down) { if (engine->hasCameraObjectAttatched()) { GameObject* obj = engine->getCameraFollowObject(); Vector2D vel(1, 0); obj->addForce(vel); } } } void keySPACEUpdateEvent(KeyState state, SEngine* engine) { }
22.387755
59
0.68186
sirjavlux
9a25fd85c68799a05aab142cdb513e6773fda2da
10,852
hpp
C++
src/compiler/lib/Solution.hpp
gperrotta/yask
a35aa5a6f52bb5a11c182045c469a55a84fa9b36
[ "MIT" ]
null
null
null
src/compiler/lib/Solution.hpp
gperrotta/yask
a35aa5a6f52bb5a11c182045c469a55a84fa9b36
[ "MIT" ]
null
null
null
src/compiler/lib/Solution.hpp
gperrotta/yask
a35aa5a6f52bb5a11c182045c469a55a84fa9b36
[ "MIT" ]
null
null
null
/***************************************************************************** YASK: Yet Another Stencil Kit Copyright (c) 2014-2019, Intel Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *****************************************************************************/ // Base class for defining stencil equations. #pragma once // Generation code. #include "ExprUtils.hpp" #include "Settings.hpp" #include "Eqs.hpp" using namespace std; namespace yask { class PrinterBase; // A base class for whole stencil solutions. This is used by solutions // defined in C++ that are inherited from StencilBase as well as those // defined via the stencil-compiler API. class StencilSolution : public virtual yc_solution { protected: // Simple name for the stencil soln. Must be a legal C++ var name. string _name; // Longer descriptive string. string _long_name; // Debug output. yask_output_ptr _debug_output; ostream* _dos = &std::cout; // just a handy pointer to an ostream. // All vars accessible by the kernel. Vars _vars; // All equations defined in this solution. Eqs _eqs; // Settings for the solution. CompilerSettings _settings; // Code extensions. vector<string> _kernel_code; vector<output_hook_t> _output_hooks; private: // Intermediate data needed to format output. Dimensions _dims; // various dimensions. PrinterBase* _printer = 0; EqBundles* _eqBundles = 0; // eq-bundles for scalar and vector. EqBundlePacks* _eqBundlePacks = 0; // packs of bundles w/o inter-dependencies. EqBundles* _clusterEqBundles = 0; // eq-bundles for scalar and vector. // Create the intermediate data. void analyze_solution(int vlen, bool is_folding_efficient); // Free allocated objs. void _free(bool free_printer); public: StencilSolution(const string& name) : _name(name) { yask_output_factory ofac; auto so = ofac.new_stdout_output(); set_debug_output(so); } virtual ~StencilSolution() { _free(true); } // Identification. virtual const string& getName() const { return _name; } virtual const string& getLongName() const { return _long_name.length() ? _long_name : _name; } // Simple accessors. virtual Vars& getVars() { return _vars; } virtual Eqs& getEqs() { return _eqs; } virtual CompilerSettings& getSettings() { return _settings; } virtual void setSettings(const CompilerSettings& settings) { _settings = settings; } virtual const Dimensions& getDims() { return _dims; } virtual const vector<string>& getKernelCode() { return _kernel_code; } // Get the messsage output stream. virtual std::ostream& get_ostr() const { assert(_dos); return *_dos; } // Make a new var. virtual yc_var_ptr newVar(const std::string& name, bool isScratch, const std::vector<yc_index_node_ptr>& dims); // stencil_solution APIs. // See yask_stencil_api.hpp for documentation. virtual void set_debug_output(yask_output_ptr debug) override { _debug_output = debug; // to share ownership of referent. _dos = &_debug_output->get_ostream(); } virtual yask_output_ptr get_debug_output() const { return _debug_output; } virtual void set_name(std::string name) override { _name = name; } virtual void set_description(std::string str) override { _long_name = str; } virtual std::string get_name() const override { return _name; } virtual std::string get_description() const override { return getLongName(); } virtual yc_var_ptr new_var(const std::string& name, const std::vector<yc_index_node_ptr>& dims) override { return newVar(name, false, dims); } virtual yc_var_ptr new_var(const std::string& name, const std::initializer_list<yc_index_node_ptr>& dims) override { std::vector<yc_index_node_ptr> dim_vec(dims); return newVar(name, false, dim_vec); } virtual yc_var_ptr new_scratch_var(const std::string& name, const std::vector<yc_index_node_ptr>& dims) override { return newVar(name, true, dims); } virtual yc_var_ptr new_scratch_var(const std::string& name, const std::initializer_list<yc_index_node_ptr>& dims) override { std::vector<yc_index_node_ptr> dim_vec(dims); return newVar(name, true, dim_vec); } virtual int get_num_vars() const override { return int(_vars.size()); } virtual yc_var_ptr get_var(const std::string& name) override { for (int i = 0; i < get_num_vars(); i++) if (_vars.at(i)->getName() == name) return _vars.at(i); return nullptr; } virtual std::vector<yc_var_ptr> get_vars() override { std::vector<yc_var_ptr> gv; for (int i = 0; i < get_num_vars(); i++) gv.push_back(_vars.at(i)); return gv; } virtual int get_num_equations() const override { return _eqs.getNum(); } virtual std::vector<yc_equation_node_ptr> get_equations() override { std::vector<yc_equation_node_ptr> ev; for (int i = 0; i < get_num_equations(); i++) ev.push_back(_eqs.getAll().at(i)); return ev; } virtual void call_after_new_solution(const string& code) override { _kernel_code.push_back(code); } virtual int get_prefetch_dist(int level) override ; virtual void set_prefetch_dist(int level, int distance) override; virtual void add_flow_dependency(yc_equation_node_ptr from, yc_equation_node_ptr to) override { auto fp = dynamic_pointer_cast<EqualsExpr>(from); assert(fp); auto tp = dynamic_pointer_cast<EqualsExpr>(to); assert(tp); _eqs.getDeps().set_imm_dep_on(fp, tp); } virtual void clear_dependencies() override { _eqs.getDeps().clear_deps(); } virtual void set_fold_len(const yc_index_node_ptr, int len) override; virtual bool is_folding_set() override { return _settings._foldOptions.size() > 0; } virtual void clear_folding() override { _settings._foldOptions.clear(); } virtual void set_cluster_mult(const yc_index_node_ptr, int mult) override; virtual bool is_clustering_set() override { return _settings._clusterOptions.size() > 0; } virtual void clear_clustering() override { _settings._clusterOptions.clear(); } virtual bool is_target_set() override { return _settings._target.length() > 0; } virtual std::string get_target() override { if (!is_target_set()) THROW_YASK_EXCEPTION("Error: call to get_target() before set_target()"); return _settings._target; } virtual void set_target(const std::string& format) override; virtual void set_element_bytes(int nbytes) override { _settings._elem_bytes = nbytes; } virtual int get_element_bytes() const override { return _settings._elem_bytes; } virtual bool is_dependency_checker_enabled() const override { return _settings._findDeps; } virtual void set_dependency_checker_enabled(bool enable) override { _settings._findDeps = enable; } virtual void output_solution(yask_output_ptr output) override; virtual void call_before_output(output_hook_t hook_fn) override { _output_hooks.push_back(hook_fn); } virtual void set_domain_dims(const std::vector<yc_index_node_ptr>& dims) override { _settings._domainDims.clear(); for (auto& d : dims) { auto dp = dynamic_pointer_cast<IndexExpr>(d); assert(dp); auto& dname = d->get_name(); if (dp->getType() != DOMAIN_INDEX) THROW_YASK_EXCEPTION("Error: set_domain_dims() called with non-domain index '" + dname + "'"); _settings._domainDims.push_back(dname); } } virtual void set_domain_dims(const std::initializer_list<yc_index_node_ptr>& dims) override { vector<yc_index_node_ptr> vdims(dims); set_domain_dims(vdims); } virtual void set_step_dim(const yc_index_node_ptr dim) override { auto dp = dynamic_pointer_cast<IndexExpr>(dim); assert(dp); auto& dname = dim->get_name(); if (dp->getType() != STEP_INDEX) THROW_YASK_EXCEPTION("Error: set_step_dim() called with non-step index '" + dname + "'"); _settings._stepDim = dname; } }; } // namespace yask.
38.34629
109
0.588555
gperrotta
9a263a6528831a76724fa8d442bd37b186de73c3
15,769
cpp
C++
CurrencyRecognition/src/ImageAnalysis/ImageDetector.cpp
vogt31337/Currency-Recognition
05198cb002d854d650479d97d6b4e7538f670965
[ "MIT" ]
42
2015-08-20T06:57:50.000Z
2021-04-30T17:52:27.000Z
CurrencyRecognition/src/ImageAnalysis/ImageDetector.cpp
vogt31337/Currency-Recognition
05198cb002d854d650479d97d6b4e7538f670965
[ "MIT" ]
3
2016-11-17T14:55:43.000Z
2019-05-20T21:01:19.000Z
CurrencyRecognition/src/ImageAnalysis/ImageDetector.cpp
vogt31337/Currency-Recognition
05198cb002d854d650479d97d6b4e7538f670965
[ "MIT" ]
27
2016-01-29T05:41:26.000Z
2020-11-09T12:58:42.000Z
#include "ImageDetector.h" // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <ImageDetector> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ImageDetector::ImageDetector(Ptr<FeatureDetector> featureDetector, Ptr<DescriptorExtractor> descriptorExtractor, Ptr<DescriptorMatcher> descriptorMatcher, Ptr<ImagePreprocessor> imagePreprocessor, const string& configurationTags, const string& selectorTags, const vector<string>& referenceImagesDirectories, bool useInliersGlobalMatch, const string& referenceImagesListPath, const string& testImagesListPath) : _featureDetector(featureDetector), _descriptorExtractor(descriptorExtractor), _descriptorMatcher(descriptorMatcher), _imagePreprocessor(imagePreprocessor), _configurationTags(configurationTags), _selectorTags(selectorTags), _referenceImagesDirectories(referenceImagesDirectories), _referenceImagesListPath(referenceImagesListPath), _testImagesListPath(testImagesListPath), _contourAspectRatioRange(-1, -1), _contourCircularityRange(-1, -1) { setupTargetDB(referenceImagesListPath, useInliersGlobalMatch); setupTargetsShapesRanges(); } ImageDetector::~ImageDetector() {} bool ImageDetector::setupTargetDB(const string& referenceImagesListPath, bool useInliersGlobalMatch) { _targetDetectors.clear(); ifstream imgsList(referenceImagesListPath); if (imgsList.is_open()) { string configurationLine; vector<string> configurations; while (getline(imgsList, configurationLine)) { configurations.push_back(configurationLine); } int numberOfFiles = configurations.size(); cout << " -> Initializing recognition database with " << numberOfFiles << " reference images and with " << _referenceImagesDirectories.size() << " levels of detail..." << endl; PerformanceTimer performanceTimer; performanceTimer.start(); //#pragma omp parallel for schedule(dynamic) for (int configIndex = 0; configIndex < numberOfFiles; ++configIndex) { string filename; size_t targetTag; string separator; Scalar color; stringstream ss(configurations[configIndex]); ss >> filename >> separator >> targetTag >> separator >> color[2] >> color[1] >> color[0]; TargetDetector targetDetector(_featureDetector, _descriptorExtractor, _descriptorMatcher, targetTag, color, useInliersGlobalMatch); for (size_t i = 0; i < _referenceImagesDirectories.size(); ++i) { string referenceImagesDirectory = _referenceImagesDirectories[i]; Mat targetImage; stringstream referenceImgePath; referenceImgePath << REFERENCE_IMGAGES_DIRECTORY << referenceImagesDirectory << "/" << filename; cout << " => Adding reference image " << referenceImgePath.str() << endl; if (_imagePreprocessor->loadAndPreprocessImage(referenceImgePath.str(), targetImage, CV_LOAD_IMAGE_GRAYSCALE, false)) { string filenameWithoutExtension = ImageUtils::getFilenameWithoutExtension(filename); stringstream maskFilename; maskFilename << REFERENCE_IMGAGES_DIRECTORY << referenceImagesDirectory << "/" << filenameWithoutExtension << MASK_TOKEN << MASK_EXTENSION; Mat targetROIs; if (ImageUtils::loadBinaryMask(maskFilename.str(), targetROIs)) { targetDetector.setupTargetRecognition(targetImage, targetROIs); vector<KeyPoint>& targetKeypoints = targetDetector.getTargetKeypoints(); stringstream imageKeypointsFilename; imageKeypointsFilename << REFERENCE_IMGAGES_ANALYSIS_DIRECTORY << filenameWithoutExtension << "_" << referenceImagesDirectory << _selectorTags << IMAGE_OUTPUT_EXTENSION; if (targetKeypoints.empty()) { imwrite(imageKeypointsFilename.str(), targetImage); } else { Mat imageKeypoints; cv::drawKeypoints(targetImage, targetKeypoints, imageKeypoints, TARGET_KEYPOINT_COLOR); imwrite(imageKeypointsFilename.str(), imageKeypoints); } } } } //#pragma omp critical _targetDetectors.push_back(targetDetector); } cout << " -> Finished initialization of targets database in " << performanceTimer.getElapsedTimeFormated() << "\n" << endl; return !_targetDetectors.empty(); } else { return false; } } void ImageDetector::setupTargetsShapesRanges(const string& maskPath) { Mat shapeROIs; if (ImageUtils::loadBinaryMask(maskPath, shapeROIs)) { vector< vector<Point> > contours; vector<Vec4i> hierarchy; findContours(shapeROIs, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0)); int contoursSize = (int)contours.size(); #pragma omp parallel for for (int i = 0; i < contoursSize; ++i) { double contourAspectRatio = ImageUtils::computeContourAspectRatio(contours[i]); double contourCircularity = ImageUtils::computeContourCircularity(contours[i]); #pragma omp critical if (_contourAspectRatioRange[0] == -1 || contourAspectRatio < _contourAspectRatioRange[0]) { _contourAspectRatioRange[0] = contourAspectRatio; } #pragma omp critical if (_contourAspectRatioRange[1] == -1 || contourAspectRatio > _contourAspectRatioRange[1]) { _contourAspectRatioRange[1] = contourAspectRatio; } #pragma omp critical if (_contourCircularityRange[0] == -1 || contourCircularity < _contourCircularityRange[0]) { _contourCircularityRange[0] = contourCircularity; } #pragma omp critical if (_contourCircularityRange[1] == -1 || contourCircularity > _contourCircularityRange[1]) { _contourCircularityRange[1] = contourCircularity; } } } } Ptr< vector< Ptr<DetectorResult> > > ImageDetector::detectTargets(Mat& image, float minimumMatchAllowed, float minimumTargetAreaPercentage, float maxDistanceRatio, float reprojectionThresholdPercentage, double confidence, int maxIters, size_t minimumNumberInliers) { Ptr< vector< Ptr<DetectorResult> > > detectorResults(new vector< Ptr<DetectorResult> >()); vector<KeyPoint> keypointsQueryImage; _featureDetector->detect(image, keypointsQueryImage); if (keypointsQueryImage.size() < 4) { return detectorResults; } Mat descriptorsQueryImage; _descriptorExtractor->compute(image, keypointsQueryImage, descriptorsQueryImage); cv::drawKeypoints(image, keypointsQueryImage, image, NONTARGET_KEYPOINT_COLOR); float bestMatch = 0; Ptr<DetectorResult> bestDetectorResult; int targetDetectorsSize = _targetDetectors.size(); bool validDetection = true; float reprojectionThreshold = image.cols * reprojectionThresholdPercentage; //float reprojectionThreshold = 3.0; do { bestMatch = 0; #pragma omp parallel for schedule(dynamic) for (int i = 0; i < targetDetectorsSize; ++i) { _targetDetectors[i].updateCurrentLODIndex(image); Ptr<DetectorResult> detectorResult = _targetDetectors[i].analyzeImage(keypointsQueryImage, descriptorsQueryImage, maxDistanceRatio, reprojectionThreshold, confidence, maxIters, minimumNumberInliers); if (detectorResult->getBestROIMatch() > minimumMatchAllowed) { float contourArea = (float)cv::contourArea(detectorResult->getTargetContour()); float imageArea = (float)(image.cols * image.rows); float contourAreaPercentage = contourArea / imageArea; if (contourAreaPercentage > minimumTargetAreaPercentage) { double contourAspectRatio = ImageUtils::computeContourAspectRatio(detectorResult->getTargetContour()); if (contourAspectRatio > _contourAspectRatioRange[0] && contourAspectRatio < _contourAspectRatioRange[1]) { double contourCircularity = ImageUtils::computeContourCircularity(detectorResult->getTargetContour()); if (contourCircularity > _contourCircularityRange[0] && contourCircularity < _contourCircularityRange[1]) { if (cv::isContourConvex(detectorResult->getTargetContour())) { #pragma omp critical { if (detectorResult->getBestROIMatch() > bestMatch) { bestMatch = detectorResult->getBestROIMatch(); bestDetectorResult = detectorResult; } } } } } } } } validDetection = bestMatch > minimumMatchAllowed && bestDetectorResult->getInliers().size() > minimumNumberInliers; if (bestDetectorResult.obj != NULL && validDetection) { detectorResults->push_back(bestDetectorResult); // remove inliers of best match to detect more occurrences of targets ImageUtils::removeInliersFromKeypointsAndDescriptors(bestDetectorResult->getInliers(), keypointsQueryImage, descriptorsQueryImage); } } while (validDetection); return detectorResults; } vector<size_t> ImageDetector::detectTargetsAndOutputResults(Mat& image, const string& imageFilename, bool useHighGUI) { Mat imageBackup = image.clone(); Ptr< vector< Ptr<DetectorResult> > > detectorResultsOut = detectTargets(image); vector<size_t> results; stringstream imageInliersOutputFilename; imageInliersOutputFilename << TEST_OUTPUT_DIRECTORY << imageFilename << FILENAME_SEPARATOR << _configurationTags << FILENAME_SEPARATOR << INLIERS_MATCHES << FILENAME_SEPARATOR; for (size_t i = 0; i < detectorResultsOut->size(); ++i) { Ptr<DetectorResult> detectorResult = (*detectorResultsOut)[i]; results.push_back(detectorResult->getTargetValue()); cv::drawKeypoints(image, detectorResult->getInliersKeypoints(), image, TARGET_KEYPOINT_COLOR); stringstream ss; ss << detectorResult->getTargetValue(); Mat imageMatchesSingle = imageBackup.clone(); Mat matchesInliers = detectorResult->getInliersMatches(imageMatchesSingle); try { Rect boundingBox = cv::boundingRect(detectorResult->getTargetContour()); ImageUtils::correctBoundingBox(boundingBox, image.cols, image.rows); GUIUtils::drawLabelInCenterOfROI(ss.str(), image, boundingBox); GUIUtils::drawLabelInCenterOfROI(ss.str(), matchesInliers, boundingBox); ImageUtils::drawContour(image, detectorResult->getTargetContour(), detectorResult->getContourColor()); ImageUtils::drawContour(matchesInliers, detectorResult->getTargetContour(), detectorResult->getContourColor()); } catch (...) { std::cerr << "!!! Drawing outside image !!!" << endl; } if (useHighGUI) { stringstream windowName; windowName << "Target inliers matches (window " << i << ")"; cv::namedWindow(windowName.str(), CV_WINDOW_KEEPRATIO); cv::imshow(windowName.str(), matchesInliers); cv::waitKey(10); } stringstream imageOutputFilenameFull; imageOutputFilenameFull << imageInliersOutputFilename.str() << i << IMAGE_OUTPUT_EXTENSION; imwrite(imageOutputFilenameFull.str(), matchesInliers); } sort(results.begin(), results.end()); cout << " -> Detected " << results.size() << (results.size() != 1 ? " targets" : " target"); size_t globalResult = 0; stringstream resultsSS; if (!results.empty()) { resultsSS << " ("; for (size_t i = 0; i < results.size(); ++i) { size_t resultValue = results[i]; resultsSS << " " << resultValue; globalResult += resultValue; } resultsSS << " )"; cout << resultsSS.str(); } cout << endl; stringstream globalResultSS; globalResultSS << "Global result: " << globalResult << resultsSS.str(); Rect globalResultBoundingBox(0, 0, image.cols, image.rows); GUIUtils::drawImageLabel(globalResultSS.str(), image, globalResultBoundingBox); stringstream imageOutputFilename; imageOutputFilename << TEST_OUTPUT_DIRECTORY << imageFilename << FILENAME_SEPARATOR << _configurationTags << IMAGE_OUTPUT_EXTENSION; imwrite(imageOutputFilename.str(), image); return results; } DetectorEvaluationResult ImageDetector::evaluateDetector(const string& testImgsList, bool saveResults) { double globalPrecision = 0; double globalRecall = 0; double globalAccuracy = 0; size_t numberTestImages = 0; stringstream resultsFilename; resultsFilename << TEST_OUTPUT_DIRECTORY << _configurationTags << FILENAME_SEPARATOR << RESULTS_FILE; ofstream resutlsFile(resultsFilename.str()); ifstream imgsList(testImgsList); if (resutlsFile.is_open() && imgsList.is_open()) { resutlsFile << RESULTS_FILE_HEADER << "\n" << endl; string filename; vector<string> imageFilenames; vector< vector<size_t> > expectedResults; while (getline(imgsList, filename)) { imageFilenames.push_back(filename); vector<size_t> expectedResultFromTest; extractExpectedResultsFromFilename(filename, expectedResultFromTest); expectedResults.push_back(expectedResultFromTest); } int numberOfTests = imageFilenames.size(); cout << " -> Evaluating detector with " << numberOfTests << " test images..." << endl; PerformanceTimer globalPerformanceTimer; globalPerformanceTimer.start(); //#pragma omp parallel for schedule(dynamic) for (int i = 0; i < numberOfTests; ++i) { PerformanceTimer testPerformanceTimer; testPerformanceTimer.start(); string imageFilename = imageFilenames[i]; //string imageFilename = ImageUtils::getFilenameWithoutExtension(""); string imageFilenameWithPath = TEST_IMGAGES_DIRECTORY + imageFilenames[i]; stringstream detectorEvaluationResultSS; DetectorEvaluationResult detectorEvaluationResult; Mat imagePreprocessed; cout << "\n -> Evaluating image " << imageFilename << " (" << (i + 1) << "/" << numberOfTests << ")" << endl; if (_imagePreprocessor->loadAndPreprocessImage(imageFilenameWithPath, imagePreprocessed, CV_LOAD_IMAGE_GRAYSCALE, false)) { vector<size_t> results = detectTargetsAndOutputResults(imagePreprocessed, imageFilename, false); detectorEvaluationResult = DetectorEvaluationResult(results, expectedResults[i]); globalPrecision += detectorEvaluationResult.getPrecision(); globalRecall += detectorEvaluationResult.getRecall(); globalAccuracy += detectorEvaluationResult.getAccuracy(); detectorEvaluationResultSS << PRECISION_TOKEN << ": " << detectorEvaluationResult.getPrecision() << " | " << RECALL_TOKEN << ": " << detectorEvaluationResult.getRecall() << " | " << ACCURACY_TOKEN << ": " << detectorEvaluationResult.getAccuracy(); ++numberTestImages; if (saveResults) { resutlsFile << imageFilename << " -> " << detectorEvaluationResultSS.str() << endl; } } cout << " -> Evaluation of image " << imageFilename << " finished in " << testPerformanceTimer.getElapsedTimeFormated() << endl; cout << " -> " << detectorEvaluationResultSS.str() << endl; } globalPrecision /= (double)numberTestImages; globalRecall /= (double)numberTestImages; globalAccuracy /= (double)numberTestImages; stringstream detectorEvaluationGloablResultSS; detectorEvaluationGloablResultSS << GLOBAL_PRECISION_TOKEN << ": " << globalPrecision << " | " << GLOBAL_RECALL_TOKEN << ": " << globalRecall << " | " << GLOBAL_ACCURACY_TOKEN << ": " << globalAccuracy; resutlsFile << "\n\n" << RESULTS_FILE_FOOTER << endl; resutlsFile << " ==> " << detectorEvaluationGloablResultSS.str() << endl; cout << "\n -> Finished evaluation of detector in " << globalPerformanceTimer.getElapsedTimeFormated() << " || " << detectorEvaluationGloablResultSS.str() << "\n" << endl; } return DetectorEvaluationResult(globalPrecision, globalRecall, globalAccuracy); } void ImageDetector::extractExpectedResultsFromFilename(string filename, vector<size_t>& expectedResultFromTestOut) { for (size_t i = 0; i < filename.size(); ++i) { char letter = filename[i]; if (letter == '-') { filename[i] = ' '; } else if (letter == '.' || letter == '_') { filename = filename.substr(0, i); break; } } stringstream ss(filename); size_t number; while (ss >> number) { expectedResultFromTestOut.push_back(number); } } // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </ImageDetector> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
42.850543
251
0.722684
vogt31337
9a2c88ddbed7605526dca4235c577809eba1b6b2
28,057
cpp
C++
Src/Value.cpp
draede/cx
f3ce4aec9b99095760481b1507e383975b2827e3
[ "MIT" ]
1
2016-08-28T18:29:17.000Z
2016-08-28T18:29:17.000Z
Src/Value.cpp
draede/cx
f3ce4aec9b99095760481b1507e383975b2827e3
[ "MIT" ]
null
null
null
Src/Value.cpp
draede/cx
f3ce4aec9b99095760481b1507e383975b2827e3
[ "MIT" ]
null
null
null
/* * CX - C++ framework for general purpose development * * https://github.com/draede/cx * * Copyright (C) 2014 - 2021 draede - draede [at] outlook [dot] com * * Released under the MIT License. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "CX/precomp.hpp" #include "CX/Value.hpp" #include "CX/IO/MemInputStream.hpp" #include "CX/IO/MemOutputStream.hpp" namespace CX { class VarJSONSAXParserObserver : public Data::JSON::ISAXParserObserver { public: Bool m_bInit; Value *m_pRoot; Value *m_pCurrent; String m_sKey; virtual Bool OnBeginParse() { return True; } virtual Bool OnEndParse() { return True; } virtual Bool OnBeginObject() { if (m_bInit) { if (m_pCurrent->SetAsObject().IsNOK()) { return False; } m_bInit = False; } else { Value *pValue = new (std::nothrow) Value(Value::Type_Object); if (NULL == pValue) { return False; } if (m_pCurrent->IsObject()) { m_pCurrent->AddMember(m_sKey, pValue); m_pCurrent = pValue; } else { m_pCurrent->AddItem(pValue); m_pCurrent = pValue; } } return True; } virtual Bool OnEndObject() { m_pCurrent = &m_pCurrent->GetParent(); return True; } virtual Bool OnBeginArray() { if (m_bInit) { if (m_pCurrent->SetAsArray().IsNOK()) { return False; } m_bInit = False; } else { Value *pValue = new (std::nothrow) Value(Value::Type_Array); if (NULL == pValue) { return False; } if (m_pCurrent->IsObject()) { m_pCurrent->AddMember(m_sKey, pValue); m_pCurrent = pValue; } else { m_pCurrent->AddItem(pValue); m_pCurrent = pValue; } } return True; } virtual Bool OnEndArray() { m_pCurrent = &m_pCurrent->GetParent(); return True; } virtual Bool OnKey(const Char *pBuffer, Size cLen) { m_sKey.assign(pBuffer, cLen); return True; } virtual Bool OnNullValue() { if (m_pCurrent->IsObject()) { (*m_pCurrent)[m_sKey].SetNull(); } else { (*m_pCurrent)[-1].SetNull(); } return True; } virtual Bool OnBoolValue(Bool bBool) { if (m_pCurrent->IsObject()) { (*m_pCurrent)[m_sKey].SetBool(bBool); } else { (*m_pCurrent)[-1].SetBool(bBool); } return True; } virtual Bool OnIntValue(Int64 nInt) { if (m_pCurrent->IsObject()) { (*m_pCurrent)[m_sKey].SetInt(nInt); } else { (*m_pCurrent)[-1].SetInt(nInt); } return True; } virtual Bool OnUIntValue(UInt64 uInt) { if (m_pCurrent->IsObject()) { (*m_pCurrent)[m_sKey].SetUInt(uInt); } else { (*m_pCurrent)[-1].SetUInt(uInt); } return True; } virtual Bool OnRealValue(Double lfReal) { if (m_pCurrent->IsObject()) { (*m_pCurrent)[m_sKey].SetReal(lfReal); } else { (*m_pCurrent)[-1].SetReal(lfReal); } return True; } virtual Bool OnStringValue(const Char *pBuffer, Size cLen) { if (m_pCurrent->IsObject()) { (*m_pCurrent)[m_sKey].SetString(String(pBuffer, cLen)); } else { (*m_pCurrent)[-1].SetString(String(pBuffer, cLen)); } return True; } }; Value Value::INVALID_VALUE(NULL, NULL, NULL); const Double Value::DEFAULT_REAL = 0.0; const String Value::DEFAULT_STRING; Value::Value() { m_nType = Type_Null; m_pParent = NULL; } Value::Value(void *pDummy1, void *pDummy2, void *pDummy3) { CX_UNUSED(pDummy1); CX_UNUSED(pDummy2); CX_UNUSED(pDummy3); m_nType = Type_Invalid; m_pParent = NULL; } Value::Value(Value *pParent) { m_nType = Type_Null; m_pParent = pParent; } Value::Value(Type nType) { m_nType = Type_Null; m_pParent = NULL; switch (nType) { case Type_Bool: SetBool(DEFAULT_BOOL); break; case Type_Int: SetInt(DEFAULT_INT); break; case Type_UInt: SetUInt(DEFAULT_UINT); break; case Type_Real: SetReal(DEFAULT_REAL); break; case Type_String: SetString(DEFAULT_STRING); break; case Type_Object: SetAsObject(); break; case Type_Array: SetAsArray(); break; default: { } } } Value::Value(Bool bValue) { m_nType = Type_Null; m_pParent = NULL; SetBool(bValue); } Value::Value(Int64 nValue) { m_nType = Type_Null; m_pParent = NULL; SetInt(nValue); } Value::Value(UInt64 uValue) { m_nType = Type_Null; m_pParent = NULL; SetUInt(uValue); } Value::Value(Double lfValue) { m_nType = Type_Null; m_pParent = NULL; SetReal(lfValue); } Value::Value(const String &sValue) { m_nType = Type_Null; m_pParent = NULL; SetString(sValue); } Value::Value(const Value &value) { m_nType = Type_Null; Copy(value); } Value::~Value() { if (!IsInvalid()) { FreeMem(); m_nType = Type_Null; m_pParent = NULL; } } void Value::FreeMem() { if (IsInvalid()) { return; } if (Type_String == m_nType) { delete m_psString; } else if (Type_Object == m_nType) { for (Object::iterator iter = m_pObject->begin(); iter != m_pObject->end(); ++iter) { delete iter->second; } delete m_pObject; } else if (Type_Array == m_nType) { for (Array::iterator iter = m_pArray->begin(); iter != m_pArray->end(); ++iter) { delete *iter; } delete m_pArray; } } Value &Value::operator=(const Value &value) { if (IsInvalid()) { return *this; } Copy(value); return *this; } Status Value::Copy(const Value &value) { if (IsInvalid()) { return Status_InvalidCall; } switch (value.m_nType) { case Type_Null: return SetNull(); case Type_Bool: return SetBool(value.GetBool()); case Type_Int: return SetInt(value.GetInt()); case Type_UInt: return SetUInt(value.GetUInt()); case Type_Real: return SetReal(value.GetReal()); case Type_String: return SetString(value.GetString()); case Type_Object: { Status status; if ((status = SetAsObject()).IsNOK()) { return status; } for (Object::iterator iter = value.m_pObject->begin(); iter != value.m_pObject->end(); ++iter) { if ((status = AddMember(iter->first, iter->second)).IsNOK()) { return status; } } return Status(); } break; case Type_Array: { Status status; if ((status = SetAsArray()).IsNOK()) { return status; } for (Array::iterator iter = value.m_pArray->begin(); iter != value.m_pArray->end(); ++iter) { if ((status = AddItem(*iter)).IsNOK()) { return status; } } return Status(); } break; default: { return Status_InvalidArg; } } } Bool Value::HasParent() { return (NULL != m_pParent); } const Value &Value::GetParent() const { if (NULL != m_pParent) { return *m_pParent; } else { return INVALID_VALUE; } } Value &Value::GetParent() { if (NULL != m_pParent) { return *m_pParent; } else { return INVALID_VALUE; } } Value::Type Value::GetType() const { return m_nType; } Bool Value::IsInvalid() const { return (Type_Invalid == GetType()); } Bool Value::IsNull() const { return (Type_Null == GetType()); } Bool Value::IsBool() const { return (Type_Bool == GetType()); } Bool Value::IsInt() const { return (Type_Int == GetType()); } Bool Value::IsUInt() const { return (Type_UInt == GetType()); } Bool Value::IsReal() const { return (Type_Real == GetType()); } Bool Value::IsString() const { return (Type_String == GetType()); } Bool Value::IsObject() const { return (Type_Object == GetType()); } Bool Value::IsArray() const { return (Type_Array == GetType()); } Bool Value::GetNull(Status *pStatus/* = NULL*/) const { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return False; } if (IsNull()) { if (NULL != pStatus) { *pStatus = Status_OK; } return True; } else { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return False; } } Status Value::SetNull() { if (IsInvalid()) { return Status_InvalidCall; } FreeMem(); m_nType = Type_Null; return Status(); } Bool Value::GetBool(Bool bDefault/* = DEFAULT_BOOL*/, Status *pStatus/* = NULL*/) const { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return bDefault; } if (IsBool()) { if (NULL != pStatus) { *pStatus = Status_OK; } return m_bBool; } else { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return bDefault; } } Status Value::SetBool(Bool bValue) { if (IsInvalid()) { return Status_InvalidCall; } FreeMem(); m_nType = Type_Bool; m_bBool = bValue; return Status(); } Int64 Value::GetInt(Int64 nDefault/* = DEFAULT_INT*/, Status *pStatus/* = NULL*/) const { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return nDefault; } if (IsInt()) { if (NULL != pStatus) { *pStatus = Status_OK; } return m_nInt; } else { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return nDefault; } } Status Value::SetInt(Int64 nValue) { if (IsInvalid()) { return Status_InvalidCall; } FreeMem(); m_nType = Type_Int; m_nInt = nValue; return Status(); } UInt64 Value::GetUInt(UInt64 uDefault/* = DEFAULT_UINT*/, Status *pStatus/* = NULL*/) const { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return uDefault; } if (IsUInt()) { if (NULL != pStatus) { *pStatus = Status_OK; } return m_uInt; } else { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return uDefault; } } Status Value::SetUInt(UInt64 uValue) { if (IsInvalid()) { return Status_InvalidCall; } FreeMem(); m_nType = Type_UInt; m_uInt = uValue; return Status(); } Double Value::GetReal(Double lfDefault/* = DEFAULT_DOUBLE*/, Status *pStatus/* = NULL*/) const { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return lfDefault; } if (IsReal()) { if (NULL != pStatus) { *pStatus = Status_OK; } return m_lfReal; } else { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return lfDefault; } } Status Value::SetReal(Double lfValue) { if (IsInvalid()) { return Status_InvalidCall; } FreeMem(); m_nType = Type_Real; m_lfReal = lfValue; return Status(); } const String &Value::GetString(const String &sDefault/* = DEFAULT_STRING*/, Status *pStatus/* = NULL*/) const { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return sDefault; } if (IsString()) { if (NULL != pStatus) { *pStatus = Status_OK; } return *m_psString; } else { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return sDefault; } } Status Value::SetString(const String &sValue) { if (IsInvalid()) { return Status_InvalidCall; } String *psValue; if (NULL == (psValue = new (std::nothrow) String(sValue))) { return Status_MemAllocFailed; } FreeMem(); m_nType = Type_String; m_psString = psValue; return Status(); } Status Value::SetAsArray() { if (IsInvalid()) { return Status_InvalidCall; } Array *pArray; if (NULL == (pArray = new (std::nothrow) Array())) { return Status_MemAllocFailed; } FreeMem(); m_nType = Type_Array; m_pArray = pArray; return Status(); } Status Value::SetAsObject() { if (IsInvalid()) { return Status_InvalidCall; } Object *pObject; if (NULL == (pObject = new (std::nothrow) Object())) { return Status_MemAllocFailed; } FreeMem(); m_nType = Type_Object; m_pObject = pObject; return Status(); } Size Value::GetItemsCount(Status *pStatus/* = NULL*/) const { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return 0; } if (IsArray()) { if (NULL != pStatus) { *pStatus = Status_OK; } return m_pArray->size(); } else { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return 0; } } Value &Value::AddItem(Status *pStatus/* = NULL*/) { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return INVALID_VALUE; } if (!IsArray()) { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return INVALID_VALUE; } Value *pValue; if (NULL == (pValue = new (std::nothrow) Value(this))) { return INVALID_VALUE; } m_pArray->push_back(pValue); return *pValue; } Status Value::AddItem(Value *pValue) { if (IsInvalid()) { return Status_InvalidCall; } if (!IsArray()) { return Status_InvalidArg; } if (NULL != pValue->m_pParent) { return Status_InvalidArg; } pValue->m_pParent = this; m_pArray->push_back(pValue); return Status(); } Value &Value::InsertItem(int cIndex, Status *pStatus/* = NULL*/) { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return INVALID_VALUE; } if (!IsArray()) { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return INVALID_VALUE; } if (0 > cIndex) { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return INVALID_VALUE; } if (cIndex >= (int)m_pArray->size()) { return AddItem(pStatus); } Value *pValue; if (NULL == (pValue = new (std::nothrow) Value(this))) { return INVALID_VALUE; } Array::iterator iter = m_pArray->begin() + cIndex; m_pArray->insert(iter, pValue); return *pValue; } Status Value::InsertItem(int cIndex, Value *pValue) { if (IsInvalid()) { return Status_InvalidCall; } if (!IsArray()) { return Status_InvalidArg; } if (NULL == pValue->m_pParent) { return Status_InvalidArg; } if (0 > cIndex) { return Status_InvalidArg; } if (cIndex >= (int)m_pArray->size()) { return AddItem(pValue); } pValue->m_pParent = this; Array::iterator iter = m_pArray->begin() + cIndex; m_pArray->insert(iter, pValue); return Status(); } Status Value::RemoveItem(int cIndex) { if (IsInvalid()) { return Status_InvalidCall; } if (!IsArray()) { return Status_InvalidArg; } if (cIndex >= (int)m_pArray->size()) { return Status_InvalidArg; } Array::iterator iter = m_pArray->begin() + cIndex; delete *iter; m_pArray->erase(iter); return Status(); } Status Value::RemoveAllItems() { if (IsInvalid()) { return Status_InvalidCall; } if (!IsArray()) { return Status_InvalidArg; } for (Array::iterator iter = m_pArray->begin(); iter != m_pArray->end(); ++iter) { delete *iter; } m_pArray->clear(); return Status(); } const Value &Value::GetItem(int cIndex, Status *pStatus/* = NULL*/) const { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return INVALID_VALUE; } if (!IsArray()) { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return INVALID_VALUE; } if (0 > cIndex || cIndex >= (int)m_pArray->size()) { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return INVALID_VALUE; } return *(*m_pArray)[cIndex]; } Value &Value::GetItem(int cIndex, Status *pStatus/* = NULL*/) //-1 will create a new value at the end { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return INVALID_VALUE; } if (!IsArray()) { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return INVALID_VALUE; } if (-1 == cIndex) { return AddItem(pStatus); } if (0 > cIndex || cIndex >= (int)m_pArray->size()) { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return INVALID_VALUE; } return *(*m_pArray)[cIndex]; } const Value &Value::operator[](int cIndex) const { return GetItem(cIndex); } Value &Value::operator[](int cIndex) //a non existing member will be created { return GetItem(cIndex); } Size Value::GetMembersCount(Status *pStatus/* = NULL*/) const { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return 0; } if (!IsObject()) { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return 0; } return m_pObject->size(); } Bool Value::Exists(const String &sName, Status *pStatus/* = NULL*/) const { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return False; } if (!IsObject()) { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return False; } return (m_pObject->end() != m_pObject->find(sName)); } Value &Value::AddMember(const String &sName, Status *pStatus/* = NULL*/) { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return INVALID_VALUE; } if (!IsObject()) { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return INVALID_VALUE; } Object::iterator iter = m_pObject->find(sName); if (m_pObject->end() != iter) { return *iter->second; } Value *pValue; if (NULL == (pValue = new (std::nothrow) Value(this))) { return INVALID_VALUE; } (*m_pObject)[sName] = pValue; return *pValue; } Status Value::AddMember(const String &sName, Value *pValue) { if (IsInvalid()) { return Status_InvalidCall; } if (!IsObject()) { return Status_InvalidArg; } Object::iterator iter = m_pObject->find(sName); if (m_pObject->end() != iter) { return Status_InvalidArg; } if (NULL != pValue->m_pParent) { return Status_InvalidArg; } pValue->m_pParent = this; (*m_pObject)[sName] = pValue; return Status(); } Status Value::RemoveMember(const String &sName) { if (IsInvalid()) { return Status_InvalidCall; } if (!IsObject()) { return Status_InvalidArg; } Object::iterator iter = m_pObject->find(sName); if (m_pObject->end() == iter) { return Status_NotFound; } m_pObject->erase(iter); return Status(); } Status Value::RemoveAllMembers() { if (IsInvalid()) { return Status_InvalidCall; } if (!IsObject()) { return Status_InvalidArg; } for (Object::iterator iter = m_pObject->begin(); iter != m_pObject->end(); ++iter) { delete iter->second; } m_pObject->clear(); return Status(); } Value &Value::GetMemberByIndex(Size cIndex, String *psName/* = NULL*/, Status *pStatus/* = NULL*/) { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return INVALID_VALUE; } if (!IsObject()) { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return INVALID_VALUE; } if (cIndex >= m_pObject->size()) { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return INVALID_VALUE; } Object::iterator iter = m_pObject->begin(); while (0 < cIndex) { ++iter; cIndex--; } if (NULL != psName) { *psName = iter->first; } return *iter->second; } const Value &Value::GetMemberByIndex(Size cIndex, String *psName/* = NULL*/, Status *pStatus/* = NULL*/) const { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return INVALID_VALUE; } if (!IsObject()) { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return INVALID_VALUE; } if (cIndex >= m_pObject->size()) { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return INVALID_VALUE; } Object::const_iterator iter = m_pObject->begin(); while (0 < cIndex) { ++iter; cIndex--; } if (NULL != psName) { *psName = iter->first; } return *iter->second; } const Value &Value::GetMember(const String &sName, Status *pStatus/* = NULL*/) const { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return INVALID_VALUE; } if (!IsObject()) { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return INVALID_VALUE; } Object::const_iterator iter = m_pObject->find(sName); if (m_pObject->end() == iter) { if (NULL != pStatus) { *pStatus = Status_NotFound; } return INVALID_VALUE; } return *iter->second; } Value &Value::GetMember(const String &sName, Status *pStatus/* = NULL*/) //a non existing member will be created { if (IsInvalid()) { if (NULL != pStatus) { *pStatus = Status_InvalidCall; } return INVALID_VALUE; } if (!IsObject()) { if (NULL != pStatus) { *pStatus = Status_InvalidArg; } return INVALID_VALUE; } Object::iterator iter = m_pObject->find(sName); if (m_pObject->end() == iter) { return AddMember(sName, pStatus); } return *iter->second; } const Value &Value::operator[](const String &sName) const { return GetMember(sName); } Value &Value::operator[](const String &sName) //a non existing member will be created { return GetMember(sName); } const Value &Value::operator[](const Char *szName) const { return GetMember(szName); } Value &Value::operator[](const Char *szName) //a non existing member will be created { return GetMember(szName); } Value &Value::operator=(Bool bBool) { SetBool(bBool); return *this; } Value &Value::operator=(Int64 nInt) { SetInt(nInt); return *this; } Value &Value::operator=(UInt64 uInt) { SetUInt(uInt); return *this; } Value &Value::operator=(Double lfReal) { SetReal(lfReal); return *this; } Value &Value::operator=(const String &sString) { SetString(sString); return *this; } Value &Value::operator=(const Char *szString) { SetString(szString); return *this; } Value::operator Bool () const { return GetBool(); } Value::operator Int64 () const { return GetInt(); } Value::operator UInt64 () const { return GetUInt(); } Value::operator Double () const { return GetReal(); } Value::operator const String & () const { return GetString(); } Value::operator const Char * () const { return GetString().c_str(); } Status Value::Read(IO::IInputStream *pInputStream) { Data::JSON::SAXParser parser; VarJSONSAXParserObserver observer; Status status; observer.m_pRoot = observer.m_pCurrent = this; observer.m_bInit = True; if ((status = parser.AddObserver(&observer)).IsNOK()) { return status; } return parser.ParseStream(pInputStream); } Status Value::Read(const void *pData, Size cbSize) { IO::MemInputStream mis(pData, cbSize); return Read(&mis); } Status Value::Read(const String &sData) { return Read(sData.c_str(), sData.size()); } Status Value::Read(const Char *szData) { return Read(String(szData)); } int Value::Compare(const Value &v) const { struct Node { const Value *pV1; const Value *pV2; int cIndex; }; typedef Stack<Node>::Type NodesStack; NodesStack stackNodes; const Value *pV1 = this; const Value *pV2 = &v; bool bReady; Status status; for (;;) { if (!stackNodes.empty()) { stackNodes.top().cIndex++; if (stackNodes.top().pV1->IsObject()) { String sName; if ((Size)stackNodes.top().cIndex < stackNodes.top().pV1->GetMembersCount()) { pV1 = &stackNodes.top().pV1->GetMemberByIndex((Size)stackNodes.top().cIndex, &sName, &status); if (!status) { return status; } pV2 = &stackNodes.top().pV2->GetMember(sName, &status); if (!status) { return status; } } else { stackNodes.pop(); if (stackNodes.empty()) { break; } else { continue; } } } else { if ((Size)stackNodes.top().cIndex < stackNodes.top().pV1->GetItemsCount()) { pV1 = &stackNodes.top().pV1->GetItem((Size)stackNodes.top().cIndex, &status); if (!status) { return status; } pV2 = &stackNodes.top().pV2->GetItem((Size)stackNodes.top().cIndex, &status); if (!status) { return status; } } else { stackNodes.pop(); if (stackNodes.empty()) { break; } else { continue; } } } } bReady = false; if (pV1->IsInt()) { if (pV2->IsUInt()) { if (0 > pV1->GetInt()) { return -1; } else { if ((UInt64)pV1->GetInt() < pV2->GetUInt()) { return -1; } else if ((UInt64)pV1->GetInt() > pV2->GetUInt()) { return 1; } } bReady = true; } else if (pV2->IsReal()) { if ((double)pV1->GetInt() < pV2->GetReal()) { return -1; } else if ((double)pV1->GetInt() > pV2->GetReal()) { return 1; } bReady = true; } } else if (pV1->IsUInt()) { if (pV2->IsInt()) { if (0 > pV2->GetInt()) { return 1; } else { if (pV1->GetUInt() < (UInt64)pV2->GetInt()) { return -1; } else if (pV1->GetUInt() > (UInt64)pV2->GetInt()) { return 1; } } bReady = true; } else if (pV2->IsReal()) { if ((double)pV1->GetUInt() < pV2->GetReal()) { return -1; } else if ((double)pV1->GetUInt() > pV2->GetReal()) { return 1; } bReady = true; } } else if (pV1->IsReal()) { if (pV2->IsInt()) { if (pV1->GetReal() < (double)pV2->GetInt()) { return -1; } else if (pV1->GetReal() > (double)pV2->GetInt()) { return 1; } bReady = true; } else if (pV2->IsUInt()) { if (pV1->GetReal() < (double)pV2->GetUInt()) { return -1; } else if (pV1->GetReal() > (double)pV2->GetUInt()) { return 1; } bReady = true; } } if (!bReady) { if (pV1->GetType() < pV2->GetType()) { return -1; } else if (pV1->GetType() > pV2->GetType()) { return 1; } else { if (pV1->IsNull()) { //nothing to do } else if (pV1->IsBool()) { if (pV1->GetBool() < pV2->GetBool()) { return -1; } else if (pV1->GetBool() > pV2->GetBool()) { return 1; } } else if (pV1->IsInt()) { if (pV1->GetInt() < pV2->GetInt()) { return -1; } if (pV1->GetInt() > pV2->GetInt()) { return 1; } } else if (pV1->IsUInt()) { if (pV1->GetUInt() < pV2->GetUInt()) { return -1; } if (pV1->GetUInt() > pV2->GetUInt()) { return 1; } } else if (pV1->IsReal()) { if (pV1->GetReal() < pV2->GetReal()) { return -1; } if (pV1->GetReal() > pV2->GetReal()) { return 1; } } else if (pV1->IsString()) { int nCmp = cx_strcmp(pV1->GetString().c_str(), pV2->GetString().c_str()); if (0 != nCmp) { return nCmp; } } else if (pV1->IsObject()) { if (pV1->GetMembersCount() < pV2->GetMembersCount()) { return -1; } else if (pV1->GetMembersCount() > pV2->GetMembersCount()) { return 1; } Node node; node.pV1 = pV1; node.pV2 = pV2; node.cIndex = -1; stackNodes.push(node); } else if (pV1->IsArray()) { if (pV1->GetItemsCount() < pV2->GetItemsCount()) { return -1; } else if (pV1->GetItemsCount() > pV2->GetItemsCount()) { return 1; } Node node; node.pV1 = pV1; node.pV2 = pV2; node.cIndex = -1; stackNodes.push(node); } else { return -1; } } } if (stackNodes.empty()) { break; } } return 0; } }//namespace CX
14.651175
112
0.602559
draede
9a2fb0628aefad8b7f0559296a58049cf8c5d057
1,245
hpp
C++
include/Pomdog/Graphics/InputLayoutHelper.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
include/Pomdog/Graphics/InputLayoutHelper.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
include/Pomdog/Graphics/InputLayoutHelper.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_INPUTLAYOUTHELPER_A6C6ACE6_HPP #define POMDOG_INPUTLAYOUTHELPER_A6C6ACE6_HPP #include "detail/ForwardDeclarations.hpp" #include "InputElementFormat.hpp" #include "InputElement.hpp" #include "InputLayoutDescription.hpp" #include "Pomdog/Basic/Export.hpp" #include <cstdint> namespace Pomdog { class POMDOG_EXPORT InputLayoutHelper final { public: InputLayoutHelper & PushBack(InputElementFormat format); InputLayoutHelper & Byte4(); InputLayoutHelper & Float(); InputLayoutHelper & Float2(); InputLayoutHelper & Float3(); InputLayoutHelper & Float4(); InputLayoutHelper & Int4(); InputLayoutHelper & AddInputSlot(); InputLayoutHelper & AddInputSlot(InputClassification slotClass, std::uint16_t instanceStepRate); InputLayoutDescription CreateInputLayout(); private: std::vector<InputElement> elements; std::uint16_t inputSlot = 0; std::uint16_t byteOffset = 0; std::uint16_t instanceStepRate = 0; InputClassification slotClass = InputClassification::InputPerVertex; }; } // namespace Pomdog #endif // POMDOG_INPUTLAYOUTHELPER_A6C6ACE6_HPP
24.9
72
0.759839
bis83
9a2fb48bc643b588adf33c4b65b984ac3fbbd498
7,800
cpp
C++
include/et/rendering/vulkan/vulkan_textureset.cpp
sergeyreznik/et-engine
a95fe4b9c5db0e873361f36908de284d0ae4b6d6
[ "BSD-3-Clause" ]
55
2015-01-13T22:50:36.000Z
2022-02-26T01:55:02.000Z
include/et/rendering/vulkan/vulkan_textureset.cpp
sergeyreznik/et-engine
a95fe4b9c5db0e873361f36908de284d0ae4b6d6
[ "BSD-3-Clause" ]
4
2015-01-17T01:57:42.000Z
2016-07-29T07:49:27.000Z
include/et/rendering/vulkan/vulkan_textureset.cpp
sergeyreznik/et-engine
a95fe4b9c5db0e873361f36908de284d0ae4b6d6
[ "BSD-3-Clause" ]
10
2015-01-17T18:46:44.000Z
2021-05-21T09:19:13.000Z
/* * This file is part of `et engine` * Copyright 2009-2016 by Sergey Reznik * Please, modify content only if you know what are you doing. * */ #pragma once #include <et/rendering/vulkan/vulkan_textureset.h> #include <et/rendering/vulkan/vulkan_texture.h> #include <et/rendering/vulkan/vulkan_sampler.h> #include <et/rendering/vulkan/vulkan_renderer.h> #include <et/rendering/vulkan/vulkan.h> namespace et { class VulkanTextureSetPrivate : public VulkanNativeTextureSet { public: VulkanTextureSetPrivate(VulkanState& v) : vulkan(v) { } VulkanState& vulkan; }; VulkanTextureSet::VulkanTextureSet(VulkanRenderer* renderer, VulkanState& vulkan, const Description& desc) { ET_PIMPL_INIT(VulkanTextureSet, vulkan); const uint32_t MaxObjectsCount = 32; std::array<VkDescriptorSetLayoutBinding, MaxObjectsCount> texturesBindings = {}; std::array<VkWriteDescriptorSet, MaxObjectsCount> texturesWriteSet = {}; std::array<VkDescriptorImageInfo, MaxObjectsCount> texturesInfos = {}; std::array<VkDescriptorSetLayoutBinding, MaxObjectsCount> imagesBindings = {}; std::array<VkWriteDescriptorSet, MaxObjectsCount> imagesWriteSet = {}; std::array<VkDescriptorImageInfo, MaxObjectsCount> imagesInfos = {}; std::array<VkDescriptorSetLayoutBinding, MaxObjectsCount> samplersBindings = {}; std::array<VkWriteDescriptorSet, MaxObjectsCount> samplersWriteSet = {}; std::array<VkDescriptorImageInfo, MaxObjectsCount> samplersInfos = {}; bool allowEmptySet = false; uint32_t texturesCount = 0; uint32_t samplersCount = 0; uint32_t imagesCount = 0; for (const auto& entry : desc) { allowEmptySet |= entry.second.allowEmptySet; VkShaderStageFlagBits stageFlags = vulkan::programStageValue(entry.first); for (const auto& e : entry.second.textures) { VkDescriptorSetLayoutBinding& binding = texturesBindings[texturesCount]; binding.binding = e.first; binding.descriptorCount = 1; binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; binding.stageFlags = stageFlags; VkDescriptorImageInfo& info = texturesInfos[texturesCount]; info.imageView = VulkanTexture::Pointer(e.second.image)->nativeTexture().imageView(e.second.range); info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; VkWriteDescriptorSet& ws = texturesWriteSet[texturesCount]; ws.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; ws.descriptorCount = binding.descriptorCount; ws.descriptorType = binding.descriptorType; ws.dstBinding = binding.binding; ws.pImageInfo = texturesInfos.data() + texturesCount; ++texturesCount; ET_ASSERT(texturesCount < MaxObjectsCount); } for (const auto& e : entry.second.images) { VkDescriptorSetLayoutBinding& binding = imagesBindings[imagesCount]; binding.binding = e.first; binding.descriptorCount = 1; binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; binding.stageFlags = stageFlags; // TODO : use range for images (instead of whole range) VkDescriptorImageInfo& info = imagesInfos[imagesCount]; info.imageView = VulkanTexture::Pointer(e.second)->nativeTexture().imageView(ResourceRange::whole); info.imageLayout = VK_IMAGE_LAYOUT_GENERAL; VkWriteDescriptorSet& ws = imagesWriteSet[imagesCount]; ws.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; ws.descriptorCount = binding.descriptorCount; ws.descriptorType = binding.descriptorType; ws.dstBinding = binding.binding; ws.pImageInfo = imagesInfos.data() + imagesCount; ++imagesCount; ET_ASSERT(imagesCount < MaxObjectsCount); } for (const auto& e : entry.second.samplers) { VkDescriptorSetLayoutBinding& binding = samplersBindings[samplersCount]; binding.binding = e.first; binding.descriptorCount = 1; binding.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; binding.stageFlags = stageFlags; VkDescriptorImageInfo& info = samplersInfos[samplersCount]; info.sampler = VulkanSampler::Pointer(e.second)->nativeSampler().sampler; VkWriteDescriptorSet& ws = samplersWriteSet[samplersCount]; ws.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; ws.descriptorCount = binding.descriptorCount; ws.descriptorType = binding.descriptorType; ws.dstBinding = binding.binding; ws.pImageInfo = samplersInfos.data() + samplersCount; ++samplersCount; ET_ASSERT(samplersCount < MaxObjectsCount); } } if ((imagesCount > 0) || allowEmptySet) { VkDescriptorSetLayoutCreateInfo createInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO }; createInfo.bindingCount = imagesCount; createInfo.pBindings = imagesBindings.data(); VULKAN_CALL(vkCreateDescriptorSetLayout(vulkan.device, &createInfo, nullptr, &_private->imagesSetLayout)); VkDescriptorSetAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO }; allocInfo.descriptorPool = vulkan.descriptorPool; allocInfo.descriptorSetCount = 1; allocInfo.pSetLayouts = &_private->imagesSetLayout; VULKAN_CALL(vkAllocateDescriptorSets(vulkan.device, &allocInfo, &_private->imagesSet)); for (uint32_t i = 0; i < imagesCount; ++i) imagesWriteSet[i].dstSet = _private->imagesSet; vkUpdateDescriptorSets(vulkan.device, imagesCount, imagesWriteSet.data(), 0, nullptr); } if ((samplersCount > 0) || allowEmptySet) { VkDescriptorSetLayoutCreateInfo createInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO }; createInfo.bindingCount = samplersCount; createInfo.pBindings = samplersBindings.data(); VULKAN_CALL(vkCreateDescriptorSetLayout(vulkan.device, &createInfo, nullptr, &_private->samplersSetLayout)); VkDescriptorSetAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO }; allocInfo.descriptorPool = vulkan.descriptorPool; allocInfo.descriptorSetCount = 1; allocInfo.pSetLayouts = &_private->samplersSetLayout; VULKAN_CALL(vkAllocateDescriptorSets(vulkan.device, &allocInfo, &_private->samplersSet)); for (uint32_t i = 0; i < samplersCount; ++i) samplersWriteSet[i].dstSet = _private->samplersSet; vkUpdateDescriptorSets(vulkan.device, samplersCount, samplersWriteSet.data(), 0, nullptr); } if ((texturesCount > 0) || allowEmptySet) { VkDescriptorSetLayoutCreateInfo createInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO }; createInfo.bindingCount = texturesCount; createInfo.pBindings = texturesBindings.data(); VULKAN_CALL(vkCreateDescriptorSetLayout(vulkan.device, &createInfo, nullptr, &_private->texturesSetLayout)); VkDescriptorSetAllocateInfo allocInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO }; allocInfo.descriptorPool = vulkan.descriptorPool; allocInfo.descriptorSetCount = 1; allocInfo.pSetLayouts = &_private->texturesSetLayout; VULKAN_CALL(vkAllocateDescriptorSets(vulkan.device, &allocInfo, &_private->texturesSet)); for (uint32_t i = 0; i < texturesCount; ++i) texturesWriteSet[i].dstSet = _private->texturesSet; vkUpdateDescriptorSets(vulkan.device, texturesCount, texturesWriteSet.data(), 0, nullptr); } } VulkanTextureSet::~VulkanTextureSet() { VULKAN_CALL(vkFreeDescriptorSets(_private->vulkan.device, _private->vulkan.descriptorPool, 1, &_private->texturesSet)); vkDestroyDescriptorSetLayout(_private->vulkan.device, _private->texturesSetLayout, nullptr); VULKAN_CALL(vkFreeDescriptorSets(_private->vulkan.device, _private->vulkan.descriptorPool, 1, &_private->samplersSet)); vkDestroyDescriptorSetLayout(_private->vulkan.device, _private->samplersSetLayout, nullptr); VULKAN_CALL(vkFreeDescriptorSets(_private->vulkan.device, _private->vulkan.descriptorPool, 1, &_private->imagesSet)); vkDestroyDescriptorSetLayout(_private->vulkan.device, _private->imagesSetLayout, nullptr); ET_PIMPL_FINALIZE(VulkanTextureSet); } const VulkanNativeTextureSet& VulkanTextureSet::nativeSet() const { return *(_private); } }
38.613861
120
0.782821
sergeyreznik
9a317db3c774b45f8f4c3e1a3770092005b5f11b
2,482
cpp
C++
lab_01/lab1_fixed.cpp
pwestrich/csc_2110
ed56c0ccdc7aeb55e6f0711a958b8c1fff691bd5
[ "MIT" ]
null
null
null
lab_01/lab1_fixed.cpp
pwestrich/csc_2110
ed56c0ccdc7aeb55e6f0711a958b8c1fff691bd5
[ "MIT" ]
null
null
null
lab_01/lab1_fixed.cpp
pwestrich/csc_2110
ed56c0ccdc7aeb55e6f0711a958b8c1fff691bd5
[ "MIT" ]
null
null
null
// ------------------------------------------------------- // // lab1.cpp // // Program to read a 3 X 3 matrix of integers mat and an integer item, and // search mat to see if it contains item. // // Add your name here and other info requested by your instructor. // // ------------------------------------------------------- #include <iostream> const int SIZE = 3; // Set Matrix size typedef int Matrix[SIZE][SIZE]; bool matrixSearch(Matrix &mat, int n, int item); // ------------------------------------------------------- // Search the n X n matrix mat in row-wise order for item. // // Precondition: // Matrix mat is an n X n matrix of integers with n > 0. // Postcondition: // True is returned if item is found in mat, else false. // ------------------------------------------------------- int main() { Matrix mat; // Enter the matrix Matrix mat; std::cout << "Enter the elements of the " << SIZE << " X " << SIZE << " matrix row-wise:" << std::endl; for (int i = 0; i < SIZE; i++) for (int j = 0; j < SIZE; j++) std::cin >> mat[i][j]; // Search mat for various items mt itemToFind; char response; int itemToFind; do { std::cout << "Enter integer to search for: "; std::cin >> itemToFind; if (matrixSearch(mat, SIZE, itemToFind)) std::cout << "item found" << std::endl; else std::cout << "item not found" << std::endl; std::cout << std::endl << "More items to search for (Y or N)? "; std::cin >> response; } while (response == 'Y' || response == 'y'); } //-- (-- Incorrect --) Definition of matrixSearch() // ------------------------------------------------------- // Search the n X n matrix mat in row-wise order for item // // Precondition: // Matrix mat is an n X n matrix of integers with n > 0. // // Postcondition: // True is returned if item is found in mat, else false. // // NOTE: // mat[row] [col] denotes the entry of the matrix in the // (horizontal) row numbered row (counting from 0) and the // (vertical) column numbered col. // -------------------------------------------------------- bool matrixSearch(Matrix & mat, int n, int item) { bool found = false; for (int row = 0; row < n; row++){ for (int col = 0; col < n; col++) { if (mat[row][col] == item) { found = true; } } } return found; }
30.641975
76
0.485093
pwestrich
9a389690742920a2c94fc47c069346cc422bf1d7
4,502
cpp
C++
tests/manipulating_values.cpp
whiterabbit963/tomlplusplus
6b8fa1bef546664b1031d4f0d32c77df5d8d94c1
[ "MIT" ]
null
null
null
tests/manipulating_values.cpp
whiterabbit963/tomlplusplus
6b8fa1bef546664b1031d4f0d32c77df5d8d94c1
[ "MIT" ]
null
null
null
tests/manipulating_values.cpp
whiterabbit963/tomlplusplus
6b8fa1bef546664b1031d4f0d32c77df5d8d94c1
[ "MIT" ]
null
null
null
// This file is a part of toml++ and is subject to the the terms of the MIT license. // Copyright (c) 2019-2020 Mark Gillard <mark.gillard@outlook.com.au> // See https://github.com/marzer/tomlplusplus/blob/master/LICENSE for the full license text. // SPDX-License-Identifier: MIT #include "tests.h" #ifdef _WIN32 TOML_PUSH_WARNINGS TOML_DISABLE_ALL_WARNINGS #include <Windows.h> TOML_POP_WARNINGS #endif // TOML_PUSH_WARNINGS // TOML_DISABLE_ARITHMETIC_WARNINGS template <typename T> static constexpr T one = static_cast<T>(1); TEST_CASE("values - construction") { #define CHECK_VALUE_INIT2(initializer, target_type, equiv) \ do { \ auto v = value{ initializer }; \ static_assert(std::is_same_v<decltype(v), value<target_type>>); \ CHECK(v == equiv); \ CHECK(equiv == v); \ CHECK(*v == equiv); \ CHECK(v.get() == equiv); \ } while (false) #define CHECK_VALUE_INIT(initializer, target_type) \ CHECK_VALUE_INIT2(initializer, target_type, initializer) CHECK_VALUE_INIT(one<signed char>, int64_t); CHECK_VALUE_INIT(one<signed short>, int64_t); CHECK_VALUE_INIT(one<signed int>, int64_t); CHECK_VALUE_INIT(one<signed long>, int64_t); CHECK_VALUE_INIT(one<signed long long>, int64_t); CHECK_VALUE_INIT2(one<unsigned char>, int64_t, 1u); CHECK_VALUE_INIT2(one<unsigned short>, int64_t, 1u); CHECK_VALUE_INIT2(one<unsigned int>, int64_t, 1u); CHECK_VALUE_INIT2(one<unsigned long>, int64_t, 1u); CHECK_VALUE_INIT2(one<unsigned long long>, int64_t, 1u); CHECK_VALUE_INIT(true, bool); CHECK_VALUE_INIT(false, bool); CHECK_VALUE_INIT("kek", std::string); CHECK_VALUE_INIT("kek"s, std::string); CHECK_VALUE_INIT("kek"sv, std::string); CHECK_VALUE_INIT2("kek"sv.data(), std::string, "kek"sv); #ifdef __cpp_lib_char8_t CHECK_VALUE_INIT2(u8"kek", std::string, "kek"sv); CHECK_VALUE_INIT2(u8"kek"s, std::string, "kek"sv); CHECK_VALUE_INIT2(u8"kek"sv, std::string, "kek"sv); CHECK_VALUE_INIT2(u8"kek"sv.data(), std::string, "kek"sv); #endif #ifdef _WIN32 CHECK_VALUE_INIT(one<BOOL>, int64_t); CHECK_VALUE_INIT(one<SHORT>, int64_t); CHECK_VALUE_INIT(one<INT>, int64_t); CHECK_VALUE_INIT(one<LONG>, int64_t); CHECK_VALUE_INIT(one<INT_PTR>, int64_t); CHECK_VALUE_INIT(one<LONG_PTR>, int64_t); CHECK_VALUE_INIT2(one<USHORT>, int64_t, 1u); CHECK_VALUE_INIT2(one<UINT>, int64_t, 1u); CHECK_VALUE_INIT2(one<ULONG>, int64_t, 1u); CHECK_VALUE_INIT2(one<UINT_PTR>, int64_t, 1u); CHECK_VALUE_INIT2(one<ULONG_PTR>, int64_t, 1u); CHECK_VALUE_INIT2(one<WORD>, int64_t, 1u); CHECK_VALUE_INIT2(one<DWORD>, int64_t, 1u); CHECK_VALUE_INIT2(one<DWORD32>, int64_t, 1u); CHECK_VALUE_INIT2(one<DWORD64>, int64_t, 1u); CHECK_VALUE_INIT2(one<DWORDLONG>, int64_t, 1u); #if TOML_WINDOWS_COMPAT CHECK_VALUE_INIT2(L"kek", std::string, "kek"sv); CHECK_VALUE_INIT2(L"kek"s, std::string, "kek"sv); CHECK_VALUE_INIT2(L"kek"sv, std::string, "kek"sv); CHECK_VALUE_INIT2(L"kek"sv.data(), std::string, "kek"sv); #endif // TOML_WINDOWS_COMPAT #endif } // TOML_POP_WARNINGS TEST_CASE("values - printing") { static constexpr auto print_value = [](auto&& raw) { auto val = toml::value{ std::forward<decltype(raw)>(raw) }; std::stringstream ss; ss << val; return ss.str(); }; CHECK(print_value(1) == "1"); CHECK(print_value(1.0f) == "1.0"); CHECK(print_value(1.0) == "1.0"); CHECK(print_value(1.5f) == "1.5"); CHECK(print_value(1.5) == "1.5"); CHECK(print_value(10) == "10"); CHECK(print_value(10.0f) == "10.0"); CHECK(print_value(10.0) == "10.0"); CHECK(print_value(100) == "100"); CHECK(print_value(100.0f) == "100.0"); CHECK(print_value(100.0) == "100.0"); CHECK(print_value(1000) == "1000"); CHECK(print_value(1000.0f) == "1000.0"); CHECK(print_value(1000.0) == "1000.0"); CHECK(print_value(10000) == "10000"); CHECK(print_value(10000.0f) == "10000.0"); CHECK(print_value(10000.0) == "10000.0"); CHECK(print_value(std::numeric_limits<double>::infinity()) == "inf"); CHECK(print_value(-std::numeric_limits<double>::infinity()) == "-inf"); CHECK(print_value(std::numeric_limits<double>::quiet_NaN()) == "nan"); // only integers for large values; // large floats might get output as scientific notation and that's fine CHECK(print_value(10000000000) == "10000000000"); CHECK(print_value(100000000000000) == "100000000000000"); }
33.849624
92
0.683696
whiterabbit963
9a3ba4e009c36026703baa2c7cd1c15a6daabbd1
530
cpp
C++
uva/11889_0.cpp
larc/competitive_programming
deccd7152a14adf217c58546d1cf8ac6b45f1c52
[ "MIT" ]
1
2019-05-23T19:05:39.000Z
2019-05-23T19:05:39.000Z
uva/11889_0.cpp
larc/oremor
deccd7152a14adf217c58546d1cf8ac6b45f1c52
[ "MIT" ]
null
null
null
uva/11889_0.cpp
larc/oremor
deccd7152a14adf217c58546d1cf8ac6b45f1c52
[ "MIT" ]
null
null
null
// 11889 - Benefit #include <cstdio> int gcd(const int & a, const int & b) { if(!b) return a; return gcd(b, a % b); } // gcd and lcm solution int main() { int a, b, c, n; scanf("%d", &n); while(n-- && scanf("%d %d", &a, &c)) { if(c % a != 0) printf("NO SOLUTION\n"); else { b = c; for(int i = 1; i * i <= c; ++i) if(c % i == 0) { if(i < b && (a / gcd(a, i)) * i == c) b = i; if(c / i < b && a == gcd(a, c / i) * i) b = c / i; } printf("%d\n", b); } } return 0; }
13.25
44
0.40566
larc
9a4001b994da872b3f169344c8f06a215cecc3ec
1,058
cpp
C++
MovieRental/main.cpp
SonicYeager/CppPractice
05b80ac918648ba733ec5fce969eac4b2ae79b58
[ "MIT" ]
null
null
null
MovieRental/main.cpp
SonicYeager/CppPractice
05b80ac918648ba733ec5fce969eac4b2ae79b58
[ "MIT" ]
9
2020-10-26T10:14:46.000Z
2020-10-27T12:13:51.000Z
MovieRental/main.cpp
SonicYeager/CppPractice
05b80ac918648ba733ec5fce969eac4b2ae79b58
[ "MIT" ]
null
null
null
#include "Customer.h" #include <iostream> #include <sstream> int main() { Customer paul("Paul"), jana("Jana"); paul.AddRental({{"Planet Erde", Movie::REGULAR}, 3}); paul.AddRental({{"Planet der Affen", Movie::NEW_RELEASE}, 5}); paul.AddRental({{"HowTo MAGIX", Movie::NEW_RELEASE}, 1}); jana.AddRental({{"Der kleine Zwerg", Movie::CHILDRENS}, 2}); jana.AddRental({{"Murx der Arzt", Movie::CHILDRENS}, 5}); std::ostringstream out; out << paul.Statement() << '\n' << jana.Statement() << '\n'; const std::string expected = R"(Rental Record for Paul Planet Erde 3.5 Planet der Affen 15 HowTo MAGIX 3 Amount owed is 21.5 You earned 4 frequent renter points Rental Record for Jana Der kleine Zwerg 1.5 Murx der Arzt 4.5 Amount owed is 6 You earned 2 frequent renter points )"; const std::string actual = out.str(); if(actual != expected) { std::cout << "actual:\n" << actual << "\ndiffers from expected:\n" << expected; } else { std::cout << "programm runs fine\n"; } system("pause"); return 0; }
26.45
82
0.643667
SonicYeager
9a422b4a5bfcbd31df6cd0e7cb09e588cd3e83cc
8,902
cpp
C++
apps/ncv_benchmark_optimizers.cpp
0x0all/nanocv
dc58dea6b4eb7be2089b168d39c2b02aa2730741
[ "MIT" ]
null
null
null
apps/ncv_benchmark_optimizers.cpp
0x0all/nanocv
dc58dea6b4eb7be2089b168d39c2b02aa2730741
[ "MIT" ]
null
null
null
apps/ncv_benchmark_optimizers.cpp
0x0all/nanocv
dc58dea6b4eb7be2089b168d39c2b02aa2730741
[ "MIT" ]
1
2018-08-02T02:41:37.000Z
2018-08-02T02:41:37.000Z
#include "nanocv/timer.h" #include "nanocv/logger.h" #include "nanocv/minimize.h" #include "nanocv/tabulator.h" #include "nanocv/math/abs.hpp" #include "nanocv/math/clamp.hpp" #include "nanocv/math/stats.hpp" #include "nanocv/math/random.hpp" #include "nanocv/math/numeric.hpp" #include "nanocv/math/epsilon.hpp" #include "nanocv/thread/loopi.hpp" #include "nanocv/functions/function_trid.h" #include "nanocv/functions/function_beale.h" #include "nanocv/functions/function_booth.h" #include "nanocv/functions/function_sphere.h" #include "nanocv/functions/function_matyas.h" #include "nanocv/functions/function_powell.h" #include "nanocv/functions/function_mccormick.h" #include "nanocv/functions/function_himmelblau.h" #include "nanocv/functions/function_rosenbrock.h" #include "nanocv/functions/function_3hump_camel.h" #include "nanocv/functions/function_sum_squares.h" #include "nanocv/functions/function_dixon_price.h" #include "nanocv/functions/function_goldstein_price.h" #include "nanocv/functions/function_rotated_ellipsoid.h" #include <map> #include <tuple> using namespace ncv; const size_t trials = 1024; struct optimizer_stat_t { stats_t<scalar_t> m_time; stats_t<scalar_t> m_crits; stats_t<scalar_t> m_fails; stats_t<scalar_t> m_iters; stats_t<scalar_t> m_fvals; stats_t<scalar_t> m_grads; }; std::map<string_t, optimizer_stat_t> optimizer_stats; static void check_problem( const string_t& problem_name, const opt_opsize_t& fn_size, const opt_opfval_t& fn_fval, const opt_opgrad_t& fn_grad, const std::vector<std::pair<vector_t, scalar_t>>&) { const size_t iterations = 1024; const scalar_t epsilon = 1e-6; const size_t dims = fn_size(); // generate fixed random trials vectors_t x0s; for (size_t t = 0; t < trials; t ++) { random_t<scalar_t> rgen(-1.0, +1.0); vector_t x0(dims); rgen(x0.data(), x0.data() + x0.size()); x0s.push_back(x0); } // optimizers to try const auto optimizers = { // optim::batch_optimizer::GD, // optim::batch_optimizer::CGD_CD, // optim::batch_optimizer::CGD_DY, // optim::batch_optimizer::CGD_FR, // optim::batch_optimizer::CGD_HS, // optim::batch_optimizer::CGD_LS, // optim::batch_optimizer::CGD_DYCD, optim::batch_optimizer::CGD_DYHS, optim::batch_optimizer::CGD_PRP, optim::batch_optimizer::CGD_N, optim::batch_optimizer::LBFGS }; const auto ls_initializers = { optim::ls_initializer::unit, optim::ls_initializer::quadratic, optim::ls_initializer::consistent }; const auto ls_strategies = { optim::ls_strategy::backtrack_armijo, optim::ls_strategy::backtrack_wolfe, optim::ls_strategy::backtrack_strong_wolfe, optim::ls_strategy::interpolation, optim::ls_strategy::cg_descent }; tabulator_t table(text::resize(problem_name, 32)); table.header() << "cost" << "time [us]" << "|grad|/|fval|" << "#fails" << "#iters" << "#fvals" << "#grads"; thread_pool_t pool; thread_pool_t::mutex_t mutex; for (optim::batch_optimizer optimizer : optimizers) for (optim::ls_initializer ls_initializer : ls_initializers) for (optim::ls_strategy ls_strategy : ls_strategies) { stats_t<scalar_t> times; stats_t<scalar_t> crits; stats_t<scalar_t> fails; stats_t<scalar_t> iters; stats_t<scalar_t> fvals; stats_t<scalar_t> grads; thread_loopi(trials, pool, [&] (size_t t) { const vector_t& x0 = x0s[t]; // check gradients const opt_problem_t problem(fn_size, fn_fval, fn_grad); if (problem.grad_accuracy(x0) > math::epsilon2<scalar_t>()) { const thread_pool_t::lock_t lock(mutex); log_error() << "invalid gradient for problem [" << problem_name << "]!"; } // optimize const ncv::timer_t timer; const opt_state_t state = ncv::minimize( fn_size, fn_fval, fn_grad, nullptr, nullptr, nullptr, x0, optimizer, iterations, epsilon, ls_initializer, ls_strategy); const scalar_t crit = state.convergence_criteria(); // update stats const thread_pool_t::lock_t lock(mutex); times(timer.microseconds()); crits(crit); iters(state.n_iterations()); fvals(state.n_fval_calls()); grads(state.n_grad_calls()); fails(!state.converged(epsilon) ? 1.0 : 0.0); }); // update per-problem table const string_t name = text::to_string(optimizer) + "[" + text::to_string(ls_initializer) + "][" + text::to_string(ls_strategy) + "]"; table.append(name) << static_cast<int>(fvals.sum() + 2 * grads.sum()) / trials << times.avg() << crits.avg() << static_cast<int>(fails.sum()) << iters.avg() << fvals.avg() << grads.avg(); // update global statistics optimizer_stat_t& stat = optimizer_stats[name]; stat.m_time(times.avg()); stat.m_crits(crits.avg()); stat.m_fails(fails.sum()); stat.m_iters(iters.avg()); stat.m_fvals(fvals.avg()); stat.m_grads(grads.avg()); } // print stats table.sort_as_number(2, tabulator_t::sorting::ascending); table.print(std::cout); } static void check_problems(const std::vector<ncv::function_t>& funcs) { for (const ncv::function_t& func : funcs) { check_problem(func.m_name, func.m_opsize, func.m_opfval, func.m_opgrad, func.m_solutions); } } int main(int, char* []) { using namespace ncv; // check_problems(ncv::make_beale_funcs()); check_problems(ncv::make_booth_funcs()); check_problems(ncv::make_matyas_funcs()); check_problems(ncv::make_trid_funcs(128)); check_problems(ncv::make_sphere_funcs(128)); check_problems(ncv::make_powell_funcs(128)); check_problems(ncv::make_mccormick_funcs()); check_problems(ncv::make_himmelblau_funcs()); check_problems(ncv::make_rosenbrock_funcs(7)); check_problems(ncv::make_3hump_camel_funcs()); check_problems(ncv::make_dixon_price_funcs(128)); check_problems(ncv::make_sum_squares_funcs(128)); // check_problems(ncv::make_goldstein_price_funcs()); check_problems(ncv::make_rotated_ellipsoid_funcs(128)); // show global statistics tabulator_t table(text::resize("optimizer", 32)); table.header() << "cost" << "time [us]" << "|grad|/|fval|" << "#fails" << "#iters" << "#fvals" << "#grads"; for (const auto& it : optimizer_stats) { const string_t& name = it.first; const optimizer_stat_t& stat = it.second; table.append(name) << static_cast<int>(stat.m_fvals.sum() + 2 * stat.m_grads.sum()) << stat.m_time.sum() << stat.m_crits.avg() << static_cast<int>(stat.m_fails.sum()) << stat.m_iters.sum() << stat.m_fvals.sum() << stat.m_grads.sum(); } table.sort_as_number(2, tabulator_t::sorting::ascending); table.print(std::cout); // OK log_info() << done; return EXIT_SUCCESS; }
36.040486
106
0.526174
0x0all
9a487b9a7ccac9f34b2618dcad4491cc3fcc14ec
5,047
cpp
C++
ares/fc/cartridge/board/konami-vrc2.cpp
moon-chilled/Ares
909fb098c292f8336d0502dc677050312d8b5c81
[ "0BSD" ]
7
2020-07-25T11:44:39.000Z
2021-01-29T13:21:31.000Z
ares/fc/cartridge/board/konami-vrc2.cpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
null
null
null
ares/fc/cartridge/board/konami-vrc2.cpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
1
2021-03-22T16:15:30.000Z
2021-03-22T16:15:30.000Z
struct KonamiVRC2 : Interface { Memory::Readable<uint8> programROM; Memory::Writable<uint8> programRAM; Memory::Readable<uint8> characterROM; Memory::Writable<uint8> characterRAM; using Interface::Interface; auto load(Markup::Node document) -> void override { auto board = document["game/board"]; Interface::load(programROM, board["memory(type=ROM,content=Program)"]); Interface::load(programRAM, board["memory(type=RAM,content=Save)"]); Interface::load(characterROM, board["memory(type=ROM,content=Character)"]); Interface::load(characterRAM, board["memory(type=RAM,content=Character)"]); pinA0 = 1 << board["chip(type=VRC2)/pinout/a0"].natural(); pinA1 = 1 << board["chip(type=VRC2)/pinout/a1"].natural(); } auto save(Markup::Node document) -> void override { auto board = document["game/board"]; Interface::save(programRAM, board["memory(type=RAM,content=Save)"]); Interface::save(characterRAM, board["memory(type=RAM,content=Character)"]); } auto readPRG(uint address) -> uint8 { if(address < 0x6000) return cpu.mdr(); if(address < 0x8000) { if(!programRAM && (address & 0xf000) == 0x6000) return cpu.mdr() | latch; if(!programRAM) return cpu.mdr(); return programRAM.read((uint13)address); } uint5 bank, banks = programROM.size() >> 13; switch(address & 0xe000) { case 0x8000: bank = programBank[0]; break; case 0xa000: bank = programBank[1]; break; case 0xc000: bank = banks - 2; break; case 0xe000: bank = banks - 1; break; } address = bank << 13 | (uint13)address; return programROM.read(address); } auto writePRG(uint address, uint8 data) -> void { if(address < 0x6000) return; if(address < 0x8000) { if(!programRAM && (address & 0xf000) == 0x6000) latch = data.bit(0); if(!programRAM) return; return programRAM.write((uint13)address, data); } bool a0 = address & pinA0; bool a1 = address & pinA1; address &= 0xf000; address |= a0 << 0 | a1 << 1; switch(address) { case 0x8000: case 0x8001: case 0x8002: case 0x8003: programBank[0] = data.bit(0,4); break; case 0x9000: case 0x9001: case 0x9002: case 0x9003: mirror = data.bit(0,1); break; case 0xa000: case 0xa001: case 0xa002: case 0xa003: programBank[1] = data.bit(0,4); break; case 0xb000: characterBank[0].bit(0,3) = data.bit(0,3); break; case 0xb001: characterBank[0].bit(4,7) = data.bit(0,3); break; case 0xb002: characterBank[1].bit(0,3) = data.bit(0,3); break; case 0xb003: characterBank[1].bit(4,7) = data.bit(0,3); break; case 0xc000: characterBank[2].bit(0,3) = data.bit(0,3); break; case 0xc001: characterBank[2].bit(4,7) = data.bit(0,3); break; case 0xc002: characterBank[3].bit(0,3) = data.bit(0,3); break; case 0xc003: characterBank[3].bit(4,7) = data.bit(0,3); break; case 0xd000: characterBank[4].bit(0,3) = data.bit(0,3); break; case 0xd001: characterBank[4].bit(4,7) = data.bit(0,3); break; case 0xd002: characterBank[5].bit(0,3) = data.bit(0,3); break; case 0xd003: characterBank[5].bit(4,7) = data.bit(0,3); break; case 0xe000: characterBank[6].bit(0,3) = data.bit(0,3); break; case 0xe001: characterBank[6].bit(4,7) = data.bit(0,3); break; case 0xe002: characterBank[7].bit(0,3) = data.bit(0,3); break; case 0xe003: characterBank[7].bit(4,7) = data.bit(0,3); break; } } auto addressCIRAM(uint address) const -> uint { switch(mirror) { case 0: return address >> 0 & 0x0400 | address & 0x03ff; //vertical mirroring case 1: return address >> 1 & 0x0400 | address & 0x03ff; //horizontal mirroring case 2: return 0x0000 | address & 0x03ff; //one-screen mirroring (first) case 3: return 0x0400 | address & 0x03ff; //one-screen mirroring (second) } unreachable; } auto addressCHR(uint address) const -> uint { uint8 bank = characterBank[address >> 10]; return bank << 10 | (uint10)address; } auto readCHR(uint address) -> uint8 { if(address & 0x2000) return ppu.readCIRAM(addressCIRAM(address)); if(characterROM) return characterROM.read(addressCHR(address)); if(characterRAM) return characterRAM.read(addressCHR(address)); return 0x00; } auto writeCHR(uint address, uint8 data) -> void { if(address & 0x2000) return ppu.writeCIRAM(addressCIRAM(address), data); if(characterRAM) return characterRAM.write(addressCHR(address), data); } auto power() -> void { for(auto& bank : programBank) bank = 0; for(auto& bank : characterBank) bank = 0; mirror = 0; latch = 0; } auto serialize(serializer& s) -> void { programRAM.serialize(s); characterRAM.serialize(s); s.integer(pinA0); s.integer(pinA1); s.array(programBank); s.array(characterBank); s.integer(mirror); s.integer(latch); } uint8 pinA0; uint8 pinA1; uint5 programBank[2]; uint8 characterBank[8]; uint2 mirror; uint1 latch; };
36.05
93
0.644938
moon-chilled
9a487e6564783f51cf469c2a1abd163251228c67
8,829
cpp
C++
QuantLib-Ext/qlext/termstructures/yield/ratehelpers.cpp
ChinaQuants/qlengine
6f40f8204df9b5c46eec6c6bb5cae6cde9b1455d
[ "BSD-3-Clause" ]
17
2017-09-24T13:25:43.000Z
2021-08-31T13:14:45.000Z
QuantLib-Ext/qlext/termstructures/yield/ratehelpers.cpp
Bralzer/ExoticOptionPriceEngine
55650eee29b054b2e3d5083eb42a81419960901f
[ "BSD-3-Clause" ]
null
null
null
QuantLib-Ext/qlext/termstructures/yield/ratehelpers.cpp
Bralzer/ExoticOptionPriceEngine
55650eee29b054b2e3d5083eb42a81419960901f
[ "BSD-3-Clause" ]
6
2017-09-25T01:29:35.000Z
2021-09-01T05:14:17.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2017 Cheng Li This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ #include <boost/make_shared.hpp> #include <ql/cashflows/iborcoupon.hpp> #include <ql/indexes/ibor/shibor.hpp> #include <ql/pricingengines/swap/discountingswapengine.hpp> #include <ql/time/calendars/china.hpp> #include <ql/utilities/null_deleter.hpp> #include <qlext/instruments/shiborswap.hpp> #include <qlext/instruments/subperiodsswap.hpp> #include <qlext/termstructures/yield/ratehelpers.hpp> namespace QuantLib { ShiborSwapRateHelper::ShiborSwapRateHelper(const Handle<Quote>& rate, const Period& swapTenor, Frequency fixedFreq, const boost::shared_ptr<Shibor>& shiborIndex, const Period& fwdStart, const Handle<YieldTermStructure>& discountingCurve) : RelativeDateRateHelper(rate), tenor_(swapTenor), fixedFrequency_(fixedFreq), fwdStart_(fwdStart), discountHandle_(discountingCurve) { settlementDays_ = shiborIndex->fixingDays(); shiborIndex_ = boost::dynamic_pointer_cast<Shibor>(shiborIndex->clone(termStructureHandle_)); shiborIndex_->unregisterWith(termStructureHandle_); registerWith(shiborIndex_); registerWith(discountHandle_); initializeDates(); } void ShiborSwapRateHelper::initializeDates() { Date refDate = Settings::instance().evaluationDate(); China floatCalendar(China::IB); refDate = floatCalendar.adjust(refDate); Date spotDate = floatCalendar.advance(refDate, settlementDays_ * Days); Date startDate = spotDate + fwdStart_; if (fwdStart_.length() < 0) startDate = floatCalendar.adjust(startDate, Preceding); else startDate = floatCalendar.adjust(startDate, Following); swap_ = boost::make_shared<ShiborSwap>(VanillaSwap::Payer, 1., startDate, tenor_, Period(fixedFrequency_), 0., shiborIndex_); bool includeSettlementDateFlows = false; boost::shared_ptr<PricingEngine> engine( new DiscountingSwapEngine(discountRelinkableHandle_, includeSettlementDateFlows)); swap_->setPricingEngine(engine); earliestDate_ = swap_->startDate(); maturityDate_ = swap_->maturityDate(); boost::shared_ptr<IborCoupon> lastCoupon = boost::dynamic_pointer_cast<IborCoupon>(swap_->floatingLeg().back()); latestRelevantDate_ = std::max(maturityDate_, lastCoupon->fixingEndDate()); latestDate_ = maturityDate_; } void ShiborSwapRateHelper::accept(AcyclicVisitor& v) { Visitor<ShiborSwapRateHelper>* v1 = dynamic_cast<Visitor<ShiborSwapRateHelper>*>(&v); if (v1 != 0) v1->visit(*this); else RateHelper::accept(v); } Real ShiborSwapRateHelper::impliedQuote() const { QL_REQUIRE(termStructure_ != 0, "term structure not set"); // we didn't register as observers - force calculation swap_->recalculate(); // weak implementation... to be improved static const Spread basisPoint = 1.0e-4; Real floatingLegNPV = swap_->floatingLegNPV(); Real totNPV = -floatingLegNPV; Real result = totNPV / (swap_->fixedLegBPS() / basisPoint); return result; } void ShiborSwapRateHelper::setTermStructure(YieldTermStructure* t) { // do not set the relinkable handle as an observer - // force recalculation when needed---the index is not lazy bool observer = false; boost::shared_ptr<YieldTermStructure> temp(t, null_deleter()); termStructureHandle_.linkTo(temp, observer); if (discountHandle_.empty()) discountRelinkableHandle_.linkTo(temp, observer); else discountRelinkableHandle_.linkTo(*discountHandle_, observer); RelativeDateRateHelper::setTermStructure(t); } SubPeriodsSwapRateHelper::SubPeriodsSwapRateHelper( const Handle<Quote>& rate, const Period& swapTenor, Frequency fixedFreq, const Calendar& fixedCalendar, const DayCounter& fixedDayCount, BusinessDayConvention fixedConvention, const Period& floatPayTenor, const boost::shared_ptr<IborIndex>& iborIndex, const DayCounter& floatingDayCount, DateGeneration::Rule rule, Ext::SubPeriodsCoupon::Type type, const Period& fwdStart, const Handle<YieldTermStructure>& discountingCurve) : RelativeDateRateHelper(rate), tenor_(swapTenor), fixedFrequency_(fixedFreq), fixedCalendar_(fixedCalendar), fixedDayCount_(fixedDayCount), fixedConvention_(fixedConvention), floatPayTenor_(floatPayTenor), floatingDayCount_(floatingDayCount), rule_(rule), type_(type), fwdStart_(fwdStart), discountHandle_(discountingCurve) { settlementDays_ = iborIndex->fixingDays(); iborIndex_ = boost::dynamic_pointer_cast<IborIndex>(iborIndex->clone(termStructureHandle_)); iborIndex_->unregisterWith(termStructureHandle_); registerWith(iborIndex_); registerWith(discountHandle_); initializeDates(); } void SubPeriodsSwapRateHelper::initializeDates() { Date refDate = Settings::instance().evaluationDate(); Calendar floatCalendar = iborIndex_->fixingCalendar(); refDate = floatCalendar.adjust(refDate); Date spotDate = floatCalendar.advance(refDate, settlementDays_ * Days); Date startDate = spotDate + fwdStart_; if (fwdStart_.length() < 0) startDate = floatCalendar.adjust(startDate, Preceding); else startDate = floatCalendar.adjust(startDate, Following); swap_ = boost::shared_ptr<SubPeriodsSwap>(new SubPeriodsSwap(startDate, 1., tenor_, true, Period(fixedFrequency_), 0., fixedCalendar_, fixedDayCount_, fixedConvention_, floatPayTenor_, iborIndex_, floatingDayCount_, rule_, type_)); bool includeSettlementDateFlows = false; boost::shared_ptr<PricingEngine> engine( new DiscountingSwapEngine(discountRelinkableHandle_, includeSettlementDateFlows)); swap_->setPricingEngine(engine); earliestDate_ = swap_->startDate(); maturityDate_ = swap_->maturityDate(); Leg floatLeg = swap_->floatLeg(); boost::shared_ptr<Ext::SubPeriodsCoupon> lastCoupon = boost::dynamic_pointer_cast<Ext::SubPeriodsCoupon>(floatLeg[floatLeg.size() - 1]); latestRelevantDate_ = std::max(latestDate_, lastCoupon->latestRelevantDate()); latestDate_ = maturityDate_; } void SubPeriodsSwapRateHelper::accept(AcyclicVisitor& v) { Visitor<SubPeriodsSwapRateHelper>* v1 = dynamic_cast<Visitor<SubPeriodsSwapRateHelper>*>(&v); if (v1 != 0) v1->visit(*this); else RateHelper::accept(v); } Real SubPeriodsSwapRateHelper::impliedQuote() const { QL_REQUIRE(termStructure_ != 0, "term structure not set"); // we didn't register as observers - force calculation swap_->recalculate(); // weak implementation... to be improved static const Spread basisPoint = 1.0e-4; Real floatingLegNPV = swap_->floatLegNPV(); Real totNPV = -floatingLegNPV; Real result = totNPV / (swap_->fixedLegBPS() / basisPoint); return result; } void SubPeriodsSwapRateHelper::setTermStructure(YieldTermStructure* t) { // do not set the relinkable handle as an observer - // force recalculation when needed---the index is not lazy bool observer = false; boost::shared_ptr<YieldTermStructure> temp(t, null_deleter()); termStructureHandle_.linkTo(temp, observer); if (discountHandle_.empty()) discountRelinkableHandle_.linkTo(temp, observer); else discountRelinkableHandle_.linkTo(*discountHandle_, observer); RelativeDateRateHelper::setTermStructure(t); } } // namespace QuantLib
42.859223
126
0.680372
ChinaQuants
9a4d816ed7e9a880ed798674b6969d2a8b5aa9a7
4,079
cpp
C++
user/tests/wiring/no_fixture/system.cpp
zsoltmazlo/indoor-controller2
5fde9f40b30d087af03f6cccdb97821719941955
[ "MIT" ]
1
2019-02-24T07:13:51.000Z
2019-02-24T07:13:51.000Z
user/tests/wiring/no_fixture/system.cpp
zsoltmazlo/indoor-controller2
5fde9f40b30d087af03f6cccdb97821719941955
[ "MIT" ]
1
2018-05-29T19:27:53.000Z
2018-05-29T19:27:53.000Z
user/tests/wiring/no_fixture/system.cpp
zsoltmazlo/indoor-controller2
5fde9f40b30d087af03f6cccdb97821719941955
[ "MIT" ]
null
null
null
#include "application.h" #include "unit-test/unit-test.h" #if PLATFORM_ID >= 3 test(SYSTEM_01_freeMemory) { // this test didn't work on the core attempting to allocate the current value of // freeMemory(), presumably because of fragmented heap from // relatively large allocations during the handshake, so the request was satisfied // without calling _sbrk() // 4096 was chosen to be small enough to allocate, but large enough to force _sbrk() to be called.) uint32_t free1 = System.freeMemory(); if (free1>128) { void* m1 = malloc(1024*6); uint32_t free2 = System.freeMemory(); free(m1); assertLess(free2, free1); } } #endif test(SYSTEM_02_version) { uint32_t versionNumber = System.versionNumber(); // Serial.println(System.versionNumber()); // 328193 -> 0x00050201 // Serial.println(System.version().c_str()); // 0.5.2-rc.1 char expected[20]; if (SYSTEM_VERSION & 0xFF) sprintf(expected, "%d.%d.%d-rc.%d", (int)BYTE_N(versionNumber,3), (int)BYTE_N(versionNumber,2), (int)BYTE_N(versionNumber,1), (int)BYTE_N(versionNumber,0)); else sprintf(expected, "%d.%d.%d", (int)BYTE_N(versionNumber,3), (int)BYTE_N(versionNumber,2), (int)BYTE_N(versionNumber,1)); assertTrue(strcmp(expected,System.version().c_str())==0); } // todo - use platform feature flags #if defined(STM32F2XX) // subtract 4 bytes for signature (3068 bytes) #define USER_BACKUP_RAM ((1024*3)-4) #endif // defined(STM32F2XX) #if defined(USER_BACKUP_RAM) STARTUP(System.enableFeature(FEATURE_RETAINED_MEMORY)); static retained uint8_t app_backup[USER_BACKUP_RAM]; static uint8_t app_ram[USER_BACKUP_RAM]; test(SYSTEM_03_user_backup_ram) { int total_backup = 0; int total_ram = 0; for (unsigned i=0; i<(sizeof(app_backup)/sizeof(app_backup[0])); i++) { app_backup[i] = 1; app_ram[i] = 1; total_backup += app_backup[i]; total_ram += app_ram[i]; } // Serial.printlnf("app_backup(0x%x), app_ram(0x%x)", &app_backup, &app_ram); // Serial.printlnf("total_backup: %d, total_ram: %d", total_backup, total_ram); assertTrue(total_backup==(USER_BACKUP_RAM)); assertTrue(total_ram==(USER_BACKUP_RAM)); if (int(&app_backup) < 0x40024000) { Serial.printlnf("ERROR: expected app_backup in user backup memory, but was at %x", &app_backup); } assertTrue(int(&app_backup)>=0x40024000); if (int(&app_ram) >= 0x40024000) { Serial.printlnf("ERROR: expected app_ram in user sram memory, but was at %x", &app_ram); } assertTrue(int(&app_ram)<0x40024000); } #endif // defined(USER_BACKUP_RAM) #if defined(BUTTON1_MIRROR_SUPPORTED) static int s_button_clicks = 0; static void onButtonClick(system_event_t ev, int data) { s_button_clicks = data; } test(SYSTEM_04_button_mirror) { // Known bug: // events posted from an ISR might not be delivered to the application queue // when threading is enabled if (system_thread_get_state(nullptr) == spark::feature::ENABLED) { skip(); return; } System.buttonMirror(D1, FALLING, false); auto pinmap = HAL_Pin_Map(); System.on(button_click, onButtonClick); // "Click" setup button 3 times // First click pinMode(D1, INPUT_PULLDOWN); // Just in case manually trigger EXTI interrupt EXTI_GenerateSWInterrupt(pinmap[D1].gpio_pin); delay(300); pinMode(D1, INPUT_PULLUP); delay(100); // Second click pinMode(D1, INPUT_PULLDOWN); // Just in case manually trigger EXTI interrupt EXTI_GenerateSWInterrupt(pinmap[D1].gpio_pin); delay(300); pinMode(D1, INPUT_PULLUP); delay(100); // Third click pinMode(D1, INPUT_PULLDOWN); // Just in case manually trigger EXTI interrupt EXTI_GenerateSWInterrupt(pinmap[D1].gpio_pin); delay(300); pinMode(D1, INPUT_PULLUP); delay(300); assertEqual(s_button_clicks, 3); } test(SYSTEM_05_button_mirror_disable) { System.disableButtonMirror(false); } #endif // defined(BUTTON1_MIRROR_SUPPORTED)
31.137405
164
0.683256
zsoltmazlo
9a51c4f477a971b0aac14e517d23c8ae2cd5a1a5
6,234
hpp
C++
ModelData/InstableCPUcoreOperationDetection.hpp
st-gb/CPUinfoAndControl
5e93d4a195b4692d147bb05cfef534e38d7f8b64
[ "MIT" ]
null
null
null
ModelData/InstableCPUcoreOperationDetection.hpp
st-gb/CPUinfoAndControl
5e93d4a195b4692d147bb05cfef534e38d7f8b64
[ "MIT" ]
null
null
null
ModelData/InstableCPUcoreOperationDetection.hpp
st-gb/CPUinfoAndControl
5e93d4a195b4692d147bb05cfef534e38d7f8b64
[ "MIT" ]
1
2021-07-16T21:01:26.000Z
2021-07-16T21:01:26.000Z
/* * InstableCPUcoreOperationDetection.hpp * * Created on: 22.04.2012 * Author: Stefan */ #ifndef INSTABLECPUCOREVOLTAGEDETECTION_HPP_ #define INSTABLECPUCOREVOLTAGEDETECTION_HPP_ //#include "VoltageAndFreq.hpp" //class VoltageAndFreq #include <Controller/multithread/thread_type.hpp> //THREAD_PROC_CALLING_CONVENTION #include <preprocessor_macros/thread_proc_calling_convention.h> #include <preprocessor_macros/logging_preprocessor_macros.h> //struct external_caller, StartInstableVoltageDetectionFunctionPointer, // StopInstableVoltageDetectionFunctionPointer #include <InstableCPUcoreVoltageDefintions.h> #include <UserInterface/UserInterface.hpp> #include <Controller/multithread/condition_type.hpp> //#include "" //Forward decl. class CPUcoreData; class I_CPUcontroller; /** Used for displaying the progress of finding the lowest voltage for an * instable CPU operation detection status in GUI. */ struct InstableCPUoperationDetectionData { //protected: public: unsigned m_secondsUntilCPUcoreVoltageDecrease; float m_fCPUcoreUsageOfDynLibThread; }; class wxX86InfoAndControlApp; class InstableCPUcoreOperationDetection : public InstableCPUoperationDetectionData { public: /** Set to true if executable was called by instable CPU core op detection dyn lib */ volatile bool m_bVoltageWasTooLowCalled; volatile bool m_bStopFindingLowestStableCPUcoreVoltageRequestedViaUI; //Is set to true when "VoltageTooLow" was called. volatile bool m_vbExitFindLowestStableVoltage; static InstableCPUcoreOperationDetection * s_p_instableCPUcoreOperationDetection; uint32_t m_ui32CPUcoreMask; CPUcoreData & m_r_cpucoredata; I_CPUcontroller * m_p_cpucontroller; // float m_fCPUcoreUsageOfDynLibThread; /** Use unsigned datatype because same bit width as CPU arch.->fast. */ unsigned m_secondsUntilVoltageDecrease; unsigned m_milliSecondsToWaitBeforeSecondsCountDown; #ifdef _WIN32 //TODO replace with wxDynLib typedef HMODULE dynlibType; #else typedef int dynlibType; #endif typedef wxX86InfoAndControlApp userinterface_type; //UserInterface * m_p_userinterface; userinterface_type * m_p_userinterface; dynlibType m_hmoduleUnstableVoltageDetectionDynLib; StartInstableVoltageDetectionFunctionPointer m_pfnStartInstableCPUcoreVoltageDetection; StopInstableVoltageDetectionFunctionPointer m_pfnStopInstableCPUcoreVoltageDetection; struct external_caller m_external_caller; condition_type m_conditionFindLowestStableVoltage; //http://forums.wxwidgets.org/viewtopic.php?t=4824: // wxMutex m_wxmutexFindLowestStableVoltage; // wxCondition m_wxconditionFindLowestStableVoltage; x86IandC::thread_type m_x86iandc_threadFindLowestStableVoltage; x86IandC::thread_type m_x86iandc_threadFindLowestStableCPUcoreOperationInDLL; unsigned m_uiNumberOfSecondsToWaitUntilVoltageIsReduced; //std::wstring m_std_wstrInstableCPUcoreVoltageDynLibPath; std::wstring m_std_wstrDynLibPath; // VoltageAndFreq m_lastSetVoltageAndFreq; //TODO if the reference clock changes after starting to find an unstable //CPU core voltage then (if the ref. clock in heightened) it can be still //instable. But on the other hand: if the calculation of the ref. clock is //inaccurate then it is better to set to the same multiplier as at start of //find lowest voltage. //Use separate values for both multi and ref clock rather than a single //composed value for the frequency. because the mult float m_lastSetCPUcoreMultiplier; float m_lastSetCPUcoreVoltageInVolt; float m_fReferenceClockInMHz; /** min CPU core usage for unstable CPU operation detection thread needed */ float m_fMinCPUcoreUsage; InstableCPUcoreOperationDetection(/*UserInterface * p_ui*/ CPUcoreData & r_cpucoredata); /** Must be virtual because else g++ warning: * `class InstableCPUcoreOperationDetection' has virtual functions * but non-virtual destructor */ virtual ~InstableCPUcoreOperationDetection() {} void CountSecondsDown(); float DecreaseVoltageStepByStep( unsigned wCPUcoreVoltageArrayIndex, const float fMultiplier); bool DynLibAccessInitialized() { return m_hmoduleUnstableVoltageDetectionDynLib && m_pfnStartInstableCPUcoreVoltageDetection && m_pfnStopInstableCPUcoreVoltageDetection; } void ExitFindLowestStableVoltageThread() { //Exit the "find lowest stable voltage" thread. m_vbExitFindLowestStableVoltage = true; // wxGetApp().m_wxconditionFindLowestStableVoltage.Signal(); LOGN( "signalling the condition to end finding the" " lowest stable voltage thread") //Wake up all threads waiting on the condition. m_conditionFindLowestStableVoltage.Broadcast(); LOGN( "after signalling the condition to end finding the" " lowest stable voltage thread") } virtual dynlibType LoadDynLib() = 0; bool DynLibSuccessFullyLoaded() { return m_hmoduleUnstableVoltageDetectionDynLib != NULL; } static DWORD THREAD_PROC_CALLING_CONVENTION FindLowestStableVoltage_ThreadProc( void * p_v ); DWORD FindLowestStableVoltage(); virtual /*ULONG64*/ unsigned long long GetThreadUserModeStartTime(/*void **/) = 0; virtual float GetCPUcoreUsageForDynLibThread() = 0; void HandleVoltageTooLow(); bool IsRunning() { return m_x86iandc_threadFindLowestStableVoltage.IsRunning(); } void SetStopRequestedViaGUI(bool b) { m_bStopFindingLowestStableCPUcoreVoltageRequestedViaUI = b; } void SetUserInterface(/*UserInterface * p_ui*/ userinterface_type * p_ui); const x86IandC::thread_type & StartInDynLibInSeparateThread(); void StartInDynLib(/*uint16_t m_ui32CPUcoreMask*/); /** Must be static as thread proc. */ static DWORD THREAD_PROC_CALLING_CONVENTION StartInDynLib_ThreadProc(void * p_v ); void Stop(); virtual void UnloadDynLib() = 0; void ShowMessage(const wchar_t * const msg); BYTE Start(); virtual StartInstableVoltageDetectionFunctionPointer AssignStartFunctionPointer() = 0; virtual StopInstableVoltageDetectionFunctionPointer AssignStopFunctionPointer() = 0; /** Called by "instable CPU core operation" dyn lib */ static void VoltageTooLow(); }; #endif /* INSTABLECPUCOREVOLTAGEDETECTION_HPP_ */
34.441989
88
0.796118
st-gb
9a5463c61acadf9034e5c0698b86f19004fbdeb8
949
cpp
C++
graphics-library/src/illumination/directional_light.cpp
thetorine/opengl3-library
3904d857fd1085ba2c57c4289eb0e0d123f11a14
[ "MIT" ]
null
null
null
graphics-library/src/illumination/directional_light.cpp
thetorine/opengl3-library
3904d857fd1085ba2c57c4289eb0e0d123f11a14
[ "MIT" ]
null
null
null
graphics-library/src/illumination/directional_light.cpp
thetorine/opengl3-library
3904d857fd1085ba2c57c4289eb0e0d123f11a14
[ "MIT" ]
null
null
null
#include <string> #include "engine/shader_controller.hpp" #include "illumination/directional_light.hpp" namespace gl::illumination { DirectionalLight::DirectionalLight(const glm::vec3 &dir, const glm::vec3 &color, float intensity) : m_dir(dir), m_color(color), m_intensity(intensity) { } DirectionalLight::~DirectionalLight() { } void DirectionalLight::setShaderParams(int index) { char buffer[22]; snprintf(buffer, sizeof(buffer), "directionalLights[%d]", index); std::string structName { buffer }; engine::ShaderController::getInstance()->setVec3(structName + ".dir", m_dir); engine::ShaderController::getInstance()->setVec3(structName + ".color", m_color); engine::ShaderController::getInstance()->setFloat(structName + ".intensity", m_intensity); engine::ShaderController::getInstance()->setInt(structName + ".on", true); } }
36.5
102
0.667018
thetorine
9a5bea3fff59bbd804be55fc3bae91234f087268
267
cpp
C++
Day2/zadanie2.cpp
majkel84/kurs_cpp_podstawowy
eddaffb310c6132304aa26dc87ec04ddfc09c541
[ "MIT" ]
1
2022-03-03T14:07:57.000Z
2022-03-03T14:07:57.000Z
Day2/zadanie2.cpp
majkel84/kurs_cpp_podstawowy
eddaffb310c6132304aa26dc87ec04ddfc09c541
[ "MIT" ]
2
2020-05-22T22:01:52.000Z
2020-05-30T09:24:42.000Z
Day2/zadanie2.cpp
majkel84/kurs_cpp_podstawowy
eddaffb310c6132304aa26dc87ec04ddfc09c541
[ "MIT" ]
null
null
null
#include <iostream> void foo(int* ptr) { *ptr = 10; } void bar(int* ptr) { *ptr = 20; } int main() { int number = 5; std::cout << number << '\n'; foo(&number); std::cout << number << '\n'; bar(&number); std::cout << number << '\n'; return 0; }
12.714286
30
0.505618
majkel84
9a5c8fa10db7b514eb5979e451ad60d3e6ff69a5
4,060
cpp
C++
ImdViewerV2/plugins/efbbox/efbbox.cpp
olivierchatry/iri3d
cae98c61d9257546d0fc81e69709297d04a17a14
[ "MIT" ]
2
2022-01-02T08:12:29.000Z
2022-02-12T22:15:11.000Z
ImdViewerV2/plugins/efbbox/efbbox.cpp
olivierchatry/iri3d
cae98c61d9257546d0fc81e69709297d04a17a14
[ "MIT" ]
null
null
null
ImdViewerV2/plugins/efbbox/efbbox.cpp
olivierchatry/iri3d
cae98c61d9257546d0fc81e69709297d04a17a14
[ "MIT" ]
1
2022-01-02T08:09:51.000Z
2022-01-02T08:09:51.000Z
#include "stdafx.h" #include "efbbox.h" #include "magic/MgcBox3.h" #include "magic/MgcVector3.h" static imdviewer_plugin_info_t plugins_info = { "Epifighter BoundingBox generator.", "Generate bounding box around bones.", "Chatry Oliver, Julien Barbier.", true // display box for octree. }; BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } void PluginEfBox::PluginDestroy() { if (_bbox) delete _bbox; _bbox = 0; _bbox_count = 0; } #define DEFAULT_FILE_NAME "\\bones_bbox.dat" #define NB_POINTS_PER_BBOX 8 #define NB_COORD_PER_POINT 3 void PluginEfBox::SaveToFile(const char *path) { int i; std::string file_name(path); file_name += DEFAULT_FILE_NAME; FILE *fd = fopen(file_name.c_str(), "wb"); if (fd == NULL) return; fwrite(&_bbox_count, sizeof(_bbox_count), 1, fd); for (i = 0; i < _bbox_count; i++) fwrite(&_bbox[i], sizeof(_bbox[i]), 1, fd); fclose(fd); } bool PluginEfBox::PluginGo(const char *path, imd2_object_t *object, imd2_bone_file_t *bones) { if (object == 0 || !object->imd2_object_header.have_skin) return false; PluginDestroy(); _bbox = new BoundingBox[object->imd2_object_header.num_bones]; _bbox_count = object->imd2_object_header.num_bones; for (int bi = 0; bi < _bbox_count; bi++) { std::vector<Mgc::Vector3> mesh_point; mesh_point.clear(); for (int mi = 0; mi < object->imd2_object_header.num_mesh; mi++) { imd2_mesh_t *mesh = object->imd2_mesh + mi; if (mesh->imd2_mesh_header.have_skin) { for (int vi = 0; vi < mesh->imd2_mesh_header.num_vertex; vi++) { imd2_skin_t *skin = mesh->imd2_skin + vi; imd2_vertex_t *vertex = mesh->imd2_vertex + vi; int bone_index = -1; float max_weight = 0.0f; for (int wi = 0; wi < skin->num_bones_assigned; wi++) { imd2_weight_t *weight = skin->weight + wi; if (weight->weight > max_weight) { bone_index = weight->bone_index; max_weight = weight->weight; } } if (bone_index != -1 && bone_index == bi) { Mgc::Vector3 v(vertex->pos); mesh_point.push_back(v); } } } } size_t count = mesh_point.size(); Mgc::Vector3 *pt = new Mgc::Vector3[count]; for (size_t i = 0; i < count; ++i) pt[i] = mesh_point[i]; // compute bounding box. Mgc::Box3 magic_bbox; BoundingBox *bbox = _bbox + bi; if (mesh_point.size() > 0) { bbox->box = ContOrientedBox((int)mesh_point.size(), pt); bbox->bone_index = bi; } else bbox->bone_index = -1; delete pt; } SaveToFile(path); return false; } void PluginEfBox::PluginInit() { _bbox = 0; _bbox_count = 0; } void PluginEfBox::PluginRender(unsigned int current_anim, imd2_bone_file_t *bones) { for (int i = 0; i < _bbox_count; ++i) { BoundingBox *bbox = _bbox + i; int pair[] = {3, 2, 2, 1, 1, 0, 0, 3, 1, 5, 2, 6, 3, 7, 0, 4, 4, 7, 7, 6, 6, 5, 5, 4}; Mgc::Vector3 p[8]; bbox->box.ComputeVertices(p); // search for bone index glPushMatrix(); if (bones) for (int i = 0; i < bones->imd2_bone_file_header.bone_count; ++i) { if (bones->bones[i].imd2_bone_header.bone_index == bbox->bone_index) { glMultMatrixf(bones->bones[i].imd2_bone_anim[current_anim].matrix); continue; } } glBegin(GL_LINES); for (int i = 0; i < 24; i += 2) { glVertex3fv(p[pair[i]]); glVertex3fv(p[pair[i + 1]]); } glEnd(); glPopMatrix(); } } DLLAPI imdviewer_plugin_info_t *GetPluginInfo() { return &plugins_info; } DLLAPI ImdViewerPlugins *CreateInstance() { return new PluginEfBox; }
25.061728
92
0.599015
olivierchatry
9a5e005d2f388ea2c62ff109bd5bc7fc4f0d0c44
8,320
cpp
C++
source/examples/states/main.cpp
citron0xa9/globjects
53a1de45f3c177fbd805610f274d3ffb1b97843a
[ "MIT" ]
null
null
null
source/examples/states/main.cpp
citron0xa9/globjects
53a1de45f3c177fbd805610f274d3ffb1b97843a
[ "MIT" ]
null
null
null
source/examples/states/main.cpp
citron0xa9/globjects
53a1de45f3c177fbd805610f274d3ffb1b97843a
[ "MIT" ]
2
2020-10-01T04:10:51.000Z
2021-07-01T07:45:45.000Z
#include <iostream> #include <algorithm> #include <cpplocate/cpplocate.h> #include <cpplocate/ModuleInfo.h> #include <glm/vec2.hpp> #include <glbinding/gl/gl.h> #include <glbinding/ContextInfo.h> #include <glbinding/Version.h> #include <GLFW/glfw3.h> #include <globjects/globjects.h> #include <globjects/base/File.h> #include <globjects/logging.h> #include <globjects/Buffer.h> #include <globjects/Program.h> #include <globjects/Shader.h> #include <globjects/VertexArray.h> #include <globjects/VertexAttributeBinding.h> #include <globjects/State.h> #include "datapath.inl" using namespace gl; namespace { std::unique_ptr<globjects::Program> g_shaderProgram = nullptr; std::unique_ptr<globjects::File> g_vertexShaderSource = nullptr; std::unique_ptr<globjects::AbstractStringSource> g_vertexShaderTemplate = nullptr; std::unique_ptr<globjects::Shader> g_vertexShader = nullptr; std::unique_ptr<globjects::File> g_fragmentShaderSource = nullptr; std::unique_ptr<globjects::AbstractStringSource> g_fragmentShaderTemplate = nullptr; std::unique_ptr<globjects::Shader> g_fragmentShader = nullptr; std::unique_ptr<globjects::VertexArray> g_vao = nullptr; std::unique_ptr<globjects::Buffer> g_buffer = nullptr; std::unique_ptr<globjects::State> g_thinnestPointSizeState = nullptr; std::unique_ptr<globjects::State> g_thinPointSizeState = nullptr; std::unique_ptr<globjects::State> g_normalPointSizeState = nullptr; std::unique_ptr<globjects::State> g_thickPointSizeState = nullptr; std::unique_ptr<globjects::State> g_disableRasterizerState = nullptr; std::unique_ptr<globjects::State> g_enableRasterizerState = nullptr; std::unique_ptr<globjects::State> g_defaultPointSizeState = nullptr; auto g_size = glm::ivec2{}; } void initialize() { // Initialize OpenGL objects g_defaultPointSizeState = globjects::State::create(); g_defaultPointSizeState->pointSize(globjects::getFloat(GL_POINT_SIZE)); g_thinnestPointSizeState = globjects::State::create(); g_thinnestPointSizeState->pointSize(2.0f); g_thinPointSizeState = globjects::State::create(); g_thinPointSizeState->pointSize(5.0f); g_normalPointSizeState = globjects::State::create(); g_normalPointSizeState->pointSize(10.0f); g_thickPointSizeState = globjects::State::create(); g_thickPointSizeState->pointSize(20.0f); g_disableRasterizerState = globjects::State::create(); g_disableRasterizerState->enable(GL_RASTERIZER_DISCARD); g_enableRasterizerState = globjects::State::create(); g_enableRasterizerState->disable(GL_RASTERIZER_DISCARD); g_vao = globjects::VertexArray::create(); g_buffer = globjects::Buffer::create(); g_shaderProgram = globjects::Program::create(); const auto dataPath = common::retrieveDataPath("globjects", "dataPath"); g_vertexShaderSource = globjects::Shader::sourceFromFile(dataPath + "states/standard.vert"); g_vertexShaderTemplate = globjects::Shader::applyGlobalReplacements(g_vertexShaderSource.get()); g_vertexShader = globjects::Shader::create(GL_VERTEX_SHADER, g_vertexShaderTemplate.get()); g_fragmentShaderSource = globjects::Shader::sourceFromFile(dataPath + "states/standard.frag"); g_fragmentShaderTemplate = globjects::Shader::applyGlobalReplacements(g_fragmentShaderSource.get()); g_fragmentShader = globjects::Shader::create(GL_FRAGMENT_SHADER, g_fragmentShaderTemplate.get()); g_shaderProgram->attach(g_vertexShader.get(), g_fragmentShader.get()); static auto data = std::vector<glm::vec2>(); if (data.empty()) { for (auto y = 0.8f; y > -1.f; y -= 0.2f) for (auto x = -0.8f; x < 1.f; x += 0.4f) data.push_back(glm::vec2(x, y)); } g_buffer->setData(data, GL_STATIC_DRAW ); g_vao->binding(0)->setAttribute(0); g_vao->binding(0)->setBuffer(g_buffer.get(), 0, sizeof(glm::vec2)); g_vao->binding(0)->setFormat(2, GL_FLOAT); g_vao->enable(0); } void deinitialize() { g_shaderProgram.reset(nullptr); g_vertexShaderSource.reset(nullptr); g_vertexShaderTemplate.reset(nullptr); g_vertexShader.reset(nullptr); g_fragmentShaderSource.reset(nullptr); g_fragmentShaderTemplate.reset(nullptr); g_fragmentShader.reset(nullptr); g_vao.reset(nullptr); g_buffer.reset(nullptr); g_thinnestPointSizeState.reset(nullptr); g_thinPointSizeState.reset(nullptr); g_normalPointSizeState.reset(nullptr); g_thickPointSizeState.reset(nullptr); g_disableRasterizerState.reset(nullptr); g_enableRasterizerState.reset(nullptr); g_defaultPointSizeState.reset(nullptr); } void draw() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glViewport(0, 0, g_size.x, g_size.y); g_shaderProgram->use(); g_defaultPointSizeState->apply(); g_vao->drawArrays(GL_POINTS, 0, 5); g_thinnestPointSizeState->apply(); g_vao->drawArrays(GL_POINTS, 5, 5); g_thinPointSizeState->apply(); g_vao->drawArrays(GL_POINTS, 10, 5); g_normalPointSizeState->apply(); g_vao->drawArrays(GL_POINTS, 15, 5); g_thickPointSizeState->apply(); g_vao->drawArrays(GL_POINTS, 20, 1); g_disableRasterizerState->apply(); g_vao->drawArrays(GL_POINTS, 21, 1); g_enableRasterizerState->apply(); g_vao->drawArrays(GL_POINTS, 22, 1); g_disableRasterizerState->apply(); g_vao->drawArrays(GL_POINTS, 23, 1); g_enableRasterizerState->apply(); g_vao->drawArrays(GL_POINTS, 24, 1); g_normalPointSizeState->apply(); g_vao->drawArrays(GL_POINTS, 25, 5); g_thinPointSizeState->apply(); g_vao->drawArrays(GL_POINTS, 30, 5); g_thinnestPointSizeState->apply(); g_vao->drawArrays(GL_POINTS, 35, 5); g_defaultPointSizeState->apply(); g_vao->drawArrays(GL_POINTS, 35, 5); g_shaderProgram->release(); } void error(int errnum, const char * errmsg) { globjects::critical() << errnum << ": " << errmsg << std::endl; } void framebuffer_size_callback(GLFWwindow * /*window*/, int width, int height) { g_size = glm::ivec2{ width, height }; } void key_callback(GLFWwindow * window, int key, int /*scancode*/, int action, int /*modes*/) { if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) glfwSetWindowShouldClose(window, true); if (key == GLFW_KEY_F5 && action == GLFW_RELEASE) { g_vertexShaderSource->reload(); g_fragmentShaderSource->reload(); } } int main(int /*argc*/, char * /*argv*/[]) { // Initialize GLFW if (!glfwInit()) return 1; glfwSetErrorCallback(error); glfwDefaultWindowHints(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true); // Create a context and, if valid, make it current GLFWwindow * window = glfwCreateWindow(640, 480, "globjects States", NULL, NULL); if (window == nullptr) { globjects::critical() << "Context creation failed. Terminate execution."; glfwTerminate(); return -1; } glfwSetKeyCallback(window, key_callback); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwMakeContextCurrent(window); // Initialize globjects (internally initializes glbinding, and registers the current context) globjects::init(); std::cout << std::endl << "OpenGL Version: " << glbinding::ContextInfo::version() << std::endl << "OpenGL Vendor: " << glbinding::ContextInfo::vendor() << std::endl << "OpenGL Renderer: " << glbinding::ContextInfo::renderer() << std::endl << std::endl; globjects::info() << "Press F5 to reload shaders." << std::endl << std::endl; glfwGetFramebufferSize(window, &g_size[0], &g_size[1]); initialize(); // Main loop while (!glfwWindowShouldClose(window)) { glfwPollEvents(); draw(); glfwSwapBuffers(window); } deinitialize(); // Properly shutdown GLFW glfwTerminate(); return 0; }
32.885375
105
0.683774
citron0xa9
9a5f5c33216fd13f253f598c1e49cd75cc8c66df
559
cpp
C++
dev/assem.cpp
jordanjohnston/manseglib
00723792c9b16f6518e25095569d77f2ed7b6d22
[ "MIT" ]
null
null
null
dev/assem.cpp
jordanjohnston/manseglib
00723792c9b16f6518e25095569d77f2ed7b6d22
[ "MIT" ]
null
null
null
dev/assem.cpp
jordanjohnston/manseglib
00723792c9b16f6518e25095569d77f2ed7b6d22
[ "MIT" ]
1
2020-06-09T18:48:14.000Z
2020-06-09T18:48:14.000Z
#include <iostream> #include "../manseglib.hpp" int main() { constexpr int size = 1000; ManSeg::ManSegArray a(size); ManSeg::ManSegArray b(size); // double a[size]; // double b[size]; std::cout << "filling\n"; for(int i = 0; i < size; ++i) { b.pairs[i] = 0; a.pairs[i] = i; } std::cout << "now copying\n"; for(int i = 0; i < size; ++i) { for(int j = 0; j < size; ++j) b.pairs[i] += a.pairs[j]; } std::cout << "finished copying\n"; for(int i = 0; i < size; ++i) std::cout << b.pairs[i] << " "; std::cout << std::endl; return 0; }
17.46875
57
0.543828
jordanjohnston
9a602f9f5123a3670e8b693e3b9852c589b22c54
30
cpp
C++
src/expression.cpp
koraxkorakos/mv
b5f589bd089fd05fde7a0837f39746e2e343499e
[ "BSD-2-Clause" ]
null
null
null
src/expression.cpp
koraxkorakos/mv
b5f589bd089fd05fde7a0837f39746e2e343499e
[ "BSD-2-Clause" ]
null
null
null
src/expression.cpp
koraxkorakos/mv
b5f589bd089fd05fde7a0837f39746e2e343499e
[ "BSD-2-Clause" ]
null
null
null
//#include <mv/expression.hpp>
30
30
0.733333
koraxkorakos
9a6070ae0d84e05add8020fe843e371cff24d5a0
16,062
cpp
C++
src/cpm_BaseParaManager_MPI.cpp
jorji/CPMlib
7ba683d1abc60f11bafcc5732da831278b002afa
[ "BSD-2-Clause" ]
4
2015-03-17T17:30:10.000Z
2019-01-31T15:13:59.000Z
src/cpm_BaseParaManager_MPI.cpp
jorji/CPMlib
7ba683d1abc60f11bafcc5732da831278b002afa
[ "BSD-2-Clause" ]
null
null
null
src/cpm_BaseParaManager_MPI.cpp
jorji/CPMlib
7ba683d1abc60f11bafcc5732da831278b002afa
[ "BSD-2-Clause" ]
4
2015-12-09T02:42:29.000Z
2022-03-18T09:03:28.000Z
/* ################################################################################### # # CPMlib - Computational space Partitioning Management library # # Copyright (c) 2012-2014 Institute of Industrial Science (IIS), The University of Tokyo. # All rights reserved. # # Copyright (c) 2014-2016 Advanced Institute for Computational Science (AICS), RIKEN. # All rights reserved. # # Copyright (c) 2016-2017 Research Institute for Information Technology (RIIT), Kyushu University. # All rights reserved. # ################################################################################### */ /** * @file cpm_BaseParaManager_MPI.cpp * パラレルマネージャクラスのMPIインターフェイス関数ソースファイル * @date 2012/05/31 */ #include "stdlib.h" #include "cpm_BaseParaManager.h" #if !defined(_WIN32) && !defined(WIN32) #include <unistd.h> // for gethostname() of FX10/K #endif //////////////////////////////////////////////////////////////////////////////// // MPI_Datatypeを取得 MPI_Datatype cpm_BaseParaManager::GetMPI_Datatype(int datatype) { if( datatype == CPM_REAL ) { if( RealIsDouble() ) return MPI_DOUBLE; return MPI_FLOAT; } else if( datatype == CPM_CHAR ) return MPI_CHAR; else if( datatype == CPM_SHORT ) return MPI_SHORT; else if( datatype == CPM_INT ) return MPI_INT; else if( datatype == CPM_LONG ) return MPI_LONG; else if( datatype == CPM_FLOAT ) return MPI_FLOAT; else if( datatype == CPM_DOUBLE ) return MPI_DOUBLE; else if( datatype == CPM_LONG_DOUBLE ) return MPI_LONG_DOUBLE; else if( datatype == CPM_UNSIGNED_CHAR ) return MPI_UNSIGNED_CHAR; else if( datatype == CPM_UNSIGNED_SHORT ) return MPI_UNSIGNED_SHORT; else if( datatype == CPM_UNSIGNED ) return MPI_UNSIGNED; else if( datatype == CPM_UNSIGNED_LONG ) return MPI_UNSIGNED_LONG; #ifdef MPI_LONG_LONG_INT else if( datatype == CPM_LONG_LONG_INT ) return MPI_LONG_LONG_INT; #endif #ifdef MPI_LONG_LONG else if( datatype == CPM_LONG_LONG ) return MPI_LONG_LONG; #endif #ifdef MPI_UNSIGNED_LONG_LONG else if( datatype == CPM_UNSIGNED_LONG_LONG ) return MPI_UNSIGNED_LONG_LONG; #endif return MPI_DATATYPE_NULL; } //////////////////////////////////////////////////////////////////////////////// // MPI_Opを取得 MPI_Op cpm_BaseParaManager::GetMPI_Op(int op) { if ( op == CPM_MAX ) return MPI_MAX; else if( op == CPM_MIN ) return MPI_MIN; else if( op == CPM_SUM ) return MPI_SUM; else if( op == CPM_PROD ) return MPI_PROD; else if( op == CPM_LAND ) return MPI_LAND; else if( op == CPM_BAND ) return MPI_BAND; else if( op == CPM_LOR ) return MPI_LOR; else if( op == CPM_BOR ) return MPI_BOR; else if( op == CPM_LXOR ) return MPI_LXOR; else if( op == CPM_BXOR ) return MPI_BXOR; // else if( op == CPM_MINLOC ) return CPM_MINLOC; // not support // else if( op == CPM_MAXLOC ) return CPM_MAXLOC; // not support return MPI_OP_NULL; } //////////////////////////////////////////////////////////////////////////////// // ランク番号の取得 int cpm_BaseParaManager::GetMyRankID( int procGrpNo ) { // 不正なプロセスグループ番号 if( procGrpNo < 0 || procGrpNo >= int(m_procGrpList.size()) ) { // プロセスグループが存在しない return getRankNull(); } // コミュニケータをチェック MPI_Comm comm = m_procGrpList[procGrpNo]; if( IsCommNull(comm) ) { // プロセスグループに自ランクが含まれない return getRankNull(); } // ランク番号を取得 int rankNo; MPI_Comm_rank( comm, &rankNo ); // ランク番号 return rankNo; } //////////////////////////////////////////////////////////////////////////////// // ランク数の取得 int cpm_BaseParaManager::GetNumRank( int procGrpNo ) { // 不正なプロセスグループ番号 if( procGrpNo < 0 || procGrpNo >= int(m_procGrpList.size()) ) { // プロセスグループが存在しない return -1; } // コミュニケータをチェック MPI_Comm comm = m_procGrpList[procGrpNo]; if( IsCommNull(comm) ) { // プロセスグループに自ランクが含まれない return -1; } // ランク数を取得 int nrank; MPI_Comm_size( comm, &nrank ); // ランク数 return nrank; } //////////////////////////////////////////////////////////////////////////////// // ホスト名の取得 std::string cpm_BaseParaManager::GetHostName() { char name[512]; memset(name, 0x00, sizeof(char)*512); if( gethostname(name, 512) != 0 ) return std::string(""); return std::string(name); } //////////////////////////////////////////////////////////////////////////////// // コミュニケータの取得 MPI_Comm cpm_BaseParaManager::GetMPI_Comm( int procGrpNo ) { // 不正なプロセスグループ番号 if( procGrpNo < 0 || procGrpNo >= int(m_procGrpList.size()) ) { // プロセスグループが存在しない return getCommNull(); } return m_procGrpList[procGrpNo]; } //////////////////////////////////////////////////////////////////////////////// // Abort void cpm_BaseParaManager::Abort( int errorcode ) { // MPI_Abort MPI_Abort(MPI_COMM_WORLD, errorcode); exit(errorcode); } //////////////////////////////////////////////////////////////////////////////// // Barrier cpm_ErrorCode cpm_BaseParaManager::Barrier( int procGrpNo ) { // コミュニケータを取得 MPI_Comm comm = GetMPI_Comm( procGrpNo ); if( IsCommNull( comm ) ) { // プロセスグループが存在しない return CPM_ERROR_NOT_IN_PROCGROUP; } // MPI_Barrier if( MPI_Barrier(comm) != MPI_SUCCESS ) { return CPM_ERROR_MPI_BARRIER; } return CPM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // Wait cpm_ErrorCode cpm_BaseParaManager::Wait( MPI_Request *request ) { if( !request ) { return CPM_ERROR_INVALID_PTR; } if( *request == MPI_REQUEST_NULL ) { return CPM_ERROR_MPI_INVALID_REQUEST; } // MPI_Wait MPI_Status status; if( MPI_Wait( request, &status ) != MPI_SUCCESS ) { return CPM_ERROR_MPI_WAIT; } return CPM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // Waitall cpm_ErrorCode cpm_BaseParaManager::Waitall( int count, MPI_Request requests[] ) { // status int cnt = 0; MPI_Status *stat = new MPI_Status[count]; MPI_Request *req = new MPI_Request[count]; for( int i=0;i<count;i++ ) { if( requests[i] != MPI_REQUEST_NULL ) req[cnt++] = requests[i]; } if( cnt == 0 ) { delete [] stat; delete [] req; return CPM_SUCCESS; } // MPI_Waitall if( MPI_Waitall( cnt, req, stat ) != MPI_SUCCESS ) { delete [] stat; delete [] req; return CPM_ERROR_MPI_WAITALL; } delete [] stat; delete [] req; return CPM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // Bcast(MPI_Datatype指定) cpm_ErrorCode cpm_BaseParaManager::Bcast( MPI_Datatype dtype, void *buf, int count, int root, int procGrpNo ) { if( !buf ) { return CPM_ERROR_INVALID_PTR; } // コミュニケータを取得 MPI_Comm comm = GetMPI_Comm(procGrpNo); if( IsCommNull(comm) ) { // プロセスグループが存在しない return CPM_ERROR_NOT_IN_PROCGROUP; } // MPI_Bcast if( MPI_Bcast( buf, count, dtype, root, comm ) != MPI_SUCCESS ) { return CPM_ERROR_MPI_BCAST; } return CPM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // Send(MPI_Datatype指定) cpm_ErrorCode cpm_BaseParaManager::Send( MPI_Datatype dtype, void *buf, int count, int dest, int procGrpNo ) { if( !buf ) { return CPM_ERROR_INVALID_PTR; } // コミュニケータを取得 MPI_Comm comm = GetMPI_Comm(procGrpNo); if( IsCommNull(comm) ) { // プロセスグループが存在しない return CPM_ERROR_NOT_IN_PROCGROUP; } // MPI_Send int tag = 1; if( MPI_Send( buf, count, dtype, dest, tag, comm ) != MPI_SUCCESS ) { return CPM_ERROR_MPI_SEND; } return CPM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // Recv(MPI_Datatype指定) cpm_ErrorCode cpm_BaseParaManager::Recv( MPI_Datatype dtype, void *buf, int count, int source, int procGrpNo ) { if( !buf ) { return CPM_ERROR_INVALID_PTR; } // コミュニケータを取得 MPI_Comm comm = GetMPI_Comm(procGrpNo); if( IsCommNull(comm) ) { // プロセスグループが存在しない return CPM_ERROR_NOT_IN_PROCGROUP; } // MPI_Send int tag = 1; MPI_Status status; if( MPI_Recv( buf, count, dtype, source, tag, comm, &status ) != MPI_SUCCESS ) { return CPM_ERROR_MPI_SEND; } return CPM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // Isend(MPI_Datatype指定) cpm_ErrorCode cpm_BaseParaManager::Isend( MPI_Datatype dtype, void *buf, int count, int dest, MPI_Request *request, int procGrpNo ) { if( !buf || !request ) { return CPM_ERROR_INVALID_PTR; } *request = MPI_REQUEST_NULL; // コミュニケータを取得 MPI_Comm comm = GetMPI_Comm(procGrpNo); if( IsCommNull(comm) ) { // プロセスグループが存在しない return CPM_ERROR_NOT_IN_PROCGROUP; } // MPI_Isend int tag = 1; if( MPI_Isend( buf, count, dtype, dest, tag, comm, request ) != MPI_SUCCESS ) { return CPM_ERROR_MPI_ISEND; } return CPM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // Irecv(MPI_Datatype指定) cpm_ErrorCode cpm_BaseParaManager::Irecv( MPI_Datatype dtype, void *buf, int count, int source, MPI_Request *request, int procGrpNo ) { if( !buf || !request ) { return CPM_ERROR_INVALID_PTR; } *request = MPI_REQUEST_NULL; // コミュニケータを取得 MPI_Comm comm = GetMPI_Comm(procGrpNo); if( IsCommNull(comm) ) { // プロセスグループが存在しない return CPM_ERROR_NOT_IN_PROCGROUP; } // MPI_Irecv int tag = 1; if( MPI_Irecv( buf, count, dtype, source, tag, comm, request ) != MPI_SUCCESS ) { return CPM_ERROR_MPI_IRECV; } return CPM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // Allreduce(MPI_Datatype指定) cpm_ErrorCode cpm_BaseParaManager::Allreduce( MPI_Datatype dtype, void *sendbuf, void *recvbuf, int count, MPI_Op op, int procGrpNo ) { if( !sendbuf || !recvbuf ) { return CPM_ERROR_INVALID_PTR; } // コミュニケータを取得 MPI_Comm comm = GetMPI_Comm(procGrpNo); if( IsCommNull(comm) ) { // プロセスグループが存在しない return CPM_ERROR_NOT_IN_PROCGROUP; } // MPI_Allreduce if( MPI_Allreduce( sendbuf, recvbuf, count, dtype, op, comm ) != MPI_SUCCESS ) { return CPM_ERROR_MPI_ALLREDUCE; } return CPM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // Gather(MPI_Datatype指定) cpm_ErrorCode cpm_BaseParaManager::Gather( MPI_Datatype stype, void *sendbuf, int sendcnt , MPI_Datatype rtype, void *recvbuf, int recvcnt , int root, int procGrpNo ) { if( !sendbuf || !recvbuf ) { return CPM_ERROR_INVALID_PTR; } //コミュニケータを取得 MPI_Comm comm = GetMPI_Comm(procGrpNo); if( IsCommNull(comm) ) { // プロセスグループが存在しない return CPM_ERROR_NOT_IN_PROCGROUP; } // MPI_Gather if( MPI_Gather( sendbuf, sendcnt, stype, recvbuf, recvcnt, rtype, root, comm ) != MPI_SUCCESS ) { return CPM_ERROR_MPI_GATHER; } return CPM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // Allgather(MPI_Datatype指定) cpm_ErrorCode cpm_BaseParaManager::Allgather( MPI_Datatype stype, void *sendbuf, int sendcnt , MPI_Datatype rtype, void *recvbuf, int recvcnt , int procGrpNo ) { if( !sendbuf || !recvbuf ) { return CPM_ERROR_INVALID_PTR; } //コミュニケータを取得 MPI_Comm comm = GetMPI_Comm(procGrpNo); if( IsCommNull(comm) ) { // プロセスグループが存在しない return CPM_ERROR_NOT_IN_PROCGROUP; } // MPI_Allaather if( MPI_Allgather( sendbuf, sendcnt, stype, recvbuf, recvcnt, rtype, comm ) != MPI_SUCCESS ) { return CPM_ERROR_MPI_ALLGATHER; } return CPM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // Gatherv(MPI_Datatype指定) cpm_ErrorCode cpm_BaseParaManager::Gatherv( MPI_Datatype stype, void *sendbuf, int sendcnt , MPI_Datatype rtype, void *recvbuf, int *recvcnts , int *displs, int root, int procGrpNo ) { if( !sendbuf || !recvbuf || !recvcnts || !displs ) { return CPM_ERROR_INVALID_PTR; } //コミュニケータを取得 MPI_Comm comm = GetMPI_Comm(procGrpNo); if( IsCommNull(comm) ) { // プロセスグループが存在しない return CPM_ERROR_NOT_IN_PROCGROUP; } // MPI_Gather if( MPI_Gatherv( sendbuf, sendcnt, stype, recvbuf, recvcnts, displs , rtype, root, comm ) != MPI_SUCCESS ) { return CPM_ERROR_MPI_GATHERV; } return CPM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // Allgatherv(MPI_Datatype指定) cpm_ErrorCode cpm_BaseParaManager::Allgatherv( MPI_Datatype stype, void *sendbuf, int sendcnt , MPI_Datatype rtype, void *recvbuf, int *recvcnts , int *displs, int procGrpNo ) { if( !sendbuf || !recvbuf || !recvcnts || !displs ) { return CPM_ERROR_INVALID_PTR; } // コミュニケータを取得 MPI_Comm comm = GetMPI_Comm(procGrpNo); if( IsCommNull(comm) ) { // プロセスグループが存在しない return CPM_ERROR_NOT_IN_PROCGROUP; } // MPI_Allaather if( MPI_Allgatherv( sendbuf, sendcnt, stype, recvbuf, recvcnts, displs, rtype, comm ) != MPI_SUCCESS ) { return CPM_ERROR_MPI_ALLGATHERV; } return CPM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // cpm_Wait cpm_ErrorCode cpm_BaseParaManager::cpm_Wait( int reqNo ) { // MPI_Request MPI_Request *req = m_reqList.Get(reqNo); if( !req ) { return CPM_ERROR_INVALID_OBJKEY; } // MPI_Wait MPI_Status status; if( MPI_Wait( req, &status ) != MPI_SUCCESS ) { return CPM_ERROR_MPI_WAIT; } // 削除 return m_reqList.Delete(reqNo); } //////////////////////////////////////////////////////////////////////////////// // cpm_Waitall cpm_ErrorCode cpm_BaseParaManager::cpm_Waitall( int count, int reqNoList[] ) { // MPI_Request MPI_Status* stat = new MPI_Status [count]; MPI_Request* req = new MPI_Request[count]; int cnt = 0; for( int i=0;i<count;i++ ) { MPI_Request *r = m_reqList.Get( reqNoList[i] ); if( r ) { r[cnt++] = *req; } } if( cnt == 0 ) { delete [] stat; delete [] req; return CPM_ERROR_INVALID_OBJKEY; } // MPI_Waitall if( MPI_Waitall( cnt, req, stat ) != MPI_SUCCESS ) { delete [] stat; delete [] req; return CPM_ERROR_MPI_WAITALL; } // 削除 for( int i=0;i<count;i++ ) { m_reqList.Delete( reqNoList[i] ); } return CPM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // cpm_Isend cpm_ErrorCode cpm_BaseParaManager::cpm_Isend( void *buf, int count, int datatype, int dest, int *reqNo, int procGrpNo ) { // MPI_Datatype MPI_Datatype dtype = cpm_BaseParaManager::GetMPI_Datatype( datatype ); if( dtype == MPI_DATATYPE_NULL ) { return CPM_ERROR_MPI_INVALID_DATATYPE; } // MPI_Request MPI_Request *req = m_reqList.Create(); if( !req ) { return CPM_ERROR_INVALID_PTR; } // Isend cpm_ErrorCode ret = Isend( dtype, buf, count, dest, req, procGrpNo ); if( ret != MPI_SUCCESS ) { delete req; return ret; } // MPI_Requestを登録 if( (*reqNo = m_reqList.Add(req) ) < 0 ) { delete req; return CPM_ERROR_REGIST_OBJKEY; } return CPM_SUCCESS; } //////////////////////////////////////////////////////////////////////////////// // cpm_Irecv cpm_ErrorCode cpm_BaseParaManager::cpm_Irecv( void *buf, int count, int datatype, int source, int *reqNo, int procGrpNo ) { // MPI_Datatype MPI_Datatype dtype = cpm_BaseParaManager::GetMPI_Datatype( datatype ); if( dtype == MPI_DATATYPE_NULL ) { return CPM_ERROR_MPI_INVALID_DATATYPE; } // Irecv MPI_Request req; cpm_ErrorCode ret = Irecv( dtype, buf, count, source, &req, procGrpNo ); if( ret != MPI_SUCCESS ) { return ret; } // MPI_Requestを登録 MPI_Request *r = m_reqList.Create(); *r = req; if( (*reqNo = m_reqList.Add(r) ) < 0 ) { delete r; return CPM_ERROR_REGIST_OBJKEY; } return CPM_SUCCESS; }
23.86627
119
0.577886
jorji
9a666e5b485039da1cb223c3e70bf30f808f2da4
28
cpp
C++
DataStructures/Src/Precompiled.cpp
ikarusx/ModernCpp
8c0111dec2d0a2a183250e2f9594573b99687ec5
[ "MIT" ]
null
null
null
DataStructures/Src/Precompiled.cpp
ikarusx/ModernCpp
8c0111dec2d0a2a183250e2f9594573b99687ec5
[ "MIT" ]
null
null
null
DataStructures/Src/Precompiled.cpp
ikarusx/ModernCpp
8c0111dec2d0a2a183250e2f9594573b99687ec5
[ "MIT" ]
null
null
null
#include "Precompiled.hpp"
9.333333
26
0.75
ikarusx
9a6726017803c35221f177ec07786cb6a428563f
10,074
cpp
C++
coh2_rgt_extractor/Rainman_src/CRgdHashTable.cpp
tranek/coh2_rgt_extractor
dba2db9a06d3f31fb815ca865181d8f631306522
[ "MIT" ]
1
2016-09-24T14:57:56.000Z
2016-09-24T14:57:56.000Z
coh2_rgt_extractor/Rainman_src/CRgdHashTable.cpp
tranek/coh2_rgt_extractor
dba2db9a06d3f31fb815ca865181d8f631306522
[ "MIT" ]
null
null
null
coh2_rgt_extractor/Rainman_src/CRgdHashTable.cpp
tranek/coh2_rgt_extractor
dba2db9a06d3f31fb815ca865181d8f631306522
[ "MIT" ]
null
null
null
/* Rainman Library Copyright (C) 2006 Corsix <corsix@gmail.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "CRgdHashTable.h" #include "memdebug.h" #include "Exception.h" extern "C" { typedef unsigned long int ub4; /* unsigned 4-byte quantities */ typedef unsigned char ub1; ub4 hash(ub1 * k,ub4 length,ub4 initval); ub4 hash3(ub1 * k,ub4 length,ub4 initval); } static char* mystrdup(const char* sStr) { char* s = new char[strlen(sStr) + 1]; if(s == 0) return 0; strcpy(s, sStr); return s; } CRgdHashTable::CRgdHashTable(void) { for(int i = 1; i < 10000; ++i) { char sBuf[24]; _Value Val; Val.bCustom = false; Val.sString = CHECK_MEM(mystrdup(itoa(i,sBuf,10))); m_mHashTable[hash((ub1*)sBuf, (ub4) strlen(sBuf), 0)] = Val; } } CRgdHashTable::~CRgdHashTable(void) { _Clean(); } void CRgdHashTable::New() { _Clean(); } void CRgdHashTable::FillUnknownList(std::vector<unsigned long>& oList) { for(std::map<unsigned long, CRgdHashTable::_Value>::iterator itr = m_mHashTable.begin(); itr != m_mHashTable.end(); ++itr) { if(itr->second.sString == 0) oList.push_back(itr->first); } } static char* fgetline(FILE *f, unsigned int iInitSize = 32) { unsigned int iTotalLen; if(f == 0) throw new CRainmanException(__FILE__, __LINE__, "No file"); if(iInitSize < 4) iInitSize = 4; iTotalLen = iInitSize; char *sBuffer = new char[iInitSize]; char *sReadTo = sBuffer; if(sBuffer == 0) throw new CRainmanException(0, __FILE__, __LINE__, "Failed to allocate %u", iInitSize); do { if(fgets(sReadTo, iInitSize, f) == 0) { if(feof(f)) { if(sReadTo[strlen(sReadTo) - 1] == '\n') sReadTo[strlen(sReadTo) - 1] = 0; return sBuffer; } delete[] sBuffer; throw new CRainmanException(__FILE__, __LINE__, "Failed to read string"); } if(sReadTo[strlen(sReadTo) - 1] == '\n') { size_t n = strlen(sReadTo) - 1; sReadTo[n] = 0; while(n > 0) { --n; if(sReadTo[n] == '\n' || sReadTo[n] == '\r') sReadTo[n] = 0; else break; } return sBuffer; } iTotalLen += iInitSize; char *sTmp = new char[iTotalLen]; if(sTmp == 0) { delete[] sBuffer; throw new CRainmanException(0, __FILE__, __LINE__, "Failed to allocate %u", iTotalLen); } strcpy(sTmp, sBuffer); delete[] sBuffer; sBuffer = sTmp; sReadTo = sBuffer + strlen(sBuffer); }while(1); } void CRgdHashTable::ExtendWithDictionary(const char* sFile, bool bCustom) { FILE *fFile = fopen(sFile, "rb"); if(fFile == 0) throw new CRainmanException(0, __FILE__, __LINE__, "Failed to open file \'%s\'", sFile); while(!feof(fFile)) { char* sLine; try { sLine = fgetline(fFile); } catch(CRainmanException* pE) { fclose(fFile); throw new CRainmanException(__FILE__, __LINE__, "Failed to read line", pE); } char *sBaseLine = sLine; bool bUnk = false; if( (strncmp(sLine, "# 0x", 4) == 0) && (strncmp(sLine + 12, " is an unknown value!!", 22) == 0)) { bUnk = true; sLine[0] = ' '; sLine[12] = '='; } if(sLine[0] != '#') { unsigned long iKey = 0; int iBitsRead = -8; // Read in key while((*sLine != '=') && *sLine) { if(iBitsRead == -8) { if(*sLine == '0') iBitsRead = -4; } else if(iBitsRead == -4) { if(*sLine == 'x' || *sLine == 'X') iBitsRead = 0; } else if(iBitsRead < 32) { if(*sLine >= '0' && *sLine <= '9') { iKey <<= 4; iKey |= (*sLine - '0'); iBitsRead += 4; } else if(*sLine >= 'a' && *sLine <= 'f') { iKey <<= 4; iKey |= (*sLine - 'a' + 10); iBitsRead += 4; } else if(*sLine >= 'A' && *sLine <= 'F') { iKey <<= 4; iKey |= (*sLine - 'A' + 10); iBitsRead += 4; } } ++sLine; } if(*sLine && *sLine == '=') { ++sLine; // Read in value char *sValue = 0; if(!bUnk) { sValue = new char[strlen(sLine) + 1]; if(sValue == 0) { delete[] sBaseLine; fclose(fFile); throw new CRainmanException(__FILE__, __LINE__, "Failed to allocate memory"); } char *sTmp = sValue; memset(sValue, 0, strlen(sLine) + 1); while(*sLine) { if( (*sLine != ' ') && (*sLine != '\t') && (*sLine != '\r') && (*sLine != '\n') ) { *sTmp = *sLine; ++sTmp; } ++sLine; } } _Value Val; Val = m_mHashTable[iKey]; if(Val.sString) { Val.bCustom = Val.bCustom && bCustom; delete[] sValue; } else { Val.sString = sValue; Val.bCustom = bCustom; } m_mHashTable[iKey] = Val; } delete[] sBaseLine; } else { delete[] sLine; } } fclose(fFile); } void CRgdHashTable::XRefWithStringList(const char* sFile) { FILE *fFile = fopen(sFile, "rb"); if(fFile == 0) throw new CRainmanException(0, __FILE__, __LINE__, "Failed to open file \'%s\'", sFile); while(!feof(fFile)) { char* sLine; try { sLine = fgetline(fFile); } catch(CRainmanException* pE) { fclose(fFile); throw new CRainmanException(__FILE__, __LINE__, "Failed to read line", pE); } unsigned long iKey = hash((ub1*)sLine, (ub4) strlen(sLine), 0); if(m_mHashTable.find(iKey) != m_mHashTable.end() && m_mHashTable[iKey].sString == 0) { _Value Val; Val.bCustom = true; Val.sString = CHECK_MEM(mystrdup(sLine)); m_mHashTable[iKey] = Val; } delete[] sLine; } } void CRgdHashTable::SaveCustomKeys(const char* sFile) { FILE *fFile = fopen(sFile, "wb"); if(fFile == 0) throw new CRainmanException(0, __FILE__, __LINE__, "Failed to open file \'%s\'", sFile); fputs("#RGD_DIC\n# This dictionary is generated from any keys that are \'discovered\'\n", fFile); for(std::map<unsigned long, _Value>::iterator itr = m_mHashTable.begin(); itr != m_mHashTable.end(); ++itr) { if(itr->second.bCustom) { if(itr->second.sString == 0) fputs("# ", fFile); // Output key fputs("0x", fFile); unsigned long iMask = 0xF0000000; for(int i = 7; i >= 0; --i) { fputc("0123456789ABCDEF"[(itr->first & iMask) >> (i << 2)], fFile); iMask >>= 4; } // Output value if(itr->second.sString == 0) { fputs(" is an unknown value!!\n", fFile); } else { fputc('=', fFile); fputs(itr->second.sString, fFile); fputc('\n', fFile); } } } fclose(fFile); } const char* CRgdHashTable::HashToValue(unsigned long iHash) { const char* s = m_mHashTable[iHash].sString; if(s == 0) { m_mHashTable[iHash].bCustom = true; return 0; } return s; } unsigned long CRgdHashTable::ValueToHash(const char* sValue) { if(sValue[0] == '0' && sValue[1] == 'x') { for(int i = 2; i < 10; ++i) { if(!( (sValue[i] >= '0' && sValue[i] <= '9') || (sValue[i] >= 'a' && sValue[i] <= 'f') || (sValue[i] >= 'A' && sValue[i] <= 'F') )) goto nothex; } if(sValue[10] == 0) { unsigned long iKey = 0; for(int i = 2; i < 10; ++i) { iKey <<= 4; if(sValue[i] >= '0' && sValue[i] <= '9') iKey |= (sValue[i] - '0'); if(sValue[i] >= 'a' && sValue[i] <= 'f') iKey |= (sValue[i] - 'a' + 10); if(sValue[i] >= 'A' && sValue[i] <= 'F') iKey |= (sValue[i] - 'A' + 10); } return iKey; } } nothex: unsigned long iKey = hash((ub1*)sValue, (ub4) strlen(sValue), 0); if(m_mHashTable[iKey].sString == 0) { _Value Val; Val.bCustom = false; const char* sTmp = sValue; do { if( ((*sTmp) < '0') || ((*sTmp) > '9') ) { Val.bCustom = true; break; } ++sTmp; }while(*sTmp); Val.sString = CHECK_MEM(mystrdup(sValue)); m_mHashTable[iKey] = Val; } return iKey; } unsigned long CRgdHashTable::ValueToHashStatic(const char* sValue, size_t iValueLen) { if(sValue[0] == '0' && sValue[1] == 'x' && iValueLen == 10) { for(int i = 2; i < 10; ++i) { if(!( (sValue[i] >= '0' && sValue[i] <= '9') || (sValue[i] >= 'a' && sValue[i] <= 'f') || (sValue[i] >= 'A' && sValue[i] <= 'F') )) goto nothex; } unsigned long iKey = 0; for(int i = 2; i < 10; ++i) { iKey <<= 4; if(sValue[i] >= '0' && sValue[i] <= '9') iKey |= (sValue[i] - '0'); if(sValue[i] >= 'a' && sValue[i] <= 'f') iKey |= (sValue[i] - 'a' + 10); if(sValue[i] >= 'A' && sValue[i] <= 'F') iKey |= (sValue[i] - 'A' + 10); } return iKey; } nothex: unsigned long iKey = hash((ub1*)sValue, (ub4) iValueLen, 0); return iKey; } unsigned long CRgdHashTable::ValueToHashStatic(const char* sValue) { if(sValue[0] == '0' && sValue[1] == 'x') { for(int i = 2; i < 10; ++i) { if(!( (sValue[i] >= '0' && sValue[i] <= '9') || (sValue[i] >= 'a' && sValue[i] <= 'f') || (sValue[i] >= 'A' && sValue[i] <= 'F') )) goto nothex; } if(sValue[10] == 0) { unsigned long iKey = 0; for(int i = 2; i < 10; ++i) { iKey <<= 4; if(sValue[i] >= '0' && sValue[i] <= '9') iKey |= (sValue[i] - '0'); if(sValue[i] >= 'a' && sValue[i] <= 'f') iKey |= (sValue[i] - 'a' + 10); if(sValue[i] >= 'A' && sValue[i] <= 'F') iKey |= (sValue[i] - 'A' + 10); } return iKey; } } nothex: unsigned long iKey = hash((ub1*)sValue, (ub4) strlen(sValue), 0); return iKey; } CRgdHashTable::_Value::_Value() { sString = 0; bCustom = false; } void CRgdHashTable::_Clean() { for(std::map<unsigned long, _Value>::iterator itr = m_mHashTable.begin(); itr != m_mHashTable.end(); ++itr) { if(itr->second.sString) delete[] itr->second.sString; } }
23.105505
123
0.571074
tranek
9a6b74f17a9d9e386a1fb0d561ea3f9cb5dada08
1,518
hpp
C++
include/pichi/common/endpoint.hpp
imuzi/pichi
5ad1372bff4c3bffd201ccfb41df6c839c83c506
[ "BSD-3-Clause" ]
164
2018-09-28T09:41:05.000Z
2021-11-13T09:17:07.000Z
include/pichi/common/endpoint.hpp
imuzi/pichi
5ad1372bff4c3bffd201ccfb41df6c839c83c506
[ "BSD-3-Clause" ]
5
2018-12-21T13:40:02.000Z
2021-07-24T04:23:44.000Z
include/pichi/common/endpoint.hpp
imuzi/pichi
5ad1372bff4c3bffd201ccfb41df6c839c83c506
[ "BSD-3-Clause" ]
14
2018-12-18T09:35:42.000Z
2021-07-06T12:16:34.000Z
#ifndef PICHI_COMMON_ENDPOINT_HPP #define PICHI_COMMON_ENDPOINT_HPP #include <algorithm> #include <functional> #include <iterator> #include <pichi/common/buffer.hpp> #include <pichi/common/enumerations.hpp> #include <string> #include <string_view> #include <type_traits> namespace std { inline string to_string(string_view sv) { return {cbegin(sv), cend(sv)}; } } // namespace std namespace pichi { struct Endpoint { EndpointType type_; std::string host_; uint16_t port_; }; template <typename Int> void hton(Int src, MutableBuffer<uint8_t> dst) { static_assert(std::is_integral_v<Int>, "input type must be integral."); assert(sizeof(Int) <= dst.size()); auto p = reinterpret_cast<uint8_t*>(&src); std::reverse_copy(p, p + sizeof(Int), std::begin(dst)); } template <typename Int> Int ntoh(ConstBuffer<uint8_t> src) { static_assert(std::is_integral_v<Int>, "output type must be integral."); assert(src.size() >= sizeof(Int)); Int dst; std::reverse_copy(std::cbegin(src), std::cend(src), reinterpret_cast<uint8_t*>(&dst)); return dst; } extern size_t serializeEndpoint(Endpoint const&, MutableBuffer<uint8_t>); extern Endpoint parseEndpoint(std::function<void(MutableBuffer<uint8_t>)>); extern EndpointType detectHostType(std::string_view); extern Endpoint makeEndpoint(std::string_view, uint16_t); extern Endpoint makeEndpoint(std::string_view, std::string_view); extern bool operator==(Endpoint const&, Endpoint const&); } // namespace pichi #endif // PICHI_COMMON_ENDPOINT_HPP
27.107143
88
0.746377
imuzi
9a7253aa706747c7104c81bf942ca292d57d6aa9
1,303
cpp
C++
src/trace/GLLib/Texture/TextureTarget.cpp
attila-sim/attila-sim
a64b57240b4e10dc4df7f21eff0232b28df09532
[ "BSD-3-Clause" ]
23
2016-01-14T04:47:13.000Z
2022-01-13T14:02:08.000Z
src/trace/GLLib/Texture/TextureTarget.cpp
attila-sim/attila-sim
a64b57240b4e10dc4df7f21eff0232b28df09532
[ "BSD-3-Clause" ]
2
2018-03-25T14:39:20.000Z
2022-03-18T05:11:21.000Z
src/trace/GLLib/Texture/TextureTarget.cpp
attila-sim/attila-sim
a64b57240b4e10dc4df7f21eff0232b28df09532
[ "BSD-3-Clause" ]
17
2016-02-13T05:35:35.000Z
2022-03-24T16:05:40.000Z
/************************************************************************** * * Copyright (c) 2002 - 2011 by Computer Architecture Department, * Universitat Politecnica de Catalunya. * All rights reserved. * * The contents of this file may not be disclosed to third parties, * copied or duplicated in any form, in whole or in part, without the * prior permission of the authors, Computer Architecture Department * and Universitat Politecnica de Catalunya. * */ #include "TextureTarget.h" using namespace libgl; TextureTarget::TextureTarget(GLuint target) : BaseTarget(target) { if ( target != GL_TEXTURE_1D && target != GL_TEXTURE_2D && target != GL_TEXTURE_3D && target != GL_TEXTURE_CUBE_MAP ) panic("TextureTarget", "TextureTarget", "Unexpected texture target"); TextureObject* defTex = new TextureObject(0, target); // create a default object defTex->setTarget(*this); setCurrent(*defTex); setDefault(defTex); /***************************************** * CONFIGURE DEFAULT TEXTURE OBJECT HERE * *****************************************/ } TextureObject* TextureTarget::createObject(GLuint name) { TextureObject* to = new TextureObject(name, getName()); to->setTarget(*this); return to; }
30.302326
90
0.604758
attila-sim
9a77b287a6fd0647a604244033677071702b2567
187,010
cpp
C++
libs/graph_parallel/test/performance_test.cpp
thejkane/AGM
4d5cfe9522461d207ceaef7d90c1cd10ce9b469c
[ "BSL-1.0" ]
1
2021-09-03T10:22:04.000Z
2021-09-03T10:22:04.000Z
libs/graph_parallel/test/performance_test.cpp
thejkane/AGM
4d5cfe9522461d207ceaef7d90c1cd10ce9b469c
[ "BSL-1.0" ]
null
null
null
libs/graph_parallel/test/performance_test.cpp
thejkane/AGM
4d5cfe9522461d207ceaef7d90c1cd10ce9b469c
[ "BSL-1.0" ]
null
null
null
// Copyright (C) 2014 The Trustees of Indiana University. // 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) // Authors: Nicholas Edmonds // Andrew Lumsdaine // Marcin Zalewski // Thejaka Kanewala #define LIB_CDS 1 #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #include <stdint.h> #include <inttypes.h> #include <cstdlib> #include <math.h> //#define DISABLE_SELF_SEND_CHECK //#define AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS //#define PBGL2_PRINT_WORK_STATS // #define PRINT_STATS // #define PRINT_DEBUG #define AMPLUSPLUS_PRINT_HIT_RATES #define BFS_SV_CC_HACK // #define DS_SHARED_REDUCTIONS // #define BFS_VECTOR #define DISABLE_BFS_BITMAP #ifdef __bgp__ #define BGP_REPORT_MEMORY 1 // if >1 all ranks will report memory usage #endif //#define NUMBER_COMPONENTS // #define PBGL_TIMING // turn on local component counting, sequential timing, and such in CC // #define PRINT_ET #define BARRIER_TRANS // #define CLONE #define CALCULATE_GTEPS 1 #include <am++/am++.hpp> #include <am++/mpi_transport.hpp> #include <am++/counter_coalesced_message_type.hpp> #include <boost/graph/distributed/time_calc.hpp> #include <boost/iterator/transform_iterator.hpp> #include <boost/graph/use_mpi.hpp> #include <boost/property_map/parallel/distributed_property_map.hpp> #include <boost/property_map/property_map.hpp> #include <boost/graph/distributed/compressed_sparse_row_graph.hpp> #include <boost/graph/recursive_rmat_generator.hpp> #include <boost/graph/erdos_renyi_generator.hpp> #include <boost/graph/graph500_generator.hpp> #include <boost/graph/permute_graph.hpp> #include <boost/graph/parallel/algorithm.hpp> // for all_reduce #include <boost/graph/breadth_first_search.hpp> #include <boost/graph/distributed/delta_stepping_shortest_paths.hpp> #include <boost/graph/distributed/delta_stepping_shortest_paths_node.hpp> #include <boost/graph/distributed/delta_stepping_shortest_paths_thread.hpp> #include <boost/graph/distributed/delta_stepping_shortest_paths_numa.hpp> #include <boost/graph/distributed/mis.hpp> #include <boost/graph/distributed/mis_delta.hpp> #include <boost/graph/distributed/luby_mis.hpp> #include <boost/graph/distributed/kla_sssp_buffer.hpp> #include <boost/graph/distributed/kla_sssp_numa.hpp> #include <boost/graph/distributed/kla_sssp_node.hpp> #include <boost/graph/distributed/kla_sssp_thread.hpp> #include <boost/graph/distributed/distributed_control.hpp> #include <boost/graph/distributed/distributed_control_node.hpp> #include <boost/graph/distributed/distributed_control_pheet.hpp> #include <boost/graph/distributed/priority_q_defs.hpp> #include <boost/graph/distributed/distributed_control_chaotic.hpp> #include <boost/graph/distributed/cc_dc.hpp> #include <boost/graph/distributed/cc_chaotic.hpp> #include <boost/graph/distributed/delta_stepping_cc.hpp> #include <boost/graph/distributed/cc_diff_dc.hpp> #include <boost/graph/distributed/level_sync_cc.hpp> #include <boost/graph/distributed/connected_components.hpp> #include <boost/graph/distributed/sv_cc.hpp> #include <boost/graph/distributed/page_rank.hpp> #include <boost/graph/distributed/graph_reader.hpp> #include <boost/graph/relax.hpp> #include <boost/random/linear_congruential.hpp> #include <boost/lexical_cast.hpp> #include <boost/property_map/parallel/global_index_map.hpp> #include <boost/parallel/append_buffer.hpp> #include <boost/accumulators/accumulators.hpp> #include <boost/accumulators/statistics.hpp> #include <parallel/algorithm> #include <algorithm> // for std::min, std::max #include <functional> #include <cds/init.h> // for cds::Initialize and cds::Terminate #include <cds/gc/hp.h> // for cds::HP (Hazard Pointer) SMR //#include "statistics.h" #define HAS_NOT_BEEN_SEEN #ifdef DISABLE_SELF_SEND_CHECK #warning "==================^^^^^Self send check is disabled !^^^^^=======================" #endif int _RANK; using namespace boost; using boost::parallel::all_reduce; using boost::parallel::maximum; using std::max; #include <time.h> #include <sys/time.h> /*typedef double time_type; inline time_type get_time() { return MPI_Wtime(); #if 0 timeval tp; gettimeofday(&tp, 0); return tp.tv_sec + tp.tv_usec / 1000000.0; #endif }*/ std::string print_time(time_type t) { std::ostringstream out; out << std::setiosflags(std::ios::fixed) << std::setprecision(2) << t; return out.str(); } struct flip_pair { template <typename T> T operator()(const T& x) const { // flipping edges by keeping same weight return std::make_pair(x.second.first, std::make_pair(x.first, x.second.second)); } }; #define PRINT_GRAPH500_STATS(lbl, israte) \ do { \ printf ("Min(%s): %20.17e\n", lbl, stats[0]); \ printf ("First Quartile(%s): %20.17e\n", lbl, stats[1]); \ printf ("Median(%s): %20.17e\n", lbl, stats[2]); \ printf ("Third Quartile(%s): %20.17e\n", lbl, stats[3]); \ printf ("Max(%s): %20.17e\n", lbl, stats[4]); \ if (!israte) { \ printf ("Mean(%s): %20.17e\n", lbl, stats[5]); \ printf ("Stddev(%s): %20.17e\n", lbl, stats[6]); \ } else { \ printf ("Harmonic Mean(%s): %20.17e\n", lbl, stats[7]); \ printf ("Harmonic Stddev(%s): %20.17e\n", lbl, stats[8]); \ } \ } while (0) extern void statistics (double *out, double *data, size_t n); static int dcmp (const void *a, const void *b) { const double da = *(const double*)a; const double db = *(const double*)b; if (da > db) return 1; if (db > da) return -1; if (da == db) return 0; fprintf (stderr, "No NaNs permitted in output.\n"); abort (); return 0; } void statistics (double *out, double *data, size_t n) { long double s, mean; double t; int k; /* Quartiles */ qsort (data, n, sizeof (*data), dcmp); out[0] = data[0]; t = (n+1) / 4.0; k = (int) t; if (t == k) out[1] = data[k]; else out[1] = 3*(data[k]/4.0) + data[k+1]/4.0; t = (n+1) / 2.0; k = (int) t; if (t == k) out[2] = data[k]; else out[2] = data[k]/2.0 + data[k+1]/2.0; t = 3*((n+1) / 4.0); k = (int) t; if (t == k) out[3] = data[k]; else out[3] = data[k]/4.0 + 3*(data[k+1]/4.0); out[4] = data[n-1]; s = data[n-1]; for (k = n-1; k > 0; --k) s += data[k-1]; mean = s/n; out[5] = mean; s = data[n-1] - mean; s *= s; for (k = n-1; k > 0; --k) { long double tmp = data[k-1] - mean; s += tmp * tmp; } out[6] = sqrt (s/(n-1)); s = (data[0]? 1.0L/data[0] : 0); for (k = 1; k < n; ++k) s += (data[k]? 1.0L/data[k] : 0); out[7] = n/s; mean = s/n; /* Nilan Norris, The Standard Errors of the Geometric and Harmonic Means and Their Application to Index Numbers, 1940. http://www.jstor.org/stable/2235723 */ s = (data[0]? 1.0L/data[0] : 0) - mean; s *= s; for (k = 1; k < n; ++k) { long double tmp = (data[k]? 1.0L/data[k] : 0) - mean; s += tmp * tmp; } s = (sqrt (s)/(n-1)) * out[7] * out[7]; out[8] = s; } // // Performance counters // #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS std::vector<time_type> epoch_times; // These should really be atomic typedef unsigned long long flush_type; typedef amplusplus::detail::atomic<flush_type> atomic_flush_type; #define FLUSH_MPI_TYPE MPI_UNSIGNED_LONG std::unique_ptr<atomic_flush_type[]> flushes; flush_type flushes_size; std::vector<flush_type> all_flushes, cumulative_flushes; atomic_flush_type full{}, messages_received{}; flush_type all_full{}, cumulative_full{}, all_messages{}, cumulative_messages{}; void print_and_clear_epoch_times() { if(_RANK == 0) { std::cout << "There were " << epoch_times.size() << " epochs." << std::endl; std::cout << "Epoch times "; BOOST_FOREACH(time_type t, epoch_times) { std::cout << print_time(t) << " "; } std::cout << "\n"; } epoch_times.clear(); } void clear_buffer_stats() { for(unsigned int i = 0; i < flushes_size; ++i) flushes[i] = 0; full = 0; messages_received = 0; } void clear_cumulative_buffer_stats() { for(unsigned int i = 0; i < flushes_size; ++i) cumulative_flushes[i] = 0; cumulative_full = 0; cumulative_messages = 0; } void print_buffer_stats() { unsigned long long sum = 0; unsigned long long number_of_buffers = 0; flush_type tmp_flushes[flushes_size]; for(int i = 0; i < flushes_size; ++i) tmp_flushes[i] = flushes[i].load(); flush_type tmp_full = full.load(); flush_type tmp_messages = messages_received.load(); MPI_Allreduce(&tmp_flushes, &all_flushes.front(), flushes_size, FLUSH_MPI_TYPE, MPI_SUM, MPI_COMM_WORLD); MPI_Allreduce(&tmp_full, &all_full, 1, FLUSH_MPI_TYPE, MPI_SUM, MPI_COMM_WORLD); MPI_Allreduce(&tmp_messages, &all_messages, 1, FLUSH_MPI_TYPE, MPI_SUM, MPI_COMM_WORLD); if(_RANK == 0) std::cout << "Flushes: "; for(unsigned int i = 0; i < all_flushes.size(); ++i) { if(all_flushes[i] != 0) { if(_RANK == 0) std::cout << i+1 << "->" << all_flushes[i] << " "; sum += (i + 1) * all_flushes[i]; number_of_buffers += all_flushes[i]; cumulative_flushes[i] += all_flushes[i]; } } cumulative_full += all_full; cumulative_messages += all_messages; if(_RANK == 0) { std::cout << std::endl; std::cout << "There were " << number_of_buffers << " incomplete flushes with the average size of a flush of " << (number_of_buffers != 0 ? sum/number_of_buffers : 0) << std::endl; std::cout << "Full buffers: " << all_full << std::endl; std::cout << "Messages: " << all_messages << std::endl; } } namespace amplusplus { namespace performance_counters { void hook_flushed_message_size(amplusplus::rank_type dest, size_t count, size_t elt_size) { if(count <= flushes_size) flushes[count-1]++; #ifdef PRINT_STATS time_type t = get_time(); fprintf(stderr, "Flush: %d bytes to %d at %f\n", (count * elt_size), dest, t); #endif } void hook_full_buffer_send(amplusplus::rank_type dest, size_t count, size_t elt_size) { full++; #ifdef PRINT_STATS time_type t = get_time(); fprintf(stderr, "Full buffer: %d bytes to %d at %f\n", (count * elt_size), dest, t); #endif } void hook_message_received(amplusplus::rank_type src, size_t count, size_t elt_size) { messages_received += count; #ifdef PRINT_STATS time_type t = get_time(); fprintf(stderr, "%d: Message received: %d bytes from %d at %f\n", _RANK, (count * elt_size), src, t); #endif } void hook_begin_epoch(amplusplus::transport& trans) { epoch_times.push_back(get_time()); } void hook_epoch_finished(amplusplus::transport& trans) { epoch_times.back() = get_time() - epoch_times.back(); } } } #endif // AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS // Hit rates #ifdef AMPLUSPLUS_PRINT_HIT_RATES unsigned long long cumulative_hits, cumulative_tests; void print_and_accumulate_cache_stats(std::pair<unsigned long long, unsigned long long> stats) { unsigned long long hits, tests; MPI_Allreduce(&stats.first, &hits, 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD); MPI_Allreduce(&stats.second, &tests, 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD); cumulative_hits += hits; cumulative_tests += tests; if(_RANK == 0) { std::cout << "Cache hit rates: " << hits << " hits, " << tests << " tests. Success ratio: " << (double)hits / (double)tests << "." << std::endl; } } #endif // AMPLUSPLUS_PRINT_HIT_RATES #ifdef PBGL2_PRINT_WORK_STATS typedef std::tuple<unsigned long long, unsigned long long, unsigned long long, unsigned long long> work_stats_t; typedef std::tuple<unsigned long long, unsigned long long, unsigned long long, unsigned long long, unsigned long long, unsigned long long> all_work_stats_t; // Distributed control work stats all_work_stats_t dc_stats, ds_stats; void clear_cumulative_work_stats() { dc_stats = all_work_stats_t{ 0ul, 0ul, 0ul, 0ul, 0ul, 0ul }; ds_stats = all_work_stats_t{ 0ul, 0ul, 0ul, 0ul, 0ul, 0ul }; } void print_q_stats(unsigned long long max_q_sz, unsigned long long avg_max_q_size = 0) { unsigned long long max, min; MPI_Allreduce(&max_q_sz, &max, 1, MPI_UNSIGNED_LONG, MPI_MAX, MPI_COMM_WORLD); MPI_Allreduce(&max_q_sz, &min, 1, MPI_UNSIGNED_LONG, MPI_MIN, MPI_COMM_WORLD); if (_RANK == 0) std::cout << "Maximum max q size : " << max << " minimum max q size : " << min << std::endl; if (avg_max_q_size != 0) { int world_size; MPI_Comm_size(MPI_COMM_WORLD, &world_size); unsigned long long avg_max_sum; MPI_Allreduce(&avg_max_q_size, &avg_max_sum, 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD); if (_RANK == 0) std::cout << "Average maximum queue size : " << (avg_max_sum / world_size) << std::endl; } } void print_and_accumulate_work_stats(work_stats_t stats, all_work_stats_t &cummulative_stats, size_t edges_traverse) { work_stats_t temp_stats; MPI_Allreduce(&std::get<0>(stats), &std::get<0>(temp_stats), 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD); MPI_Allreduce(&std::get<1>(stats), &std::get<1>(temp_stats), 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD); MPI_Allreduce(&std::get<2>(stats), &std::get<2>(temp_stats), 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD); MPI_Allreduce(&std::get<3>(stats), &std::get<3>(temp_stats), 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD); if(_RANK == 0) std::cout << "Useful work: " << std::get<0>(temp_stats) << ", invalidated work: " << std::get<1>(temp_stats) << ", useless work: " << std::get<2>(temp_stats) << ", rejected work: " << std::get<3>(temp_stats) << ", number of edges traversed : " << edges_traverse << ", level of ordering: " << (std::get<0>(temp_stats) + std::get<2>(temp_stats) - (2*edges_traverse)-1) << ", extra edge relaxes: " << (std::get<1>(temp_stats)-std::get<3>(temp_stats)) << std::endl; std::get<0>(cummulative_stats) += std::get<0>(temp_stats); std::get<1>(cummulative_stats) += std::get<1>(temp_stats); std::get<2>(cummulative_stats) += std::get<2>(temp_stats); std::get<3>(cummulative_stats) += std::get<3>(temp_stats); std::get<4>(cummulative_stats) += (std::get<0>(temp_stats) + std::get<2>(temp_stats) - (2*edges_traverse) - 1); // ordering std::get<5>(cummulative_stats) += (std::get<1>(temp_stats)-std::get<3>(temp_stats)); // extra relaxes } // TODO: Unify these two macros? We probably don't need macros at all. This is just a leftover from the previous test harness. #define PBGL2_DC_PRINT \ << "\nUseful work: " << (std::get<0>(dc_stats) / num_sources) << " (per source), invalidated work: " << (std::get<1>(dc_stats) / num_sources) << " (per source), useless work: " << (std::get<2>(dc_stats)/num_sources) << " (per source), rejected work: " << (std::get<3>(dc_stats)/num_sources) << " (per source). Rejected/useful ratio: " << ((double)std::get<3>(dc_stats) / (double)std::get<0>(dc_stats)) << ". Invalidated/useful ratio: " << ((double)std::get<1>(dc_stats) / (double)std::get<0>(dc_stats)) << ", level of ordering: " << std::get<4>(dc_stats) << ", extra edge relaxes: " << std::get<5>(dc_stats) #define PBGL2_DS_PRINT \ << "\nUseful work: " << (std::get<0>(ds_stats) / num_sources) << " (per source), invalidated work: " << (std::get<1>(ds_stats) / num_sources) << " (per source), useless work: " << (std::get<2>(ds_stats)/num_sources) << " (per source), rejected work: " << (std::get<3>(ds_stats)/num_sources) << " (per source). Rejected/useful ratio: " << ((double)std::get<3>(ds_stats) / (double)std::get<0>(ds_stats)) << ". Invalidated/useful ratio: " << ((double)std::get<1>(ds_stats) / (double)std::get<0>(ds_stats)) << ", level of ordering: " << (std::get<4>(ds_stats)/num_sources) << ", extra edge relaxes: " << (std::get<5>(ds_stats)/num_sources) #endif // PBGL2_PRINT_WORK_STATS // // Edge properties // typedef int32_t weight_type; // Needed so atomics are available on MacOS struct WeightedEdge { WeightedEdge(weight_type weight = 0) : weight(weight) { } weight_type weight; }; namespace amplusplus { template<> struct make_mpi_datatype<WeightedEdge> : make_mpi_datatype_base { make_mpi_datatype<weight_type> dt1; scoped_mpi_datatype dt; make_mpi_datatype(): dt1() { int blocklengths[1] = {1}; MPI_Aint displacements[1]; WeightedEdge test_object; MPI_Aint test_object_ptr; MPI_Get_address(&test_object, &test_object_ptr); MPI_Get_address(&test_object.weight, &displacements[0]); displacements[0] -= test_object_ptr; MPI_Datatype types[1] = {dt1.get()}; MPI_Type_create_struct(1, blocklengths, displacements, types, dt.get_ptr()); MPI_Type_commit(dt.get_ptr()); } MPI_Datatype get() const {return dt;} }; } // // Edge weight generator iterator // template<typename F, typename RandomGenerator> class generator_iterator { public: typedef std::input_iterator_tag iterator_category; typedef typename F::result_type value_type; typedef const value_type& reference; typedef const value_type* pointer; typedef void difference_type; explicit generator_iterator(RandomGenerator& gen, const F& f = F()) : f(f), gen(&gen) { value = this->f(gen); } reference operator*() const { return value; } pointer operator->() const { return &value; } generator_iterator& operator++() { value = f(*gen); return *this; } generator_iterator operator++(int) { generator_iterator temp(*this); ++(*this); return temp; } bool operator==(const generator_iterator& other) const { return f == other.f; } bool operator!=(const generator_iterator& other) const { return !(*this == other); } private: F f; RandomGenerator* gen; value_type value; }; template<typename F, typename RandomGenerator> inline generator_iterator<F, RandomGenerator> make_generator_iterator( RandomGenerator& gen, const F& f) { return generator_iterator<F, RandomGenerator>(gen, f); } template <typename Graph, typename DistanceMap, typename WeightMap> size_t get_gteps(amplusplus::transport& trans, Graph& g, DistanceMap& distance, const WeightMap& weight) { distance.set_consistency_model(boost::parallel::cm_forward); distance.set_max_ghost_cells(0); size_t gteps = 0; { amplusplus::scoped_epoch epoch(g.transport()); size_t dist = std::numeric_limits<size_t>::max(); BGL_FORALL_VERTICES_T(v, g, Graph) { dist = get(distance, v); if(dist < std::numeric_limits<size_t>::max()) { BGL_FORALL_OUTEDGES_T(v, e, g, Graph) { gteps+=1; //get(distance, target(e, g)); } } } } gteps = gteps / 2; // we are considering an undirected graph return gteps; } template <typename Graph, typename DistanceMap, typename WeightMap, typename Vertex> size_t count_edges(amplusplus::transport& trans, Graph& g, DistanceMap& distance, const WeightMap& weight, const Vertex source) { distance.set_consistency_model(boost::parallel::cm_forward); distance.set_max_ghost_cells(0); size_t gteps = 0; { amplusplus::scoped_epoch epoch(g.transport()); size_t dist = std::numeric_limits<size_t>::max(); BGL_FORALL_VERTICES_T(v, g, Graph) { dist = get(distance, v); if(dist < std::numeric_limits<size_t>::max()) { BGL_FORALL_OUTEDGES_T(v, e, g, Graph) { // check whether this is a self loop; if self loop dont count it if (target(e,g) == v) continue; gteps+=1; //get(distance, target(e, g)); } } } } return gteps; } template<typename MessageType> class threaded_distributor { public: threaded_distributor(MessageType& mtype) : msg_type(mtype) {} void operator()() { } template <typename InIter, typename Flip> void operator()(int tid, InIter begin, InIter end, const Flip& flip, amplusplus::transport& trans) { AMPLUSPLUS_WITH_THREAD_ID(tid) { concurrent_distribute(begin, end, flip, trans, msg_type); } } private: MessageType& msg_type; }; template <typename Edges> class threaded_merger { public: threaded_merger(Edges& all) : all_edges(all) {} void operator()() { } template <typename EdgesIter> void operator()(EdgesIter pos, EdgesIter begin, EdgesIter end) { std::copy(begin, end, pos); } private: Edges& all_edges; }; template <typename Graph, typename ComponentMap, typename vertices_sz_t> void calculate_cc_stats(Graph& g, ComponentMap& components, vertices_sz_t n, bool allstats) { typedef unsigned int component_t; typedef std::map<component_t, component_t> component_stats_t; component_stats_t component_stats; #ifdef PRINT_DEBUG std::cout << "Calculating local components ..." << std::endl; #endif BGL_FORALL_VERTICES_T(v, g, Graph) { component_t vcomp = (component_t)get(components, v); component_stats_t::iterator ite = component_stats.find(vcomp); if (ite == component_stats.end()) { component_stats.insert(std::make_pair(vcomp, 1)); } else { ++((*ite).second); } } // end calculating local components. // exchange all components component_t localcomps = component_stats.size(); #ifdef PRINT_DEBUG std::cout << "Rank : " << _RANK << ", found local components : " << localcomps << std::endl; #endif // allstats false if (!allstats) { // sort by number of vertices std::vector<std::pair<int, int>> pairs; for (auto itr = component_stats.begin(); itr != component_stats.end(); ++itr) pairs.push_back(*itr); component_stats.clear(); std::sort(pairs.begin(), pairs.end(), [=](std::pair<int, int>& a, std::pair<int, int>& b) { return a.second > b.second; }); if (_RANK == 0) { std::cout << "Printing component statistics ..." << std::endl; std::cout << "Printing only five largest components. To print all use --allstats" << std::endl; std::cout << "Total number of components in root : " << pairs.size() << std::endl; } int i = 0; vertices_sz_t rn = 0; for (; i < 5; ++i) { int compid = pairs[i].first; int vtcs = pairs[i].second; //check whether component id is same across all nodes int retcomp; MPI_Barrier(MPI_COMM_WORLD); std::cout << "r : " << _RANK << ", c=" << compid << ", i=" << i << std::endl; MPI_Allreduce(&compid, &retcomp, 1, MPI_INT, MPI_LAND, MPI_COMM_WORLD); MPI_Barrier(MPI_COMM_WORLD); if (retcomp == compid) { // run a all reduce on all the vertices int allvs; MPI_Barrier(MPI_COMM_WORLD); MPI_Allreduce(&vtcs, &allvs, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); if (_RANK == 0) { std::cout << "component : " << compid << " vertices : " << allvs << " percentage : " << ((((double)allvs)/(double)n) * 100) << std::endl; } } else { std::cout << "[ComponentStats] A mismatch found" << std::endl; } } } else { // allstats true component_t allcomps; // calculate sum of localcomps MPI_Allreduce(&localcomps, &allcomps, 1, MPI_UNSIGNED, MPI_SUM, MPI_COMM_WORLD); component_t expectedcomps = allcomps - localcomps; if (_RANK == 0) std::cout << "All the components : " << allcomps << ", expecting receive components : " << expectedcomps << std::endl; typedef struct component_vertices { component_t c; component_t vs; component_vertices(): c(0), vs(0) {} component_vertices(int pc, int pvs): c(pc), vs(pvs) {} component_vertices(const component_vertices &cvob): c(cvob.c), vs(cvob.vs) {} } cvs; const int nitems=2; int blocklengths[2] = {1,1}; MPI_Datatype types[2] = {MPI_UNSIGNED, MPI_UNSIGNED}; MPI_Datatype mpi_cv_type; MPI_Aint offsets[2]; offsets[0] = offsetof(cvs, c); offsets[1] = offsetof(cvs, vs); MPI_Type_create_struct(nitems, blocklengths, offsets, types, &mpi_cv_type); MPI_Type_commit(&mpi_cv_type); std::vector<cvs> sendcomps; std::vector<cvs> recvcomps; if (_RANK != 0) { // go through local component stat maps and collect them to an array sendcomps.resize(localcomps); int j = 0; component_stats_t::iterator itesend = component_stats.begin(); for (; itesend != component_stats.end(); ++itesend) { sendcomps[j].c = (*itesend).first; sendcomps[j].vs = (*itesend).second; #ifdef PRINT_DEBUG std::cout << "Rank : " << _RANK << ", c=" << sendcomps[j].c << ", vs=" << sendcomps[j].vs << std::endl; #endif ++j; } #ifdef PRINT_DEBUG std::cout << "Rank : " << _RANK << ", sending components : " << localcomps << std::endl; #endif if (MPI_Send(&sendcomps[0], localcomps, mpi_cv_type, 0/*rank = 0*/, 13 /*tag*/, MPI_COMM_WORLD) != 0) { std::cout << "MPI_Send : " << "Error exchanging components" << std::endl; } } MPI_Barrier(MPI_COMM_WORLD); if (_RANK == 0) { recvcomps.resize(expectedcomps); if (expectedcomps != 0) { #ifdef PRINT_DEBUG std::cout << "Rank : " << _RANK << ", expected components : " << expectedcomps << std::endl; #endif int recvcount = 0; component_t rcvexpectedcomps = expectedcomps; while (recvcount != expectedcomps) { MPI_Status status; if (MPI_Recv(&recvcomps[recvcount], rcvexpectedcomps, mpi_cv_type, MPI_ANY_SOURCE, 13, MPI_COMM_WORLD, &status) != 0) std::cout << "MPI_Recv : " << "Error receiving messages" << std::endl; int instcount = 0; if (MPI_Get_count(&status, mpi_cv_type, &instcount) != MPI_SUCCESS) std::cout << "MPI_Get_count :" << "Error getting received count" << std::endl; recvcount += instcount; rcvexpectedcomps -= instcount; } } } sendcomps.clear(); #ifdef PRINT_DEBUG std::cout << "Rank : " << _RANK << ", Merging received components to component stats. Received components : " << recvcomps.size() << std::endl; #endif // update compnent stats typename std::vector<cvs>::iterator veciter = recvcomps.begin(); for(; veciter != recvcomps.end(); ++veciter) { component_stats_t::iterator ite = component_stats.find((*veciter).c); if (ite == component_stats.end()) { #ifdef PRINT_DEBUG std::cout << "inserting c=" << (*veciter).c << ", vs=" << (*veciter).vs << std::endl; #endif component_stats.insert(std::make_pair((*veciter).c, (*veciter).vs)); } else { #ifdef PRINT_DEBUG std::cout << "adding c=" << (*veciter).c << ", vs=" << (*veciter).vs << std::endl; #endif (*ite).second += (*veciter).vs; } } recvcomps.clear(); if (_RANK == 0) { // sort by number of vertices std::vector<std::pair<int, int>> pairs; for (auto itr = component_stats.begin(); itr != component_stats.end(); ++itr) pairs.push_back(*itr); component_stats.clear(); #ifdef PRINT_DEBUG std::cout << "Sorting components by the number of vertices in their" << std::endl; #endif std::sort(pairs.begin(), pairs.end(), [=](std::pair<int, int>& a, std::pair<int, int>& b) { return a.second > b.second; }); std::cout << "Printing component statistics ..." << std::endl; std::cout << "Total number of components : " << pairs.size() << std::endl; int i = 0; vertices_sz_t rn = 0; std::vector<std::pair<int, int>>::iterator piter = pairs.begin(); for (; piter != pairs.end(); ++piter) { std::cout << "component : " << (*piter).first << " vertices : " << (*piter).second << " percentage : " << ((((double)((*piter).second))/(double)n) * 100) << std::endl; rn += (vertices_sz_t)(*piter).second; } std::cout << "rn = " << rn << ", n = " << n << std::endl; assert(rn == n); std::cout << "Done with CC stats." << std::endl; } } } template <typename Graph> bool run_grah_stats(Graph& g) { typedef typename boost::property_map<Graph, vertex_owner_t>::const_type OwnerMap; OwnerMap owner = get(vertex_owner, g); int remote_edges = 0; int local_edges = 0; BGL_FORALL_EDGES_T(e, g, Graph) { if (get(owner, source(e, g)) != _RANK) std::cout << "sv : " << source(e, g) << " svown : " << get(owner, source(e, g)) << " tv : " << target(e, g) << " tvown : " << get(owner, target(e, g)) << " rank : " << _RANK << std::endl; // assert(get(owner, source(e, g)) == _RANK); if (get(owner, target(e, g)) != _RANK) ++remote_edges; else ++local_edges; } int alllocale = num_edges(g); std::cout << "Rank : " << _RANK << " remote e : " << remote_edges << " local e : " << local_edges << " remote per : " << ((double)remote_edges / (double)alllocale) * 100 << "%" << std::endl; } template <typename Graph, typename ComponentMap> bool verify_cc(Graph& g, ComponentMap& components) { typedef typename graph_traits<Graph>::vertex_descriptor Vertex; components.set_consistency_model(boost::parallel::cm_forward); components.set_max_ghost_cells(0); { amplusplus::scoped_epoch epoch(g.transport()); BGL_FORALL_VERTICES_T(v, g, Graph) { BGL_FORALL_OUTEDGES_T(v, e, g, Graph) { get(components, source(e, g)); get(components, target(e, g)); } } } { amplusplus::scoped_epoch epoch(g.transport()); // at the moment get() sends a message BGL_FORALL_VERTICES_T(v, g, Graph) { BGL_FORALL_ADJ_T(v, u, g, Graph) { // std::cout << "verifying vertex v : " << v << std::endl; //#ifdef PRINT_DEBUG if (get(components, v) != get(components, u)) std::cout << "Component of " << v << " : " << get(components, v) << " component of " << u << " : " << get(components, u) << std::endl; assert(get(components, v) == get(components, u)); } } } components.clear(); // Clear memory used by ghost cells } template <typename Graph, typename DistanceMap, typename WeightMap> bool verify_sssp(amplusplus::transport& trans, Graph& g, DistanceMap& distance, const WeightMap& weight) { distance.set_consistency_model(boost::parallel::cm_forward); distance.set_max_ghost_cells(0); if (trans.rank() == 0) std::cout<<"Verifying results......"; { amplusplus::scoped_epoch epoch(g.transport()); BGL_FORALL_VERTICES_T(v, g, Graph) { BGL_FORALL_OUTEDGES_T(v, e, g, Graph) { get(distance, target(e, g)); } } } BGL_FORALL_VERTICES_T(v, g, Graph) { BGL_FORALL_OUTEDGES_T(v, e, g, Graph) { #ifdef PRINT_DEBUG if (get(distance, target(e, g)) > boost::closed_plus<weight_type>()(get(distance, source(e, g)), get(weight, e))) std::cout << get(get(vertex_local, g), source(e, g)) << "@" << get(get(vertex_owner, g), source(e, g)) << "->" << get(get(vertex_local, g), target(e, g)) << "@" << get(get(vertex_owner, g), target(e, g)) << " weight = " << get(weight, e) << " distance(" << get(get(vertex_local, g), source(e, g)) << "@" << get(get(vertex_owner, g), source(e, g)) << ") = " << get(distance, source(e, g)) << " distance(" << get(get(vertex_local, g), target(e, g)) << "@" << get(get(vertex_owner, g), target(e, g)) << ") = " << get(distance, target(e, g)) << std::endl; #else if(get(distance, target(e, g)) > boost::closed_plus<weight_type>()(get(distance, v), get(weight, e))) std::abort(); #endif } } if (trans.rank() == 0) std::cout << "Verified." << std::endl; distance.clear(); // Clear memory used by ghost cells return true; } template <typename Graph, typename MISMap> bool verify_mis(amplusplus::transport& trans, Graph& g, MISMap& mis) { typedef typename boost::property_map<Graph, vertex_owner_t>::const_type OwnerMap; OwnerMap owner(get(vertex_owner, g)); mis.set_consistency_model(boost::parallel::cm_forward || boost::parallel::cm_backward); mis.set_max_ghost_cells(0); if (trans.rank() == 0) std::cout<<"Verifying MIS results......"; { amplusplus::scoped_epoch epoch(g.transport()); BGL_FORALL_VERTICES_T(v, g, Graph) { BGL_FORALL_OUTEDGES_T(v, e, g, Graph) { get(mis, target(e, g)); } } } bool result = true; int found_mis = 0; #ifdef PRINT_DEBUG std::cout << "MIS = {"; #endif BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(mis, v) == MIS_FIX1) {// v in mis, none of the neigbours should be in mis #ifdef PRINT_DEBUG if (v == 35) { std::cout << "Printing all neighbors of " << v << " -- ["; BGL_FORALL_OUTEDGES_T(v, e, g, Graph) { std::cout << target(e, g) << ", "; } std::cout << "]" << std::endl; } std::cout << v << "-["; #endif BGL_FORALL_OUTEDGES_T(v, e, g, Graph) { #ifdef PRINT_DEBUG std::cout << target(e, g) << ", "; #endif if (v == target(e, g)) continue; if (get(mis, target(e, g)) == MIS_FIX1) { std::cout << "[FAIL] Vertex : " << v << " and its neigbour " << target(e, g) << " are both in MIS." << " Vertex value : " << get(mis, v) << " neighbor value : " << get(mis, target(e, g)) << std::endl; std::cout << "Neighbors of " << v << "- {"; BGL_FORALL_ADJ_T(v, u1, g, Graph) { std::cout << "(" << u1 << ", " << get(mis, u1) << ")"; } std::cout << "}" << std::endl; auto k = target(e, g); if (get(owner, k) == g.transport().rank()) { std::cout << "Neighbors of " << k << "- {"; BGL_FORALL_ADJ_T(k, u2, g, Graph) { std::cout << "(" << u2 << ", " << get(mis, u2) << ")"; } std::cout << "}" << std::endl; } result = false; } else { #ifdef PRINT_DEBUG if (get(mis, target(e, g)) != MIS_FIX0) { std::cout << "vertex : " << target(e, g) << ", is in " << get(mis, target(e, g)) << std::endl; } #endif // cannot be MIS_UNFIX assert(get(mis, target(e, g)) == MIS_FIX0); found_mis = 1; } } #ifdef PRINT_DEBUG std::cout << "], "; #endif } else { // if v is not in mis, at least one of its neighbors must // be in mis if (get(mis, v) != MIS_FIX0) { std::cout << "[ERROR] Vertex - " << v << " is in " << get(mis, v) << std::endl; } if (get(mis, v) != MIS_FIX0) { std::cout << "Error : " << v << " is not in MIS_FIX0. But in " << get(mis, v) << std::endl; BGL_FORALL_OUTEDGES_T(v, e, g, Graph) { auto k = target(e, g); std::cout << "neigbor : " << k << " mis : " << get(mis, k) << std::endl; } } assert(get(mis, v) == MIS_FIX0); bool inmis = false; BGL_FORALL_OUTEDGES_T(v, e, g, Graph) { if (v == target(e, g)) continue; if (get(mis, target(e, g)) == MIS_FIX1) { inmis = true; break; } } if (!inmis) { std::cout << "Vertex : " << v << " and none of its neighbors is in MIS" << std::endl; assert(false); } } } #ifdef PRINT_DEBUG std::cout << "}" << std::endl; #endif // Run a reduction on found mis. // We cannot expect every rank will have found_mis true. // E.g:- rank0 - {0,1}, rank1 - {281474976710656, 281474976710657} // If every vertex is connect to each other, a vertex (Lets say 0) will // be in one rank. In the second rank all vertices are out of mis. int or_found_mis = 0; MPI_Allreduce(&found_mis, &or_found_mis, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD); if (or_found_mis == 0) { std::cout << "Did not find any MIS" <<std::endl; result = false; } return result; } //=================================================// // vertex id distributions enum id_distribution_t { vertical, horizontal }; //=================================================// template <typename PriorityQueueGenerator = boost::graph::distributed::thread_priority_queue_gen, typename Graph, typename MISMap, typename MessageGenerator> time_type run_fix_mis(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, MISMap& mis, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, MessageGenerator msg_gen, int flushFreq) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; if (trans.rank() == 0) std::cout << "Initializing mis map ..." << std::endl; BGL_FORALL_VERTICES_T(v, g, Graph) { put(mis, v, MIS_UNFIX); } trans.set_nthreads(num_threads); if (trans.rank() == 0) std::cout << "Creating algorithm instance ..." << std::endl; boost::graph::distributed::maximal_independent_set<Graph, MISMap, PriorityQueueGenerator, MessageGenerator> D(g, mis, trans, flushFreq, msg_gen); trans.set_nthreads(1); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif // Many threads now trans.set_nthreads(num_threads); if (trans.rank() == 0) std::cout << "Invoking algorithm ..." << std::endl; boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); if (trans.rank() == 0) std::cout << "Algorithm done ..." << std::endl; time_type start = D.get_start_time(); #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif //#ifdef AMPLUSPLUS_PRINT_HIT_RATES //const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); //print_and_accumulate_cache_stats(stats); //#endif // Back to one thread trans.set_nthreads(1); if (verify) { if (trans.rank()==0) std::cout << "Verifying mis ..." << std::endl; if (!verify_mis(trans, g, mis)) { std::cout << "MIS Verification Failed" << std::endl; assert(false); return 0; } } vertices_size_type visited = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(mis, v) != MIS_UNFIX) ++visited; } boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > r(trans, std::plus<vertices_size_type>()); vertices_size_type total = r(visited); if (verify) if (trans.rank() == 0) std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << std::endl; //if (total < 100) return -1.; return end - start; } template <typename Graph, typename MISMap, typename MessageGenerator> time_type run_fix_mis_bucket(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, MISMap& mis, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, MessageGenerator msg_gen, int flushFreq) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; if (trans.rank() == 0) std::cout << "Initializing mis-delta map ..." << std::endl; BGL_FORALL_VERTICES_T(v, g, Graph) { put(mis, v, MIS_UNFIX); } trans.set_nthreads(num_threads); if (trans.rank() == 0) std::cout << "Creating algorithm instance ..." << std::endl; boost::graph::distributed::maximal_independent_set_delta<Graph, MISMap, append_buffer<Vertex, 10u>, MessageGenerator> D(g, mis, trans, flushFreq, msg_gen); trans.set_nthreads(1); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif // Many threads now trans.set_nthreads(num_threads); if (trans.rank() == 0) std::cout << "Invoking algorithm ..." << std::endl; boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); if (trans.rank() == 0) std::cout << "Algorithm done ..." << std::endl; time_type start = D.get_start_time(); #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif //#ifdef AMPLUSPLUS_PRINT_HIT_RATES //const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); //print_and_accumulate_cache_stats(stats); //#endif // Back to one thread trans.set_nthreads(1); if (verify) { if (trans.rank()==0) std::cout << "Verifying delta mis ..." << std::endl; if (!verify_mis(trans, g, mis)) { std::cout << "Delta-MIS Verification Failed" << std::endl; assert(false); return 0; } } vertices_size_type visited = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(mis, v) != MIS_UNFIX) ++visited; } boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > r(trans, std::plus<vertices_size_type>()); vertices_size_type total = r(visited); if (verify) if (trans.rank() == 0) std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << std::endl; //if (total < 100) return -1.; return end - start; } template <typename SelectGenerator, typename Graph, typename MISMap, typename MessageGenerator> time_type run_luby_maximal_is(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, MISMap& mis, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, MessageGenerator msg_gen, int flushFreq) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; typedef typename property_map<Graph, vertex_index_t>::type VertexIndexMap; typedef iterator_property_map<typename std::vector<random_t>::iterator, VertexIndexMap> RandomMap; // create a property map std::vector<random_t> pivec(num_vertices(g), 0); RandomMap rmap(pivec.begin(), get(vertex_index, g)); // TODO remove copying if (trans.rank() == 0) std::cout << "Initializing mis map ..." << std::endl; BGL_FORALL_VERTICES_T(v, g, Graph) { put(mis, v, MIS_UNFIX); } trans.set_nthreads(num_threads); if (trans.rank() == 0) std::cout << "Creating algorithm instance ..." << std::endl; boost::graph::distributed::luby_mis<Graph, MISMap, RandomMap, // boost::graph::distributed::select_a_functor_gen, SelectGenerator, MessageGenerator> D(g, mis, rmap, n, trans, flushFreq, msg_gen); trans.set_nthreads(1); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif // Many threads now trans.set_nthreads(num_threads); if (trans.rank() == 0) std::cout << "Invoking algorithm ..." << std::endl; boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); if (trans.rank() == 0) std::cout << "Algorithm done ..." << std::endl; time_type start = D.get_start_time(); #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif //#ifdef AMPLUSPLUS_PRINT_HIT_RATES //const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); //print_and_accumulate_cache_stats(stats); //#endif // Back to one thread trans.set_nthreads(1); if (verify) { if (trans.rank()==0) std::cout << "Verifying mis ..." << std::endl; if (!verify_mis(trans, g, mis)) { std::cout << "MIS Verification Failed" << std::endl; assert(false); return 0; } } vertices_size_type visited = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(mis, v) != MIS_UNFIX) ++visited; } boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > r(trans, std::plus<vertices_size_type>()); vertices_size_type total = r(visited); if (verify) if (trans.rank() == 0) std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << std::endl; //if (total < 100) return -1.; return end - start; } template <typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator> time_type run_kla_sssp(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, const WeightMap& weight, DistanceMap& distance, typename graph_traits<Graph>::vertex_descriptor current_source, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, bool level_sync, MessageGenerator msg_gen, size_t k_level) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; typedef typename property_traits<WeightMap>::value_type Dist; BGL_FORALL_VERTICES_T(v, g, Graph) { put(distance, v, std::numeric_limits<weight_type>::max()); } trans.set_nthreads(num_threads); boost::graph::distributed::kla_shortest_paths_buffer<Graph, DistanceMap, WeightMap, append_buffer<std::pair<Vertex, std::pair<Dist, size_t> >, 10u>, MessageGenerator> D(g, distance, weight, trans, k_level, msg_gen); trans.set_nthreads(1); D.set_source(current_source); if (level_sync) D.set_level_sync(); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); time_type start = D.get_start_time(); #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); print_and_accumulate_cache_stats(stats); #endif #ifdef PBGL2_PRINT_WORK_STATS size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source); work_stats_t work_stats = D.get_work_stats(); print_and_accumulate_work_stats(work_stats, ds_stats, edges_in_comp); #endif // Back to one thread trans.set_nthreads(1); unsigned long long num_levels = D.get_num_levels(); if (verify) { verify_sssp(trans, g, distance, weight); } vertices_size_type visited = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(distance, v) < std::numeric_limits<weight_type>::max()) ++visited; } boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > r(trans, std::plus<vertices_size_type>()); vertices_size_type total = r(visited); if (verify) if (trans.rank() == 0) std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << ", " << num_levels << " levels required." << std::endl; if (total < 100) return -1.; return end - start; } template <typename PriorityQueueGenerator = boost::graph::distributed::numa_priority_queue_gen, typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator> time_type run_kla_sssp_numa(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, const WeightMap& weight, DistanceMap& distance, typename graph_traits<Graph>::vertex_descriptor current_source, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, bool level_sync, MessageGenerator msg_gen, size_t k_level, int flushFreq) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; typedef typename property_traits<WeightMap>::value_type Dist; BGL_FORALL_VERTICES_T(v, g, Graph) { put(distance, v, std::numeric_limits<weight_type>::max()); } trans.set_nthreads(num_threads); #ifdef LIB_CDS // LIBCDS Stuff goes here if (trans.rank() == 0) std::cout << "Initializing LIBCDS .... " << std::endl; cds::Initialize(); // Initialize Hazard Pointer singleton cds::gc::HP hpGC; // Attach for the main thread cds::threading::Manager::attachThread(); #endif boost::graph::distributed::kla_shortest_paths_numa<Graph, DistanceMap, WeightMap, PriorityQueueGenerator, MessageGenerator> D(g, distance, weight, trans, k_level, flushFreq, msg_gen); trans.set_nthreads(1); D.set_source(current_source); if (level_sync) D.set_level_sync(); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); time_type start = D.get_start_time(); #ifdef LIB_CDS if (trans.rank() == 0) std::cout << "Termminating LIBCDS .... " << std::endl; cds::Terminate(); #endif #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); print_and_accumulate_cache_stats(stats); #endif #ifdef PBGL2_PRINT_WORK_STATS size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source); work_stats_t work_stats = D.get_work_stats(); print_and_accumulate_work_stats(work_stats, ds_stats, edges_in_comp); #endif // Back to one thread trans.set_nthreads(1); unsigned long long num_levels = D.get_num_levels(); if (verify) { verify_sssp(trans, g, distance, weight); } vertices_size_type visited = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(distance, v) < std::numeric_limits<weight_type>::max()) ++visited; } boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > r(trans, std::plus<vertices_size_type>()); vertices_size_type total = r(visited); if (verify) if (trans.rank() == 0) std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << ", " << num_levels << " levels required." << std::endl; if (total < 100) return -1.; return end - start; } template <typename PriorityQueueGenerator = boost::graph::distributed::numa_priority_queue_gen, typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator> time_type run_kla_sssp_thread(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, const WeightMap& weight, DistanceMap& distance, typename graph_traits<Graph>::vertex_descriptor current_source, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, bool level_sync, MessageGenerator msg_gen, size_t k_level, int flushFreq) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; typedef typename property_traits<WeightMap>::value_type Dist; BGL_FORALL_VERTICES_T(v, g, Graph) { put(distance, v, std::numeric_limits<weight_type>::max()); } trans.set_nthreads(num_threads); boost::graph::distributed::kla_shortest_paths_thread<Graph, DistanceMap, WeightMap, PriorityQueueGenerator, MessageGenerator> D(g, distance, weight, trans, k_level,flushFreq, msg_gen); trans.set_nthreads(1); D.set_source(current_source); if (level_sync) D.set_level_sync(); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); time_type start = D.get_start_time(); #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); print_and_accumulate_cache_stats(stats); #endif #ifdef PBGL2_PRINT_WORK_STATS size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source); work_stats_t work_stats = D.get_work_stats(); print_and_accumulate_work_stats(work_stats, ds_stats, edges_in_comp); #endif // Back to one thread trans.set_nthreads(1); unsigned long long num_levels = D.get_num_levels(); if (verify) { verify_sssp(trans, g, distance, weight); } vertices_size_type visited = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(distance, v) < std::numeric_limits<weight_type>::max()) ++visited; } boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > r(trans, std::plus<vertices_size_type>()); vertices_size_type total = r(visited); if (verify) if (trans.rank() == 0) std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << ", " << num_levels << " levels required." << std::endl; if (total < 100) return -1.; return end - start; } template <typename PriorityQueueGenerator = boost::graph::distributed::numa_priority_queue_gen, typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator> time_type run_kla_sssp_node(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, const WeightMap& weight, DistanceMap& distance, typename graph_traits<Graph>::vertex_descriptor current_source, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, bool level_sync, MessageGenerator msg_gen, size_t k_level, int flushFreq) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; typedef typename property_traits<WeightMap>::value_type Dist; BGL_FORALL_VERTICES_T(v, g, Graph) { put(distance, v, std::numeric_limits<weight_type>::max()); } trans.set_nthreads(num_threads); #ifdef LIB_CDS // LIBCDS Stuff goes here if (trans.rank() == 0) std::cout << "Initializing LIBCDS .... " << std::endl; cds::Initialize(); // Initialize Hazard Pointer singleton cds::gc::HP hpGC; // Attach for the main thread cds::threading::Manager::attachThread(); #endif boost::graph::distributed::kla_shortest_paths_node<Graph, DistanceMap, WeightMap, PriorityQueueGenerator, MessageGenerator> D(g, distance, weight, trans, k_level, flushFreq, msg_gen); trans.set_nthreads(1); D.set_source(current_source); if (level_sync) D.set_level_sync(); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); time_type start = D.get_start_time(); #ifdef LIB_CDS if (trans.rank() == 0) std::cout << "Termminating LIBCDS .... " << std::endl; cds::Terminate(); #endif #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); print_and_accumulate_cache_stats(stats); #endif #ifdef PBGL2_PRINT_WORK_STATS size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source); work_stats_t work_stats = D.get_work_stats(); print_and_accumulate_work_stats(work_stats, ds_stats, edges_in_comp); #endif // Back to one thread trans.set_nthreads(1); unsigned long long num_levels = D.get_num_levels(); if (verify) { verify_sssp(trans, g, distance, weight); } vertices_size_type visited = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(distance, v) < std::numeric_limits<weight_type>::max()) ++visited; } boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > r(trans, std::plus<vertices_size_type>()); vertices_size_type total = r(visited); if (verify) if (trans.rank() == 0) std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << ", " << num_levels << " levels required." << std::endl; if (total < 100) return -1.; return end - start; } template <typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator> time_type run_delta_stepping(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, const WeightMap& weight, DistanceMap& distance, typename graph_traits<Graph>::vertex_descriptor current_source, weight_type delta, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, bool level_sync, MessageGenerator msg_gen) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; BGL_FORALL_VERTICES_T(v, g, Graph) { put(distance, v, std::numeric_limits<weight_type>::max()); } trans.set_nthreads(num_threads); boost::graph::distributed::delta_stepping_shortest_paths<Graph, DistanceMap, WeightMap, append_buffer<Vertex, 10u>, MessageGenerator> D(g, distance, weight, trans, delta, msg_gen); trans.set_nthreads(1); D.set_source(current_source); if (level_sync) D.set_level_sync(); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); time_type start = D.get_start_time(); #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); print_and_accumulate_cache_stats(stats); #endif #ifdef PBGL2_PRINT_WORK_STATS size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source); work_stats_t work_stats = D.get_work_stats(); print_and_accumulate_work_stats(work_stats, ds_stats, edges_in_comp); #endif // Back to one thread trans.set_nthreads(1); unsigned long long num_levels = D.get_num_levels(); if (verify) verify_sssp(trans, g, distance, weight); vertices_size_type visited = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(distance, v) < std::numeric_limits<weight_type>::max()) ++visited; } boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > r(trans, std::plus<vertices_size_type>()); vertices_size_type total = r(visited); if (verify) if (trans.rank() == 0) std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << ", " << num_levels << " levels required." << std::endl; if (total < 100) return -1.; return end - start; } template <typename PriorityQueueGenerator = boost::graph::distributed::default_priority_queue_gen, typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator> time_type run_delta_stepping_node(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, const WeightMap& weight, DistanceMap& distance, typename graph_traits<Graph>::vertex_descriptor current_source, weight_type delta, int num_threads, typename graph_traits<Graph>:: vertices_size_type n, bool verify, bool level_sync, MessageGenerator msg_gen, int flushFreq) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; BGL_FORALL_VERTICES_T(v, g, Graph) { put(distance, v, std::numeric_limits<weight_type>::max()); } trans.set_nthreads(num_threads); #ifdef LIB_CDS // LIBCDS Stuff goes here if (trans.rank() == 0) std::cout << "Initializing LIBCDS .... " << std::endl; cds::Initialize(); // Initialize Hazard Pointer singleton cds::gc::HP hpGC; // Attach for the main thread cds::threading::Manager::attachThread(); #endif boost::graph::distributed::delta_stepping_shortest_paths_node<Graph, DistanceMap, WeightMap, PriorityQueueGenerator, MessageGenerator> D(g, distance, weight, trans, delta, flushFreq, msg_gen); trans.set_nthreads(1); D.set_source(current_source); if (level_sync) D.set_level_sync(); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); time_type start = D.get_start_time(); #ifdef LIB_CDS if (trans.rank() == 0) std::cout << "Termminating LIBCDS .... " << std::endl; cds::Terminate(); #endif #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); print_and_accumulate_cache_stats(stats); #endif #ifdef PBGL2_PRINT_WORK_STATS size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source); work_stats_t work_stats = D.get_work_stats(); print_and_accumulate_work_stats(work_stats, ds_stats, edges_in_comp); #endif // Back to one thread trans.set_nthreads(1); unsigned long long num_levels = D.get_num_levels(); if (verify) verify_sssp(trans, g, distance, weight); vertices_size_type visited = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(distance, v) < std::numeric_limits<weight_type>::max()) ++visited; } boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > r(trans, std::plus<vertices_size_type>()); vertices_size_type total = r(visited); if (verify) if (trans.rank() == 0) std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << ", " << num_levels << " levels required." << std::endl; if (total < 100) return -1.; return end - start; } template <typename PriorityQueueGenerator = boost::graph::distributed::default_priority_queue_gen, typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator> time_type run_delta_stepping_numa(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, const WeightMap& weight, DistanceMap& distance, typename graph_traits<Graph>::vertex_descriptor current_source, weight_type delta, int num_threads, typename graph_traits<Graph>:: vertices_size_type n, bool verify, bool level_sync, MessageGenerator msg_gen, int flushFreq) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; BGL_FORALL_VERTICES_T(v, g, Graph) { put(distance, v, std::numeric_limits<weight_type>::max()); } trans.set_nthreads(num_threads); #ifdef LIB_CDS // LIBCDS Stuff goes here if (trans.rank() == 0) std::cout << "Initializing LIBCDS .... " << std::endl; cds::Initialize(); // Initialize Hazard Pointer singleton cds::gc::HP hpGC; // Attach for the main thread cds::threading::Manager::attachThread(); #endif boost::graph::distributed::delta_stepping_shortest_paths_numa<Graph, DistanceMap, WeightMap, PriorityQueueGenerator, MessageGenerator> D(g, distance, weight, trans, delta, flushFreq, msg_gen); trans.set_nthreads(1); D.set_source(current_source); if (level_sync) D.set_level_sync(); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); time_type start = D.get_start_time(); #ifdef LIB_CDS if (trans.rank() == 0) std::cout << "Termminating LIBCDS .... " << std::endl; cds::Terminate(); #endif #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); print_and_accumulate_cache_stats(stats); #endif #ifdef PBGL2_PRINT_WORK_STATS size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source); work_stats_t work_stats = D.get_work_stats(); print_and_accumulate_work_stats(work_stats, ds_stats, edges_in_comp); #endif // Back to one thread trans.set_nthreads(1); unsigned long long num_levels = D.get_num_levels(); if (verify) verify_sssp(trans, g, distance, weight); vertices_size_type visited = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(distance, v) < std::numeric_limits<weight_type>::max()) ++visited; } boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > r(trans, std::plus<vertices_size_type>()); vertices_size_type total = r(visited); if (verify) if (trans.rank() == 0) std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << ", " << num_levels << " levels required." << std::endl; if (total < 100) return -1.; return end - start; } template <typename PriorityQueueGenerator = boost::graph::distributed::default_priority_queue_gen, typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator> time_type run_delta_stepping_thread(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, const WeightMap& weight, DistanceMap& distance, typename graph_traits<Graph>::vertex_descriptor current_source, weight_type delta, int num_threads, typename graph_traits<Graph>:: vertices_size_type n, bool verify, bool level_sync, MessageGenerator msg_gen, int flushFreq) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; BGL_FORALL_VERTICES_T(v, g, Graph) { put(distance, v, std::numeric_limits<weight_type>::max()); } trans.set_nthreads(num_threads); boost::graph::distributed::delta_stepping_shortest_paths_thread<Graph, DistanceMap, WeightMap, PriorityQueueGenerator, MessageGenerator> D(g, distance, weight, trans, delta, flushFreq, msg_gen); trans.set_nthreads(1); D.set_source(current_source); if (level_sync) D.set_level_sync(); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); time_type start = D.get_start_time(); #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); print_and_accumulate_cache_stats(stats); #endif #ifdef PBGL2_PRINT_WORK_STATS size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source); work_stats_t work_stats = D.get_work_stats(); print_and_accumulate_work_stats(work_stats, ds_stats, edges_in_comp); #endif // Back to one thread trans.set_nthreads(1); unsigned long long num_levels = D.get_num_levels(); if (verify) verify_sssp(trans, g, distance, weight); vertices_size_type visited = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(distance, v) < std::numeric_limits<weight_type>::max()) ++visited; } boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > r(trans, std::plus<vertices_size_type>()); vertices_size_type total = r(visited); if (verify) if (trans.rank() == 0) std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << ", " << num_levels << " levels required." << std::endl; if (total < 100) return -1.; return end - start; } template <typename PriorityQueueGenerator = boost::graph::distributed::pheet_priority_queue_gen_128, typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator> time_type run_distributed_control_pheet(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, const WeightMap& weight, DistanceMap& distance, typename graph_traits<Graph>::vertex_descriptor current_source, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, MessageGenerator msg_gen, MessageGenerator priority_msg_gen, unsigned int flushFreq, unsigned int eager_limit) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; // Initialize with infinite (max) distance BGL_FORALL_VERTICES_T(v, g, Graph) { put(distance, v, std::numeric_limits<weight_type>::max()); } trans.set_nthreads(num_threads); boost::graph::distributed::distributed_control_pheet<Graph, DistanceMap, WeightMap, PriorityQueueGenerator, MessageGenerator> D(g, distance, weight, trans, msg_gen, priority_msg_gen, flushFreq, eager_limit); trans.set_nthreads(1); //trans.set_recvdepth(recvDepth); D.set_source(current_source); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); // TODO: Add exception handling. Excptions should be caught in every thread and checked in the main thread. for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); time_type start = D.get_start_time(); #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); print_and_accumulate_cache_stats(stats); #endif #ifdef PBGL2_PRINT_WORK_STATS // calculate the number of edges size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source); work_stats_t work_stats = D.get_work_stats(); print_and_accumulate_work_stats(work_stats, dc_stats, edges_in_comp); #endif // Back to one thread trans.set_nthreads(1); #ifdef PBGL2_PRINT_WORK_STATS //get the queue size size_t local_q_size = D.get_max_q_size(); print_q_stats(local_q_size); #endif if (verify) verify_sssp(trans, g, distance, weight); vertices_size_type visited = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(distance, v) < std::numeric_limits<weight_type>::max()) ++visited; } boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > r(trans, std::plus<vertices_size_type>()); vertices_size_type total = r(visited); if (verify) if (trans.rank() == 0) std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << "\n" << std::endl; if (total < 100) return -1.; return end - start; } template <typename PriorityQueueGenerator = boost::graph::distributed::default_priority_queue_gen, typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator> time_type run_distributed_control_node(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, const WeightMap& weight, DistanceMap& distance, typename graph_traits<Graph>::vertex_descriptor current_source, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, MessageGenerator msg_gen, MessageGenerator priority_msg_gen, unsigned int flushFreq, unsigned int eager_limit, bool numa=false) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; // Initialize with infinite (max) distance BGL_FORALL_VERTICES_T(v, g, Graph) { put(distance, v, std::numeric_limits<weight_type>::max()); } trans.set_nthreads(num_threads); #ifdef LIB_CDS // LIBCDS Stuff goes here if (trans.rank() == 0) std::cout << "Initializing LIBCDS .... " << std::endl; cds::Initialize(); // Initialize Hazard Pointer singleton cds::gc::HP hpGC; // Attach for the main thread cds::threading::Manager::attachThread(); #endif boost::graph::distributed::distributed_control_node<Graph, DistanceMap, WeightMap, PriorityQueueGenerator, MessageGenerator> D(g, distance, weight, trans, msg_gen, priority_msg_gen, flushFreq, eager_limit, numa); trans.set_nthreads(1); //trans.set_recvdepth(recvDepth); D.set_source(current_source); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); // TODO: Add exception handling. Excptions should be caught in every thread and checked in the main thread. for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); time_type start = D.get_start_time(); #ifdef LIB_CDS if (trans.rank() == 0) std::cout << "Termminating LIBCDS .... " << std::endl; cds::Terminate(); #endif #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); print_and_accumulate_cache_stats(stats); #endif #ifdef PBGL2_PRINT_WORK_STATS size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source); work_stats_t work_stats = D.get_work_stats(); print_and_accumulate_work_stats(work_stats, dc_stats, edges_in_comp); #endif // Back to one thread trans.set_nthreads(1); #ifdef PBGL2_PRINT_WORK_STATS //get the queue size size_t local_q_size = D.get_max_q_size(); print_q_stats(local_q_size); #endif if (verify) verify_sssp(trans, g, distance, weight); vertices_size_type visited = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(distance, v) < std::numeric_limits<weight_type>::max()) ++visited; } boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > r(trans, std::plus<vertices_size_type>()); vertices_size_type total = r(visited); if (verify) if (trans.rank() == 0) std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << "\n" << std::endl; if (total < 100) return -1.; return end - start; } // Duplicating code; pretty bad .... // TODO find the metaprogramming way to add cds initialization code template <typename PriorityQueueGenerator = boost::graph::distributed::default_priority_queue_gen, typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator> time_type run_distributed_control(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, const WeightMap& weight, DistanceMap& distance, typename graph_traits<Graph>::vertex_descriptor current_source, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, MessageGenerator msg_gen, MessageGenerator priority_msg_gen, unsigned int flushFreq, unsigned int eager_limit) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; // Initialize with infinite (max) distance BGL_FORALL_VERTICES_T(v, g, Graph) { put(distance, v, std::numeric_limits<weight_type>::max()); } trans.set_nthreads(num_threads); boost::graph::distributed::distributed_control<Graph, DistanceMap, WeightMap, PriorityQueueGenerator, MessageGenerator> D(g, distance, weight, trans, msg_gen, priority_msg_gen, flushFreq, eager_limit); trans.set_nthreads(1); //trans.set_recvdepth(recvDepth); D.set_source(current_source); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); // TODO: Add exception handling. Excptions should be caught in every thread and checked in the main thread. for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); time_type start = D.get_start_time(); #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); print_and_accumulate_cache_stats(stats); #endif #ifdef PBGL2_PRINT_WORK_STATS work_stats_t work_stats = D.get_work_stats(); size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source); print_and_accumulate_work_stats(work_stats, dc_stats, edges_in_comp); // print q stats print_q_stats(D.get_max_q_size(), D.get_avg_max_q_size()); #endif // Back to one thread trans.set_nthreads(1); if (verify) verify_sssp(trans, g, distance, weight); vertices_size_type visited = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(distance, v) < std::numeric_limits<weight_type>::max()) ++visited; } boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > r(trans, std::plus<vertices_size_type>()); vertices_size_type total = r(visited); if (verify) if (trans.rank() == 0) std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << "\n" << std::endl; if (total < 100) return -1.; return end - start; } // Duplicating code; pretty bad .... // TODO find the metaprogramming way to add cds initialization code template <typename Graph, typename WeightMap, typename DistanceMap, typename MessageGenerator> time_type run_distributed_control_chaotic(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, const WeightMap& weight, DistanceMap& distance, typename graph_traits<Graph>::vertex_descriptor current_source, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, MessageGenerator msg_gen, unsigned int flushFreq, unsigned int eager_limit) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; // Initialize with infinite (max) distance BGL_FORALL_VERTICES_T(v, g, Graph) { put(distance, v, std::numeric_limits<weight_type>::max()); } trans.set_nthreads(num_threads); boost::graph::distributed::distributed_control_chaotic<Graph, DistanceMap, WeightMap, MessageGenerator> D(g, distance, weight, trans, msg_gen, flushFreq, eager_limit); trans.set_nthreads(1); //trans.set_recvdepth(recvDepth); D.set_source(current_source); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); // TODO: Add exception handling. Excptions should be caught in every thread and checked in the main thread. for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); time_type start = D.get_start_time(); #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); print_and_accumulate_cache_stats(stats); #endif #ifdef PBGL2_PRINT_WORK_STATS size_t edges_in_comp = count_edges(trans, g, distance, weight, current_source); work_stats_t work_stats = D.get_work_stats(); print_and_accumulate_work_stats(work_stats, dc_stats, edges_in_comp); #endif // Back to one thread trans.set_nthreads(1); if (verify) verify_sssp(trans, g, distance, weight); vertices_size_type visited = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(distance, v) < std::numeric_limits<weight_type>::max()) ++visited; } boost::parallel::all_reduce<vertices_size_type, std::plus<vertices_size_type> > r(trans, std::plus<vertices_size_type>()); vertices_size_type total = r(visited); if (verify) if (trans.rank() == 0) std::cout << "Visited " << total << " vertices of " << n << " in " << print_time(end - start) << "\n" << std::endl; if (total < 100) return -1.; return end - start; } template <typename Graph, typename MessageGenerator> time_type run_ps_sv_cc(amplusplus::transport& trans, Graph& g, int num_threads, bool verify, bool level_sync, MessageGenerator msg_gen, size_t vertices_per_lock) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif if (trans.rank() == 0) std::cout << "Initializing PS-SV-CC algorithm ... " << std::endl; // Instantiate algorithms used later here so we don't time their constructions typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename property_map<Graph, vertex_index_t>::type VertexIndexMap; // Parent, component, and lock maps for SV CC std::vector<Vertex> parentS(num_vertices(g), graph_traits<Graph>::null_vertex()); typedef iterator_property_map<typename std::vector<Vertex>::iterator, VertexIndexMap> ParentMap; ParentMap parent(parentS.begin(), get(vertex_index, g)); std::vector<int> sv_componentS(num_vertices(g), std::numeric_limits<int>::max()); typedef iterator_property_map<std::vector<int>::iterator, VertexIndexMap> ComponentMap; ComponentMap component(sv_componentS.begin(), get(vertex_index, g)); typedef boost::parallel::lock_map<VertexIndexMap> LockMap; LockMap locks(get(vertex_index, g), num_vertices(g) / vertices_per_lock); BGL_FORALL_VERTICES_T(v, g, Graph) { put(parent, v, v); } using boost::parallel::all_reduce; using boost::parallel::maximum; all_reduce<vertices_size_type, maximum<vertices_size_type> > reduce_max(trans, maximum<vertices_size_type>()); // TODO: If level_sync we should make the PS below a BFS boost::graph::distributed::parallel_search<Graph, ParentMap, MessageGenerator> PS(g, parent, graph_traits<Graph>::null_vertex(), msg_gen); trans.set_nthreads(num_threads); boost::graph::distributed::connected_components<Graph, ParentMap, MessageGenerator> CC(trans, g, parent, locks, msg_gen); trans.set_nthreads(1); if (level_sync) CC.set_level_sync(); // Less than on vertices w/ special casing for null_vertex() so we start parallel // search from the same vertex below typedef typename property_map<Graph, vertex_owner_t>::const_type OwnerMap; typedef typename property_map<Graph, vertex_local_t>::const_type LocalMap; typedef graph::distributed::cc_vertex_compare<OwnerMap, LocalMap> VertexLessThan; VertexLessThan vertex_lt(get(vertex_owner, g), get(vertex_local, g)); // // Start timing loop // { amplusplus::scoped_epoch epoch(trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif if (trans.rank() == 0) std::cout << "Starting PS-SV-CC algorithm ... " << std::endl; time_type start = get_time(); // // Find max-degree vertex (gotta time this part too) // Vertex max_v = graph_traits<Graph>::null_vertex(); // Avoid uninitialized warning { vertices_size_type degree = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (out_degree(v, g) > degree) { degree = out_degree(v, g); max_v = v; } } using boost::parallel::all_reduce; using boost::parallel::maximum; vertices_size_type max = reduce_max(degree); // If the max-degree vertex is somewhere else then clear local max v // Note: This fails to handle two vertices with the same degree... in // that case the parallel search may start from more than one // vertex, which is perfectly acceptable provided they're in the // same component... a reasonable but not fool-proof assumption if (max != degree) max_v = graph_traits<Graph>::null_vertex(); } // Find global minimum vertex w/ max degree as source so all procs start // at the same place all_reduce<Vertex, VertexLessThan> min_vertex(trans, vertex_lt); max_v = min_vertex(max_v); // // Run parallel search from max_v, this will mark all reachable vertices with // null_vertex() in parent map // PS.run(max_v); #ifdef PRINT_STATS all_reduce<vertices_size_type, std::plus<vertices_size_type> > reduce_plus(trans, std::plus<vertices_size_type>()); vertices_size_type giant_component_count = 0; BGL_FORALL_VERTICES_T(v, g, Graph) { if (get(parent, v) == graph_traits<Graph>::null_vertex()) ++giant_component_count; } vertices_size_type total = reduce_plus(giant_component_count); if (verify) if (trans.rank() == 0) std::cout << total << " vertices in giant component\n"; #endif // // Run SV CC on filtered graph // trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(CC), i + 1); threads[i].swap(thr); } CC(0); for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif if (trans.rank() == 0) std::cout << "Done with PS-SV-CC algorithm in : " << (end-start) << std::endl; // Back to one thread trans.set_nthreads(1); #ifdef NUMBER_COMPONENTS #error "Should be disabled for performance testing" int num_components = CC.template number_components<ComponentMap>(component); if (trans.rank() == 0) std::cout << num_components << " components found\n"; #endif if (verify) { if (trans.rank() == 0) std::cout << "Verifying PS-SV-CC algorithm ... " << std::endl; parent.set_consistency_model(boost::parallel::cm_forward); parent.set_max_ghost_cells(0); { amplusplus::scoped_epoch epoch(g.transport()); BGL_FORALL_VERTICES_T(v, g, Graph) { BGL_FORALL_OUTEDGES_T(v, e, g, Graph) { get(parent, source(e, g)); get(parent, target(e, g)); } } } BGL_FORALL_VERTICES_T(v, g, Graph) { BGL_FORALL_ADJ_T(v, u, g, Graph) { #ifdef PRINT_DEBUG if (get(parent, v) != get(parent, u)) std::cout << trans.rank() << ": parent(" << get(get(vertex_local, g), v) << "@" << get(get(vertex_owner, g), v) << ") = " << get(get(vertex_local, g), get(parent, v)) << "@" << get(get(vertex_owner, g), get(parent, v)) << " parent(" << get(get(vertex_local, g), u) << "@" << get(get(vertex_owner, g), u) << ") = " << get(get(vertex_local, g), get(parent, u)) << "@" << get(get(vertex_owner, g), get(parent, u)) << std::endl; #else assert(get(parent, v) == get(parent, u)); #endif } } parent.clear(); // Clear memory used by ghost cells } return time_type(end - start); } template <typename Graph, typename MessageGenerator> time_type run_sv_c_c(amplusplus::transport& trans, Graph& g, int num_threads, bool verify, bool level_sync, MessageGenerator msg_gen, size_t vertices_per_lock) { #ifdef CLONE amplusplus::transport trans = trans_passed.clone(); // Clone transport for this run #endif if (trans.rank() == 0) std::cout << "Initializing SV-CC algorithm ... " << std::endl; // Instantiate algorithms used later here so we don't time their constructions typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename property_map<Graph, vertex_index_t>::type VertexIndexMap; // Parent, component, and lock maps for SV CC std::vector<Vertex> parentS(num_vertices(g), graph_traits<Graph>::null_vertex()); typedef iterator_property_map<typename std::vector<Vertex>::iterator, VertexIndexMap> ParentMap; ParentMap parent(parentS.begin(), get(vertex_index, g)); std::vector<int> sv_componentS(num_vertices(g), std::numeric_limits<int>::max()); typedef iterator_property_map<std::vector<int>::iterator, VertexIndexMap> ComponentMap; ComponentMap component(sv_componentS.begin(), get(vertex_index, g)); typedef boost::parallel::lock_map<VertexIndexMap> LockMap; LockMap locks(get(vertex_index, g), num_vertices(g) / vertices_per_lock); if (trans.rank() == 0) std::cout << "Number of vertices : " << num_vertices(g) << std::endl; BGL_FORALL_VERTICES_T(v, g, Graph) { put(parent, v, v); } trans.set_nthreads(num_threads); boost::graph::distributed::sv_cc<Graph, ParentMap, MessageGenerator> CC(trans, g, parent, locks, msg_gen); trans.set_nthreads(1); if (level_sync) CC.set_level_sync(); { amplusplus::scoped_epoch epoch(trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif if (trans.rank() == 0) std::cout << "Starting SV-CC algorithm ... " << std::endl; time_type start = get_time(); // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(CC), i + 1); threads[i].swap(thr); } CC(0); for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); // Back to one thread trans.set_nthreads(1); if (trans.rank() == 0) std::cout << "Done with SV-CC algorithm in : " << (end-start) << std::endl; #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef NUMBER_COMPONENTS int num_components = CC.template number_components<ComponentMap>(component); if (trans.rank() == 0) std::cout << num_components << " components found\n"; #endif CC.print_stats(); if (verify) { if (trans.rank() == 0) std::cout << "Verifying SV-CC algorithm ... " << std::endl; parent.set_consistency_model(boost::parallel::cm_forward); parent.set_max_ghost_cells(0); { amplusplus::scoped_epoch epoch(g.transport()); BGL_FORALL_VERTICES_T(v, g, Graph) { BGL_FORALL_OUTEDGES_T(v, e, g, Graph) { get(parent, source(e, g)); get(parent, target(e, g)); } } } { amplusplus::scoped_epoch epoch(trans); // at the moment get() sends a message BGL_FORALL_VERTICES_T(v, g, Graph) { if (out_degree(v, g) == 0) { assert(get(parent, v) == v); } BGL_FORALL_ADJ_T(v, u, g, Graph) { #ifdef PRINT_DEBUG if (get(parent, v) != get(parent, u)) std::cout << trans.rank() << ": parent(" << get(get(vertex_local, g), v) << "@" << get(get(vertex_owner, g), v) << ") = " << get(get(vertex_local, g), get(parent, v)) << "@" << get(get(vertex_owner, g), get(parent, v)) << " parent(" << get(get(vertex_local, g), u) << "@" << get(get(vertex_owner, g), u) << ") = " << get(get(vertex_local, g), get(parent, u)) << "@" << get(get(vertex_owner, g), get(parent, u)) << std::endl; #else assert(get(parent, v) == get(parent, u)); #endif } } } parent.clear(); // Clear memory used by ghost cells } return time_type(end - start); } template <typename Graph, typename MessageGenerator> time_type run_sv_cc_optimized(amplusplus::transport& trans, Graph& g, int num_threads, bool verify, bool level_sync, MessageGenerator msg_gen, size_t vertices_per_lock) { #ifdef CLONE amplusplus::transport trans = trans_passed.clone(); // Clone transport for this run #endif if (trans.rank() == 0) std::cout << "Initializing SV-CC algorithm ... " << std::endl; // Instantiate algorithms used later here so we don't time their constructions typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename property_map<Graph, vertex_index_t>::type VertexIndexMap; // Parent, component, and lock maps for SV CC std::vector<Vertex> parentS(num_vertices(g), graph_traits<Graph>::null_vertex()); typedef iterator_property_map<typename std::vector<Vertex>::iterator, VertexIndexMap> ParentMap; ParentMap parent(parentS.begin(), get(vertex_index, g)); std::vector<int> sv_componentS(num_vertices(g), std::numeric_limits<int>::max()); typedef iterator_property_map<std::vector<int>::iterator, VertexIndexMap> ComponentMap; ComponentMap component(sv_componentS.begin(), get(vertex_index, g)); typedef boost::parallel::lock_map<VertexIndexMap> LockMap; LockMap locks(get(vertex_index, g), num_vertices(g) / vertices_per_lock); if (trans.rank() == 0) std::cout << "Number of vertices : " << num_vertices(g) << std::endl; BGL_FORALL_VERTICES_T(v, g, Graph) { put(parent, v, v); } trans.set_nthreads(num_threads); boost::graph::distributed::connected_components<Graph, ParentMap, MessageGenerator> CC(trans, g, parent, locks, msg_gen); trans.set_nthreads(1); if (level_sync) CC.set_level_sync(); { amplusplus::scoped_epoch epoch(trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif if (trans.rank() == 0) std::cout << "Starting SV-CC-Opt algorithm ... " << std::endl; time_type start = get_time(); // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(CC), i + 1); threads[i].swap(thr); } CC(0); for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); // Back to one thread trans.set_nthreads(1); if (trans.rank() == 0) std::cout << "Done with SV-CC algorithm in : " << (end-start) << std::endl; #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef NUMBER_COMPONENTS int num_components = CC.template number_components<ComponentMap>(component); if (trans.rank() == 0) std::cout << num_components << " components found\n"; #endif if (verify) { if (trans.rank() == 0) std::cout << "Verifying SV-CC algorithm ... " << std::endl; parent.set_consistency_model(boost::parallel::cm_forward); parent.set_max_ghost_cells(0); { amplusplus::scoped_epoch epoch(g.transport()); BGL_FORALL_VERTICES_T(v, g, Graph) { BGL_FORALL_OUTEDGES_T(v, e, g, Graph) { get(parent, source(e, g)); get(parent, target(e, g)); } } } { amplusplus::scoped_epoch epoch(trans); // at the moment get() sends a message BGL_FORALL_VERTICES_T(v, g, Graph) { if (out_degree(v, g) == 0) { assert(get(parent, v) == v); } BGL_FORALL_ADJ_T(v, u, g, Graph) { #ifdef PRINT_DEBUG if (get(parent, v) != get(parent, u)) std::cout << trans.rank() << ": parent(" << get(get(vertex_local, g), v) << "@" << get(get(vertex_owner, g), v) << ") = " << get(get(vertex_local, g), get(parent, v)) << "@" << get(get(vertex_owner, g), get(parent, v)) << " parent(" << get(get(vertex_local, g), u) << "@" << get(get(vertex_owner, g), u) << ") = " << get(get(vertex_local, g), get(parent, u)) << "@" << get(get(vertex_owner, g), get(parent, u)) << std::endl; #else assert(get(parent, v) == get(parent, u)); #endif } } } parent.clear(); // Clear memory used by ghost cells } return time_type(end - start); } template <typename PriorityQueueGenerator = boost::graph::distributed::cc_default_priority_queue_gen, typename Graph, typename MessageGenerator> time_type run_data_driven_cc(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, bool print_stats, bool allstats, MessageGenerator msg_gen, MessageGenerator priority_msg_gen, unsigned int flushFreq, unsigned int eager_limit) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif if (trans.rank() == 0) std::cout << "Initializing data driven connected components ..." << std::endl; typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; std::vector<Vertex> componentS(num_vertices(g), std::numeric_limits<Vertex>::max()); typedef typename property_map<Graph, vertex_index_t>::type VertexIndexMap; typedef iterator_property_map<typename std::vector<Vertex>::iterator, VertexIndexMap> ComponentsMap; ComponentsMap components(componentS.begin(), get(vertex_index, g)); //#ifndef CC_PRIORITY BGL_FORALL_VERTICES_T(v, g, Graph) { put(components, v, v); } //#endif std::cout << "Rank: " << trans.rank() << ", Number of vertices : " << num_vertices(g) << "Number of edges : " << num_edges(g) << " total vertices : " << n << std::endl; trans.set_nthreads(num_threads); boost::graph::distributed::data_driven_cc<Graph, ComponentsMap, PriorityQueueGenerator, MessageGenerator> D(g, components, trans, msg_gen, priority_msg_gen, flushFreq, eager_limit); trans.set_nthreads(1); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif if (trans.rank() == 0) std::cout << "Invoking DD-CC algorithm ......" << std::endl; // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type start = D.get_start_time(); time_type end = D.get_end_time(); if (trans.rank() == 0) std::cout << "Done with DD-CC algorithm in : " << (end-start) << std::endl; #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES //const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); //print_and_accumulate_cache_stats(stats); #endif #ifdef PBGL2_PRINT_WORK_STATS //work_stats_t work_stats = D.get_work_stats(); //print_and_accumulate_work_stats(work_stats, dc_stats); #endif // Back to one thread trans.set_nthreads(1); if (verify) { verify_cc(g, components); } if (print_stats) calculate_cc_stats(g, components, n, allstats); if (trans.rank() == 0) std::cout << "End invoking algorithm ..." << std::endl; return end - start; } // Run chaotic CC template <typename Graph, typename MessageGenerator> time_type run_chaotic_cc(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, bool print_stats, bool allstats, MessageGenerator msg_gen) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif if (trans.rank() == 0) std::cout << "Initializing data driven connected components ..." << std::endl; typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; std::vector<Vertex> componentS(num_vertices(g), std::numeric_limits<Vertex>::max()); typedef typename property_map<Graph, vertex_index_t>::type VertexIndexMap; typedef iterator_property_map<typename std::vector<Vertex>::iterator, VertexIndexMap> ComponentsMap; ComponentsMap components(componentS.begin(), get(vertex_index, g)); if (trans.rank() == 0) std::cout << "Number of vertices : " << num_vertices(g) << " total : " << n << std::endl; trans.set_nthreads(num_threads); boost::graph::distributed::chaotic_cc<Graph, ComponentsMap, MessageGenerator> D(g, components, trans, n, msg_gen); trans.set_nthreads(1); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif if (trans.rank() == 0) std::cout << "Invoking DD-CC algorithm ......" << std::endl; time_type start = get_time(); // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); // TODO: Add exception handling. Excptions should be caught in every thread and checked in the main thread. for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); if (trans.rank() == 0) std::cout << "Done with Chaotic-CC algorithm in : " << (end-start) << std::endl; #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES //const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); //print_and_accumulate_cache_stats(stats); #endif // Back to one thread trans.set_nthreads(1); if (verify) { verify_cc(g, components); } // end verify if (print_stats) calculate_cc_stats(g, components, n, allstats); if (trans.rank() == 0) std::cout << "End invoking algorithm ..." << std::endl; return end - start; } /** * One-to-one mapping of vertices. In this case * vertex is mapped to running id. Id is increase column wise. * 1 4 * 2 5 * 3 6 */ template<typename Graph> struct block_id_distribution { typedef typename graph_traits<Graph>::vertices_size_type VerticesSzType; public: block_id_distribution(Graph& _pg, VerticesSzType& pn):g(_pg), n(pn) { if (_RANK == 0) std::cout << "[INFO] Using vertical id distribution" << std::endl; } template<typename SizeType> SizeType operator()(SizeType k) { SizeType blocksz = g.distribution().block_size(0, n); return (get(get(vertex_owner, g), k))*blocksz + g.distribution().local(k); } private: Graph& g; VerticesSzType n; }; /** * One-to-one mapping of vertices. In this case * vertex is mapped to running id. Id is increase row wise. * 1 2 * 3 4 * 5 6 */ template<typename Graph> struct row_id_distribution { public: row_id_distribution(Graph& _pg, int ranks):g(_pg), totalranks(ranks) { if (_RANK == 0) std::cout << "[INFO] Using horizontal id distribution" << std::endl; } template<typename SizeType> SizeType operator()(SizeType k) { auto offset = g.distribution().local(k) * totalranks; return offset + get(get(vertex_owner, g), k); } private: Graph& g; int totalranks; }; // Run delta-stepping CC template <typename Graph, typename MessageGenerator, typename IdDistribution> time_type run_delta_cc(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, int num_threads, typename graph_traits<Graph>::vertices_size_type n, size_t nbuckets, IdDistribution idd, bool verify, bool print_stats, bool allstats, MessageGenerator msg_gen) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif if (trans.rank() == 0) std::cout << "Initializing delta connected components with buckets = " << nbuckets << "..." << std::endl; typedef typename graph_traits<Graph>::vertex_descriptor Vertex; #ifdef PRINT_DEBUG block_id_distribution<Graph> logical_block_id(g, n); row_id_distribution<Graph> logical_row_block_id(g, trans.size()); if (trans.rank()==0) { std::cout << "Printing vertex information in rank " << trans.rank() << std::endl; std::cout << "==========================================================" << std::endl; BGL_FORALL_VERTICES_T(v, g, Graph) { std::cout << "vid: " << v << ", local id : " << g.distribution().local(v) << ", logical block id: " << logical_block_id(v) << ", logical row block id : " << logical_row_block_id(v) << std::endl; /* BGL_FORALL_OUTEDGES_T(v, e, g, Graph) { Vertex u = target(e, g); std::cout << "neighbor vid: " << u << ", local id : " << g.distribution().local(u) << ", logical block id: " << logical_block_id(u, g, n) << ", logical row block id : " << logical_row_block_id(u, g, trans.size()) << std::endl; }*/ } } MPI_Barrier(MPI_COMM_WORLD); if (trans.rank()==1) { std::cout << "Printing vertex information in rank " << trans.rank() << std::endl; std::cout << "==========================================================" << std::endl; BGL_FORALL_VERTICES_T(v, g, Graph) { std::cout << "vid: " << v << ", local id : " << g.distribution().local(v) << ", logical block id: " << logical_block_id(v) << ", logical row block id : " << logical_row_block_id(v) << std::endl; } } MPI_Barrier(MPI_COMM_WORLD); if (trans.rank()==2) { std::cout << "Printing vertex information in rank " << trans.rank() << std::endl; std::cout << "==========================================================" << std::endl; BGL_FORALL_VERTICES_T(v, g, Graph) { std::cout << "vid: " << v << ", local id : " << g.distribution().local(v) << ", logical block id: " << logical_block_id(v, g, n) << ", logical row block id : " << logical_row_block_id(v, g, trans.size()) << std::endl; BGL_FORALL_OUTEDGES_T(v, e, g, Graph) { Vertex u = target(e, g); std::cout << "neighbor vid: " << u << ", local id : " << g.distribution().local(u) << ", logical block id: " << logical_block_id(u, g, n) << ", logical row block id : " << logical_row_block_id(u, g, trans.size()) << std::endl; } } } MPI_Barrier(MPI_COMM_WORLD); if (trans.rank()==3) { std::cout << "Printing vertex information in rank " << trans.rank() << std::endl; std::cout << "==========================================================" << std::endl; BGL_FORALL_VERTICES_T(v, g, Graph) { std::cout << "vid: " << v << ", local id" << g.distribution().local(v) << ", logical block id: " << logical_block_id(v, g, n) << ", logical row block id : " << logical_row_block_id(v, g, trans.size()) << std::endl; } } MPI_Barrier(MPI_COMM_WORLD); #endif typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; std::vector<Vertex> componentS(num_vertices(g), std::numeric_limits<Vertex>::max()); typedef typename property_map<Graph, vertex_index_t>::type VertexIndexMap; typedef iterator_property_map<typename std::vector<Vertex>::iterator, VertexIndexMap> ComponentsMap; ComponentsMap components(componentS.begin(), get(vertex_index, g)); BGL_FORALL_VERTICES_T(v, g, Graph) { put(components, v, v); } if (trans.rank() == 0) std::cout << "Number of vertices : " << num_vertices(g) << " total : " << n << std::endl; trans.set_nthreads(num_threads); boost::graph::distributed::delta_stepping_cc<Graph, ComponentsMap, IdDistribution, MessageGenerator> D(g, components, trans, nbuckets, idd, msg_gen); trans.set_nthreads(1); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif if (trans.rank() == 0) std::cout << "Invoking Delta-CC algorithm ......" << std::endl; time_type start = get_time(); // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); // TODO: Add exception handling. Excptions should be caught in every thread and checked in the main thread. for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); if (trans.rank() == 0) std::cout << "Done with Delta-CC algorithm in : " << (end-start) << std::endl; #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES //const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); //print_and_accumulate_cache_stats(stats); #endif // Back to one thread trans.set_nthreads(1); if (verify) { verify_cc(g, components); } if (print_stats) calculate_cc_stats(g, components, n, allstats); if (trans.rank() == 0) std::cout << "End invoking algorithm ..." << std::endl; return end - start; } // Run level CC template <typename Graph, typename MessageGenerator> time_type run_level_sync_cc(amplusplus::transport& trans, amplusplus::transport& barrier_trans, Graph& g, int num_threads, typename graph_traits<Graph>::vertices_size_type n, bool verify, bool print_stats, bool allstats, MessageGenerator msg_gen) { #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for this run #endif if (trans.rank() == 0) std::cout << "Initializing level sync connected components... " << std::endl; typedef typename graph_traits<Graph>::vertex_descriptor Vertex; typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type; std::vector<Vertex> componentS(num_vertices(g), std::numeric_limits<Vertex>::max()); typedef typename property_map<Graph, vertex_index_t>::type VertexIndexMap; typedef iterator_property_map<typename std::vector<Vertex>::iterator, VertexIndexMap> ComponentsMap; ComponentsMap components(componentS.begin(), get(vertex_index, g)); BGL_FORALL_VERTICES_T(v, g, Graph) { put(components, v, v); } if (trans.rank() == 0) std::cout << "Number of vertices : " << num_vertices(g) << " total : " << n << std::endl; trans.set_nthreads(num_threads); boost::graph::distributed::level_sync_cc<Graph, ComponentsMap, MessageGenerator> D(g, components, trans, n, msg_gen); trans.set_nthreads(1); { amplusplus::scoped_epoch epoch(barrier_trans); } #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS epoch_times.clear(); clear_buffer_stats(); #endif if (trans.rank() == 0) std::cout << "Invoking level-sync-CC algorithm ......" << std::endl; // Many threads now trans.set_nthreads(num_threads); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { boost::thread thr(boost::ref(D), i + 1); threads[i].swap(thr); } D(0); for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); time_type end = get_time(); time_type start = D.get_start_time(); if (trans.rank() == 0) std::cout << "Done with level-sync-CC algorithm in : " << (end-start) << ", buckets(levels) processed : " << D.get_num_levels() << std::endl; #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS print_and_clear_epoch_times(); print_buffer_stats(); #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES //const std::pair<unsigned long long, unsigned long long> stats = D.get_cache_stats(); //print_and_accumulate_cache_stats(stats); #endif // Back to one thread trans.set_nthreads(1); if (verify) { verify_cc(g, components); } if (print_stats) calculate_cc_stats(g, components, n, allstats); if (trans.rank() == 0) std::cout << "End invoking algorithm ..." << std::endl; return end - start; } enum mode_type {mode_none, mode_self, mode_async_bfs, mode_ds_async_bfs, mode_level_synchronized_bfs, mode_delta_stepping, mode_dc, mode_connected_components, mode_page_rank}; enum routing_type {rt_none, rt_hypercube, rt_rook}; // functions to separate edge weight and edge // separating edge template<typename t1, typename t2> struct select_edge : std::unary_function< std::pair<t1, std::pair<t1, t2> >, std::pair<t1, t1> > { public: select_edge() {} std::pair<t1, t1> operator()(std::pair<t1, std::pair<t1, t2> >& ew) const { return std::make_pair(ew.first, ew.second.first); } }; // separating edge weight template<typename t1, typename t2> struct select_edge_weight : std::unary_function< std::pair<t1, std::pair<t1, t2> >, t2 > { public: select_edge_weight() {} t2 operator()(std::pair<t1, std::pair<t1, t2> >& ew) const { return ew.second.second; } }; template<typename T> void time_statistics(std::vector<T>& data, T& m, T& minimum, T& q1, T& median, T& q3, T& maximum, T& stddev) { using namespace boost::accumulators; accumulator_set<T, stats<tag::variance> > acc; for_each(data.begin(), data.end(), bind<void>(ref(acc), _1)); m = mean(acc); stddev = sqrt(variance(acc)); auto const min = 0; auto const Q1 = data.size() / 4; auto const Q2 = data.size() / 2; auto const Q3 = Q1 + Q2; auto const max = data.size() - 1; std::nth_element(data.begin(), data.begin() + min, data.end()); minimum = data[min]; std::nth_element(data.begin(), data.begin() + Q1, data.end()); q1 = data[Q1]; std::nth_element(data.begin() + Q1 + 1, data.begin() + Q2, data.end()); median = data[Q2]; std::nth_element(data.begin() + Q2 + 1, data.begin() + Q3, data.end()); q3 = data[Q3]; std::nth_element(data.begin() + Q3 + 1, data.begin() + max, data.end()); maximum = data[max]; } class dc_test { private: std::vector<int> thread_num_vals; size_t scale = 20, num_sources = 64, iterations = 20; double edgefactor = 16; unsigned long long n = static_cast<unsigned long long>(floor(pow(2, scale))); bool verify = false, level_sync = false, stats = true; uint64_t seed64 = 12345; weight_type C = 100; weight_type delta_min = 1, delta_max = 1, delta_step = 1; unsigned int levels_min = 1, levels_max = 1, levels_step = 1; mode_type mode = mode_none; std::vector<routing_type> routing; double edge_list_reserve_factor = 1.15; bool no_reductions = false, per_thread_reductions = true; std::vector<size_t> coalescing_size; size_t distribution_coalescing_size = 1 << 17; std::vector<size_t> reduction_cache_size; std::vector<unsigned int> number_poll_task; std::vector<std::string> dc_data_structures; std::vector<unsigned int> flushFreq; std::vector<unsigned int> eager_limit; std::vector<unsigned int> recvDepth; std::vector<unsigned int> delta; std::vector<unsigned int> k_levels = {1}; std::vector<unsigned int> priority_coalescing_size_v = {40000}; bool run_dc = false, run_chaotic = false, run_ds = false, run_kla = false; // distributions enum distribution_t { block, cyclic }; size_t block_size = 10; // default block distribution distribution_t distribution_type = block; id_distribution_t id_distribution; // mis bool run_ss_mis = false; bool run_bucket_mis = false; bool run_luby_mis = false; std::vector<std::string> luby_algorithms; // connected components bool run_cc = false; std::vector<std::string> cc_algorithms; // Available CC algorithms // 1. run_sv_cc // 2. run_sv_cc_level_sync // 3. run_sv_cc_opt // 4. run_sv_cc_opt_level_sync // 5. run_sv_ps_cc // optimized version // 6. run_sv_ps_cc_level_sync // optmized version // 7. run_dd_cc // 8. run_cc_chaotic // 9. run_cc_ds // delta stepping cc // 10. run_level_sync_cc // level sync agm // data driven connected components size_t vertices_per_lock = 64; std::vector<size_t> nbuckets; size_t cutoff_degree = 0; // CC stats // print CC stats bool print_cc_stats = false; // print all CC stats (otherwise limited to 5) bool allstats = false; // read graph from file std::string graph_file; bool read_graph = false; bool gen_graph = false; bool with_weight = false; public: dc_test(int argc, char* argv[]) { for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; if(arg == "--receive-depth") { recvDepth = extract_params<unsigned int>( argv[i+1] ); //std::cerr<<"receiveDepth from main"<<recvDepth<<std::endl; } if (arg == "--threads") { thread_num_vals = extract_params<int>(argv[i+1]); } if (arg == "--graph-file") { graph_file = argv[i+1]; read_graph = true; } if (arg == "--with-weight") { // read the graph file with weight with_weight = true; } if (arg == "--seed") { seed64 = boost::lexical_cast<uint64_t>( argv[i+1] ); } if (arg == "--scale") { scale = boost::lexical_cast<size_t>( argv[i+1] ); n = (unsigned long long)(1) << scale; gen_graph = true; } if (arg == "--degree") edgefactor = boost::lexical_cast<double>( argv[i+1] ); if (arg == "--num-sources") num_sources = boost::lexical_cast<size_t>( argv[i+1] ); if (arg == "--iterations") iterations = boost::lexical_cast<size_t>( argv[i+1] ); if (arg == "--verify") verify = true; if (arg == "--stats") stats = true; if (arg == "--coalescing-size") { coalescing_size = extract_params<size_t>( argv[i+1] ); } if (arg == "--reduction-cache-size") reduction_cache_size = extract_params<size_t>( argv[i+1] ); if (arg == "--distribution-coalescing-size") distribution_coalescing_size = boost::lexical_cast<size_t>( argv[i+1] ); if (arg == "--distribution") { if (strcmp(argv[i+1],"block") == 0) distribution_type = block; else if (strcmp(argv[i+1],"cyclic") == 0) distribution_type = cyclic; else { std::cout << "Invalid distribution type. Available types are block and cyclic" << std::endl; // abort = true; } } if (arg == "--block-size") { block_size = boost::lexical_cast<size_t>( argv[i+1] ); } if (arg == "--id-distribution") { if (strcmp(argv[i+1],"vertical") == 0) id_distribution = vertical; else if (strcmp(argv[i+1],"horizontal") == 0) id_distribution = horizontal; else { std::cout << "Invalid id distribution type. Available types are vertical and horizontal" << std::endl; // abort = true; } } if (arg == "--max-weight") C = boost::lexical_cast<weight_type>( argv[i+1] ); if(arg == "--poll-task"){ number_poll_task = extract_params<unsigned int>( argv[i+1] ); //std::cerr<<"poll task number:" <<number_poll_task<<"\n"; } if (arg == "--flush") { flushFreq = extract_params<unsigned int> ( argv[i+1] ); } if (arg == "--eager-limit") { eager_limit = extract_params<unsigned int> ( argv[i+1] ); } if (arg == "--priority_coalescing_size") { priority_coalescing_size_v = extract_params<unsigned int> ( argv[i+1] ); } if(arg == "--ds"){ dc_data_structures = extract_params<std::string> ( argv[i+1] ); } if (arg == "--rook") routing.push_back(rt_rook); if (arg == "--rt_none") routing.push_back(rt_none); if (arg == "--with-no-reductions") no_reductions = true; if (arg == "--without-no-reductions") no_reductions = false; if (arg == "--with-per-thread-reductions") per_thread_reductions = true; if (arg == "--without-per-thread-reductions") per_thread_reductions = false; if (arg == "--run_dc") run_dc = true; if (arg == "--run_chaotic") run_chaotic = true; // CC if (arg == "--run_cc") run_cc = true; if (arg == "--cc_algorithms") { cc_algorithms = extract_params<std::string> ( argv[i+1] ); } if (arg == "--vertices-per-lock") { if (!run_cc) { std::cerr << "Vertices per lock is only allowed for Shiloach-Vishky connected components." << std::endl; } vertices_per_lock = boost::lexical_cast<size_t>( argv[i+1] ); } if (arg == "--level-sync") { if (!run_cc) { std::cerr << "Level synch is only allowed for Shiloach-Vishky connected components." << std::endl; return; } level_sync = true; } if (arg == "--buckets") { nbuckets = extract_params<size_t> ( argv[i+1] ); } if (arg == "--print_cc_stats") print_cc_stats = true; if (arg == "--allstats") allstats = true; if (arg == "--cutoff_degree") { cutoff_degree = boost::lexical_cast<size_t>( argv[i+1] ); } // MIS if (arg == "--run_ss_mis") run_ss_mis = true; if (arg == "--run_bucket_mis") run_bucket_mis = true; if (arg == "--run_luby_mis") { run_luby_mis = true; } if (arg == "--luby_algorithms") { luby_algorithms = extract_params<std::string> ( argv[i+1] ); } if (arg == "--run_ds") run_ds = true; if (arg == "--run_kla") run_kla = true; if (arg == "--klevel") k_levels = extract_params<unsigned int> ( argv[i+1] ); if (arg == "--delta") { delta = extract_params<unsigned int> ( argv[i+1] ); } } if (thread_num_vals.empty()) thread_num_vals.push_back(1); if (routing.empty()) routing.push_back(rt_none); // Check for necessary parameters bool abort = false; if (read_graph && gen_graph) { std::cout << "Both generate graph and read graph from file options are specified. Aborting !" << std::endl; abort = true; } if(coalescing_size.empty()) { std::cerr << "Provide a list of coalescing sizes: --coalescing-size x,y,..." << std::endl; abort = true; } if(recvDepth.empty()) { std::cerr << "Provide a list of receive depths: --receive-depth x,y,..." << std::endl; abort = true; } if(number_poll_task.empty()) { std::cerr << "Provide a list of poll tasks: --poll-task x,y,..." << std::endl; abort = true; } if(flushFreq.empty()) { std::cerr << "Provide a list of flush frequencies: --flush x,y,..." << std::endl; abort = true; } if(!(run_dc || run_ds || run_kla || run_cc || run_chaotic || run_ss_mis || run_luby_mis || run_bucket_mis)) { std::cerr << "Select at least one algorithm (--run_dc or --run_ds or" << " --run_kla or --run_cc or --run_chaotic or" << " --run_ss_mis or --run_luby_mis or --run_bucket_mis)." << std::endl; abort = true; } else if (run_cc) { if (cc_algorithms.empty()) { std::cerr << "Must specify atleast one connected component algorithms to run. Options : " << "run_sv_cc, run_sv_ps_cc, run_sv_cc_level_sync, run_sv_ps_cc_level_sync, run_dd_cc, run_cc_chaotic, run_cc_ds, run_level_sync_cc" << ", run_sv_cc_opt, run_sv_cc_opt_level_sync" << std::endl; abort = true; } } if (run_luby_mis && luby_algorithms.empty()) { std::cerr << "Select at least one Luby algorithm using --luby_algorithms. " << "Available algorithms are A, AV1,AV2, B" << std::endl; abort = true; } if(abort) std::abort(); } typedef unsigned long long block_node_t; void test_main(int argc, char* argv[]) { amplusplus::environment env = amplusplus::mpi_environment(argc, argv, true); amplusplus::transport trans = env.create_transport(); amplusplus::transport barrier_trans = trans.clone(); _RANK = trans.rank(); // For performance counter output if (_RANK == 0) { #ifdef NEW_GRAPH500_SPEC std::cout << "Synthetic graph generator used -- RMAT-2" << std::endl; #else std::cout << "Synthetic graph generator used -- RMAT-1" << std::endl; #endif } typedef amplusplus::transport::rank_type rank_type; typedef compressed_sparse_row_graph<directedS, no_property, WeightedEdge, no_property, distributedS<unsigned long long> > Digraph; typedef graph_traits<Digraph>::vertex_descriptor Vertex; typedef graph_traits<Digraph>::edges_size_type edges_size_type; typedef graph_traits<Digraph>::vertices_size_type vertices_size_type; typedef property_map<Digraph, vertex_index_t>::type VertexIndexMap; typedef property_map<Digraph, vertex_owner_t>::const_type OwnerMap; // Output of permutation // edge is expressed as source_vertex, target_vertex // But in the distribution we need source vertex as first element in the pair // Therefore we are putting source vertex first and then another pair with target and weight // So it will be pair<source, pair<target, weight> >. typedef std::vector<std::pair<edges_size_type, std::pair<edges_size_type, weight_type> > > edge_with_weight_t; edge_with_weight_t edges; parallel::variant_distribution<vertices_size_type> distrib; time_type gen_start; // Seed general-purpose RNG rand48 gen, synch_gen; gen.seed(seed64); synch_gen.seed(seed64); typedef generator_iterator<uniform_int<weight_type>, rand48> weight_iterator_t; weight_iterator_t gi = make_generator_iterator(gen, uniform_int<weight_type>(1, C)); if (read_graph) { gen_start = get_time(); std::cout << "Reading graph from file : " << graph_file << std::endl; graph_reader<block_node_t> gr(graph_file.c_str()); gr.read_header(); n = gr.get_num_vertices(); edges_size_type m = gr.get_num_edges(); // reserve space for edges std::cout << "Reserving space for edges : " << m << std::endl; edges.reserve(m); std::cout << "Reserved space for edges." << std::endl; auto bdist = parallel::block<vertices_size_type>(trans, n); // starting position for current rank block_node_t start_index = bdist.start(trans.rank()); // locally stored ids in current rank block_node_t local_count = bdist.block_size(n); distrib = bdist; if (with_weight) { if (_RANK == 0) std::cout << "Reading edges with weights ..." << std::endl; if (!gr.read_edges_with_weight<edges_size_type, weight_type, edge_with_weight_t>(start_index, local_count, edges)) return; } else { if (_RANK == 0) std::cout << "Reading edges with generated weights ..." << std::endl; if (!gr.read_edges_wo_weight<edges_size_type,edge_with_weight_t, weight_iterator_t>(start_index, local_count, edges, gi)) return; } std::cout << "Total number of edges read : " << edges.size() << std::endl; } else { assert(gen_graph); edges_size_type m = static_cast<edges_size_type>(floor(n * edgefactor)); gen_start = get_time(); edges.reserve(static_cast<edges_size_type>(floor(edge_list_reserve_factor * 2 * m / trans.size()))); if (distribution_type == cyclic) { distrib = parallel::oned_block_cyclic<vertices_size_type>(trans, block_size); std::cout << "Distribution is cyclic. block size : " << block_size << std::endl; } else //(distribution_type == block) distrib = parallel::block<vertices_size_type>(trans, n); { boost::uniform_int<uint64_t> rand_64(0, std::numeric_limits<uint64_t>::max()); #ifdef CLONE amplusplus::transport trans = trans.clone(); // Clone transport for distribution #endif edges_size_type e_start = trans.rank() * (m + trans.size() - 1) / trans.size(); edges_size_type e_count = (std::min)((m + trans.size() - 1) / trans.size(), m - e_start); // Permute and redistribute copy constructs the input iterator uint64_t a = rand_64(gen); uint64_t b = rand_64(gen); // Build a graph to test with typedef graph500_iterator<Digraph, generator_iterator<uniform_int<weight_type>, rand48>, weight_type > Graph500Iter; // Select the highest thread val int num_threads = 1; for(unsigned int thread_choice : thread_num_vals) { if (num_threads < thread_choice) num_threads = thread_choice; } // As for now, we assume that only the first routing from the list is used to generate the graph. It seems that it does not really matter which routing we use here since generation of the graph is not a part of the performance test. if (routing[0] == rt_none) { do_distribute<Graph500Iter, amplusplus::no_routing>(distrib, trans, e_start, e_count, a, b, edges, gi, num_threads); } else if (routing[0] == rt_hypercube) { do_distribute<Graph500Iter, amplusplus::hypercube_routing>(distrib, trans, e_start, e_count, a, b, edges, gi, num_threads); } else if (routing[0] == rt_rook) { do_distribute<Graph500Iter, amplusplus::rook_routing>(distrib, trans, e_start, e_count, a, b, edges, gi, num_threads); } } } typedef select_edge<edges_size_type, weight_type> EdgeSelectFunction; typedef transform_iterator<EdgeSelectFunction, edge_with_weight_t::iterator> edge_only_iterator; typedef select_edge_weight<edges_size_type, weight_type> WeightSelectFunction; typedef transform_iterator<WeightSelectFunction, edge_with_weight_t::iterator> weight_only_iterator; edge_only_iterator edge_begin(edges.begin(), EdgeSelectFunction()), edge_end(edges.end(), EdgeSelectFunction()); weight_only_iterator weight_begin(edges.begin(), WeightSelectFunction()); std::cout << "rank -- " << trans.rank() << ", total edges received=" << edges.size() << std::endl; time_type gt1 = get_time(); Digraph g(edges_are_unsorted_multi_pass, edge_begin, edge_end, weight_begin, n, trans, distrib); //Digraph g(edges_are_sorted, edge_begin, edge_end, // weight_begin, n, trans, distrib); time_type gt2 = get_time(); std::cout << "Local graph creation time : " << (gt2-gt1) << std::endl; // Clear edge array above edges.clear(); //============= run some stats ===================// run_grah_stats(g); //Generate sources boost::uniform_int<uint64_t> rand_vertex(0, n-1); { amplusplus::scoped_epoch epoch(trans); } time_type gen_end = get_time(); if (trans.rank() == 0) { std::cout << "Graph generation took " << print_time(gen_end - gen_start) << "s\n"; #ifdef PRINT_DEBUG // Printing graph edges and edge weights // Property maps typedef property_map<Digraph, weight_type WeightedEdge::*>::type WeightMap; WeightMap weight = get(&WeightedEdge::weight, g); typename graph_traits < Digraph >::edge_iterator ei, ei_end; for (boost::tie(ei, ei_end) = boost::edges(g); ei != ei_end; ++ei) { weight_type we = get(weight, *ei); Vertex v = source(*ei, g); std::cout << " Weight - " << we << " edge source : " << boost::source(*ei, g) << " edge target : " << boost::target(*ei, g) << std::endl; } #endif } // Max degree computation and printout /*{ typedef typename graph_traits<Digraph>::degree_size_type Degree; // Compute the maximum edge degree Degree max_degree = 0; BGL_FORALL_VERTICES_T(u, g, Digraph) { max_degree = max BOOST_PREVENT_MACRO_SUBSTITUTION (max_degree, out_degree(u, g)); } // max_degree = all_reduce(process_group(g), max_degree, maximum<Degree>()); all_reduce<Degree, maximum<Degree> > r(trans, maximum<Degree>()); max_degree = r(max_degree); if(trans.rank() == 0) std::cout << "Maximum Degree is " << max_degree << std::endl; }*/ // Property maps typedef property_map<Digraph, weight_type WeightedEdge::*>::type WeightMap; WeightMap weight = get(&WeightedEdge::weight, g); // Distance map std::vector<weight_type> distanceS(num_vertices(g), std::numeric_limits<weight_type>::max()); typedef iterator_property_map<std::vector<weight_type>::iterator, VertexIndexMap> DistanceMap; DistanceMap distance(distanceS.begin(), get(vertex_index, g)); std::string empty_ds = ""; for(unsigned int thread_choice : thread_num_vals) { for(unsigned int coalescing_choice : coalescing_size) { for(unsigned int depth_choice : recvDepth) { for(unsigned int poll_choice : number_poll_task) { for(routing_type routing_choice : routing) { // First print the configuration if(run_dc) { for(unsigned int flush_choice : flushFreq) { for(unsigned int eager_choice : eager_limit) { for(unsigned int priority_coalescing_size : priority_coalescing_size_v) { for (std::string dc_ds : dc_data_structures) { if (trans.rank() == 0) std::cout << "[DC]" << " Data Structure :" << dc_ds << " Threads: " << thread_choice << " Coalescing: " << coalescing_choice << " Poll: " << poll_choice << " Routing: " << routing_choice << " Depth: " << depth_choice; select_alg(env, thread_choice, coalescing_choice, priority_coalescing_size, depth_choice, poll_choice, routing_choice, g, distance, weight, thread_choice, flush_choice, eager_choice, 0, dc_ds, synch_gen, rand_vertex, false, //kla true, //dc false, //ds false, //cc false, //chaotic false, //ss-mis false, // bucket mis false, //luby-mis (size_t)1); } } } } } if (run_ss_mis || run_luby_mis || run_bucket_mis) { for(unsigned int flush_choice : flushFreq) { for (std::string dc_ds : dc_data_structures) { if (run_ss_mis) { if (trans.rank() == 0) std::cout << "[MIS-SS]" << " Data Structure :" << dc_ds << " Threads: " << thread_choice << " Coalescing: " << coalescing_choice << " Poll: " << poll_choice << " Routing: " << routing_choice << " Depth: " << depth_choice << " Flush: " << flush_choice; select_alg(env, thread_choice, coalescing_choice, 10000, depth_choice, poll_choice, routing_choice, g, distance, weight, thread_choice, flush_choice, 0, 0, dc_ds, synch_gen, rand_vertex, false, //kla false, // dc false, // ds false, // cc false, // chaotic true, // ss-mis false, // bucket-mis false, // luby-mis 1); } if (run_bucket_mis) { if (trans.rank() == 0) std::cout << "[MIS-BUCKET]" << " Data Structure :" << dc_ds << " Threads: " << thread_choice << " Coalescing: " << coalescing_choice << " Poll: " << poll_choice << " Routing: " << routing_choice << " Depth: " << depth_choice << " Flush: " << flush_choice; select_alg(env, thread_choice, coalescing_choice, 10000, depth_choice, poll_choice, routing_choice, g, distance, weight, thread_choice, flush_choice, 0, 0, dc_ds, synch_gen, rand_vertex, false, //kla false, // dc false, // ds false, // cc false, // chaotic false, // ss-mis true, //bucket-mis false, // luby-mis 1); } if (run_luby_mis) { for (std::string luby_algo : luby_algorithms) { if (trans.rank() == 0) std::cout << "[MIS-LUBY]" << " Luby Algorithm :" << luby_algo << " Data Structure :" << dc_ds << " Threads: " << thread_choice << " Coalescing: " << coalescing_choice << " Poll: " << poll_choice << " Routing: " << routing_choice << " Depth: " << depth_choice << " Flush: " << flush_choice; select_alg(env, thread_choice, coalescing_choice, 10000, depth_choice, poll_choice, routing_choice, g, distance, weight, thread_choice, flush_choice, 0, 0, dc_ds, synch_gen, rand_vertex, false, //kla false, // dc false, // ds false, // cc false, // chaotic false, // ss-mis false, //bucket mis true, // luby-mis 1, luby_algo); } } } } } if(run_chaotic) { for(unsigned int flush_choice : flushFreq) { for(unsigned int eager_choice : eager_limit) { if (trans.rank() == 0) std::cout << "[Chaotic]" << " Threads: " << thread_choice << " Coalescing: " << coalescing_choice << " Poll: " << poll_choice << " Routing: " << routing_choice << " Depth: " << depth_choice; select_alg(env, thread_choice, coalescing_choice, coalescing_choice, depth_choice, poll_choice, routing_choice, g, distance, weight, thread_choice, flush_choice, eager_choice, 0, empty_ds, synch_gen, rand_vertex, false, //kla false, // dc false, // ds false, // cc true, // chaotic false, //ss-mis false, // bucket mis false, //luby-mis 1); } } } if(run_ds) { // run_ds for(unsigned int delta_choice : delta) { for (std::string dc_ds : dc_data_structures) { for(unsigned int flush_choice : flushFreq) { if (trans.rank() == 0) std::cout << "[Delta]" << " Data Structure :" << dc_ds << " Threads: " << thread_choice << " Flush : " << flush_choice << " Coalescing: " << coalescing_choice << " Poll: " << poll_choice << " Routing: " << routing_choice << " Depth: " << depth_choice; select_alg(env, thread_choice, coalescing_choice, 0, depth_choice, poll_choice, routing_choice, g, distance, weight, thread_choice, flush_choice, 0, delta_choice, dc_ds, synch_gen, rand_vertex, false, //kla false, //dc true, // ds false, // cc false, // chaotic false, //ss-mis false, // bucket mis false, //ss-luby 1); } } } } if(run_kla) { unsigned int delta_choice = 1; for(unsigned int k_level : k_levels) { for (std::string dc_ds : dc_data_structures) { for(unsigned int flush_choice : flushFreq) { if (trans.rank() == 0) std::cout << "[KLA]" << " Data Structure :" << dc_ds << " Threads: " << thread_choice << " Flush : " << flush_choice << " Coalescing: " << coalescing_choice << " Poll: " << poll_choice << " Routing: " << routing_choice << " Depth: " << depth_choice << "k_level: " << k_level; select_alg(env, thread_choice, coalescing_choice, 0, depth_choice, poll_choice, routing_choice, g, distance, weight, thread_choice, flush_choice, 0, delta_choice, dc_ds, synch_gen, rand_vertex, true, //kla false, //dc false, //ds false, //cc false, //chaotic false, //ss-mis false, // bucket mis false, //luby k_level); } } } } if (run_cc) { for (std::string algorithm : cc_algorithms) { if (algorithm == "run_dd_cc") { for(unsigned int flush_choice : flushFreq) { if (trans.rank() == 0) std::cout << "[CC]" << " Algorithm : " << algorithm << " Threads: " << thread_choice << " Coalescing: " << coalescing_choice << " Poll: " << poll_choice << " Routing: " << routing_choice << " Depth: " << depth_choice << " Flush: " << flush_choice; unsigned int delta_choice = 1; select_alg(env, thread_choice, coalescing_choice, 1, depth_choice, poll_choice, routing_choice, g, distance, weight, thread_choice, 0, 0, delta_choice, empty_ds, synch_gen, rand_vertex, false, //kla false, //dc false, //ds true, //cc false, //chaotic false, //ss-mis false, //bucket mis false, //luby 0, // k-level "", // luby algo algorithm); } } else { if (trans.rank() == 0) std::cout << "[CC]" << " Algorithm : " << algorithm << " Threads: " << thread_choice << " Coalescing: " << coalescing_choice << " Poll: " << poll_choice << " Routing: " << routing_choice << " Depth: " << depth_choice; if ("run_cc_ds" == algorithm) { unsigned int delta_choice = 1; // ignore for(size_t bucketsz : nbuckets) { select_alg(env, thread_choice, coalescing_choice, 1, depth_choice, poll_choice, routing_choice, g, distance, weight, thread_choice, 0, 0, delta_choice, empty_ds, synch_gen, rand_vertex, false, //kla false, //dc false, //ds true, //cc false, //chaotic false, //ss-mis false, // bucket mis false, //luby 0, // k-level "", // luby algo algorithm, bucketsz); } } else { // delta is ignored unsigned int delta_choice = 1; select_alg(env, thread_choice, coalescing_choice, 1, depth_choice, poll_choice, routing_choice, g, distance, weight, thread_choice, 0, 0, delta_choice, empty_ds, synch_gen, rand_vertex, false, //kla false, //dc false, //ds true, //cc false, //chaotic false, //ss-mis false, // bucket mis false, //luby 0, // k-level "", // luby algo algorithm); } } } } } } } } } } private: template<typename Result> std::vector<Result> extract_params(const std::string args) { size_t d = 0, d2; std::vector<Result> r; while ((d2 = args.find(',', d)) != std::string::npos) { r.push_back(boost::lexical_cast<Result>(args.substr(d, d2 - d))); d = d2 + 1; } r.push_back(boost::lexical_cast<Result>(args.substr(d, args.length()))); return r; } template<typename Digraph, typename DistanceMap, typename WeightMap, typename RNG, typename RandVertex> void select_alg(amplusplus::environment& env, unsigned int thread_choice, unsigned int coalescing_choice, unsigned int priority_coalescing_size, unsigned int depth_choice, unsigned int poll_choice, routing_type routing_choice, Digraph &g, DistanceMap &distance, WeightMap &weight, unsigned int num_threads, unsigned int flush_choice, unsigned int eager_choice, unsigned int delta_choice, std::string& dc_ds_choice, RNG synch_gen, RandVertex rand_vertex, bool run_kla, bool run_dc, bool run_ds, bool run_cc, bool run_chaotic, bool run_ss_mis, bool run_bucket_mis, bool run_luby_mis, size_t k_level, std::string luby_algo="", std::string cc_algo="", size_t bucket_choice=0) { //run_ds = !run_dc; #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS flushes.reset(new atomic_flush_type[coalescing_choice]); flushes_size = coalescing_choice; all_flushes.resize(coalescing_choice); cumulative_flushes.resize(coalescing_choice); #endif // We will not run two algorithms at once since they have disjoint sets of parameters if(run_dc && run_ds && run_kla) abort(); amplusplus::transport trans = env.create_transport(); amplusplus::transport barrier_trans = trans.clone(); if(run_dc && trans.rank() == 0) { std::cout << " Priority: " << priority_coalescing_size << " Flush: " << flush_choice << " Eager: " << eager_choice; } if(run_ds && trans.rank() == 0) { std::cout << " Delta: " << delta_choice; } if(run_kla && trans.rank() == 0) { std::cout << " k_level: " << k_level<<std::endl; } // Create transport for the algorithm env.template downcast_to_impl<amplusplus::detail::mpi_environment_obj>()->set_poll_tasks(poll_choice); env.template downcast_to_impl<amplusplus::detail::mpi_environment_obj>()->set_recv_depth(depth_choice); if (trans.rank() == 0) std::cout << "per_thread_reductions - " << per_thread_reductions << " no_reductions : " << no_reductions << std::endl; if(per_thread_reductions) { for(unsigned int reduction_choice : reduction_cache_size) { if (trans.rank() == 0) std::cout << " Reduction: " << reduction_choice << std::endl; if (routing_choice == rt_none) { typedef amplusplus::per_thread_cache_generator<amplusplus::counter_coalesced_message_type_gen, amplusplus::no_routing> MessageGenerator; MessageGenerator msg_gen(amplusplus::counter_coalesced_message_type_gen(coalescing_choice), reduction_choice, amplusplus::no_routing(trans.rank(), trans.size())); MessageGenerator priority_msg_gen(amplusplus::counter_coalesced_message_type_gen(priority_coalescing_size, 1), reduction_choice, amplusplus::no_routing(trans.rank(), trans.size())); select_msg_gen(msg_gen, priority_msg_gen, trans, barrier_trans, g, distance, weight, thread_choice, flush_choice, eager_choice, delta_choice, dc_ds_choice, synch_gen, rand_vertex, run_kla, run_dc, run_ds, run_cc, run_chaotic, run_ss_mis, run_bucket_mis, run_luby_mis, k_level, luby_algo, cc_algo, bucket_choice); } if(routing_choice == rt_hypercube) { typedef amplusplus::per_thread_cache_generator<amplusplus::counter_coalesced_message_type_gen, amplusplus::hypercube_routing> MessageGenerator; MessageGenerator msg_gen(amplusplus::counter_coalesced_message_type_gen(coalescing_choice), reduction_choice, amplusplus::hypercube_routing(trans.rank(), trans.size())); MessageGenerator priority_msg_gen(amplusplus::counter_coalesced_message_type_gen(priority_coalescing_size, 1), reduction_choice, amplusplus::hypercube_routing(trans.rank(), trans.size())); select_msg_gen(msg_gen, priority_msg_gen, trans, barrier_trans, g, distance, weight, thread_choice, flush_choice, eager_choice, delta_choice, dc_ds_choice, synch_gen, rand_vertex, run_kla, run_dc, run_ds, run_cc, run_chaotic, run_ss_mis, run_bucket_mis, run_luby_mis, k_level, luby_algo, cc_algo, bucket_choice); } if(routing_choice == rt_rook) { typedef amplusplus::per_thread_cache_generator<amplusplus::counter_coalesced_message_type_gen, amplusplus::rook_routing> MessageGenerator; MessageGenerator msg_gen(amplusplus::counter_coalesced_message_type_gen(coalescing_choice), reduction_choice, amplusplus::rook_routing(trans.rank(), trans.size())); MessageGenerator priority_msg_gen(amplusplus::counter_coalesced_message_type_gen(priority_coalescing_size, 1), reduction_choice, amplusplus::rook_routing(trans.rank(), trans.size())); select_msg_gen(msg_gen, priority_msg_gen, trans, barrier_trans, g, distance, weight, thread_choice, flush_choice, eager_choice, delta_choice, dc_ds_choice, synch_gen, rand_vertex, run_kla, run_dc, run_ds, run_cc, run_chaotic, run_ss_mis, run_bucket_mis, run_luby_mis, k_level, luby_algo, cc_algo, bucket_choice); } } } if(no_reductions) { if (trans.rank() == 0) std::cout << " Reduction: 0 " << "coalescing " << coalescing_choice << " pri coalescing " << priority_coalescing_size << " routing " << routing_choice << " run_cc " << run_cc << std::endl; if(routing_choice == rt_none) { typedef amplusplus::simple_generator<amplusplus::counter_coalesced_message_type_gen> MessageGenerator; MessageGenerator msg_gen((amplusplus::counter_coalesced_message_type_gen(coalescing_choice))); MessageGenerator priority_msg_gen((amplusplus::counter_coalesced_message_type_gen(priority_coalescing_size, 1))); select_msg_gen(msg_gen, priority_msg_gen, trans, barrier_trans, g, distance, weight, thread_choice, flush_choice, eager_choice, delta_choice, dc_ds_choice, synch_gen, rand_vertex, run_kla, run_dc, run_ds, run_cc, run_chaotic, run_ss_mis, run_bucket_mis, run_luby_mis, k_level, luby_algo, cc_algo, bucket_choice); } if(routing_choice == rt_hypercube) { typedef amplusplus::routing_generator<amplusplus::counter_coalesced_message_type_gen, amplusplus::hypercube_routing> MessageGenerator; MessageGenerator msg_gen(amplusplus::counter_coalesced_message_type_gen(coalescing_choice), amplusplus::hypercube_routing(trans.rank(), trans.size())); MessageGenerator priority_msg_gen(amplusplus::counter_coalesced_message_type_gen(priority_coalescing_size, 1), amplusplus::hypercube_routing(trans.rank(), trans.size())); select_msg_gen(msg_gen, priority_msg_gen, trans, barrier_trans, g, distance, weight, thread_choice, flush_choice, eager_choice, delta_choice, dc_ds_choice, synch_gen, rand_vertex, run_kla, run_dc, run_ds, run_cc, run_chaotic, run_ss_mis, run_bucket_mis, run_luby_mis, k_level, luby_algo, cc_algo, bucket_choice); } if(routing_choice == rt_rook) { typedef amplusplus::routing_generator<amplusplus::counter_coalesced_message_type_gen, amplusplus::rook_routing> MessageGenerator; MessageGenerator msg_gen(amplusplus::counter_coalesced_message_type_gen(coalescing_choice), amplusplus::rook_routing(trans.rank(), trans.size())); MessageGenerator priority_msg_gen(amplusplus::counter_coalesced_message_type_gen(priority_coalescing_size, 1), amplusplus::rook_routing(trans.rank(), trans.size())); select_msg_gen(msg_gen, priority_msg_gen, trans, barrier_trans, g, distance, weight, thread_choice, flush_choice, eager_choice, delta_choice, dc_ds_choice, synch_gen, rand_vertex, run_kla, run_dc, run_ds, run_cc, run_chaotic, run_ss_mis, run_bucket_mis, run_luby_mis, k_level, luby_algo, cc_algo, bucket_choice); } } } template<typename MessageGenerator, typename Digraph, typename DistanceMap, typename WeightMap, typename RNG, typename RandVertex> void select_msg_gen(MessageGenerator &msg_gen, MessageGenerator &priority_msg_gen, amplusplus::transport &trans, amplusplus::transport &barrier_trans, Digraph &g, DistanceMap &distance, WeightMap &weight, unsigned int num_threads, unsigned int flushFreq, unsigned int eager_limit, unsigned int delta, std::string& dc_ds, RNG synch_gen, RandVertex rand_vertex, bool run_kla, bool run_dc, bool run_ds, bool run_cc, bool run_chaotic, bool run_ss_mis, bool run_bucket_mis, bool run_luby_mis, size_t k_level, std::string luby_algo, std::string cc_algo, size_t bucket_choice) { //run_ds = !run_dc; typedef typename graph_traits<Digraph>::vertex_descriptor Vertex; time_type total_time = 0; std::vector<time_type> all_times(num_sources); std::vector<state_t> misvec(num_vertices(g), MIS_UNFIX); typedef typename property_map<Digraph, vertex_index_t>::type VertexIndexMap; typedef iterator_property_map<typename std::vector<state_t>::iterator, VertexIndexMap> MISMap; MISMap mis(misvec.begin(), get(vertex_index, g)); #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS clear_cumulative_buffer_stats(); #endif #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS cumulative_hits = 0; cumulative_tests = 0; #endif #ifdef PBGL2_PRINT_WORK_STATS clear_cumulative_work_stats(); #endif // For GTEPS double total_elapsed_time = 0.0; size_t *edge_traversed =(size_t *) calloc(num_sources, sizeof(size_t)); double *elapsed_time = (double *) calloc(num_sources, sizeof(double)); for (unsigned int source_i = 0; source_i < num_sources; ++source_i) { #ifdef PRINT_ET if (trans.rank() == 0) std::cout << print_time(get_time() - job_start) << "s elapsed since job start\n"; #endif Vertex current_source = vertex(rand_vertex(synch_gen), g); time_type time; if(run_dc) { if(dc_ds == "vector") { // Note : We need to modify vector data srtucture to accomadate new interface std::cout << " This (vector data structure) option is not supported." << " We need to change vector implementation to satisfy new interface" << std::endl; exit(1); /* time = run_distributed_control<boost::graph::distributed::vector_of_vector_gen> (trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, priority_msg_gen, flushFreq, eager_limit); */ } else if (dc_ds == "nodeq") { // priority queue per node time = run_distributed_control_node<boost::graph::distributed::node_priority_queue_gen> (trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, priority_msg_gen, flushFreq, eager_limit); } else if (dc_ds == "ms_nodeq"){ // priority queue per node time = run_distributed_control_node<boost::graph::distributed::ms_node_priority_queue_gen> (trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, priority_msg_gen, flushFreq, eager_limit); } else if (dc_ds == "numaq") { // priority queue per numa node time = run_distributed_control_node<boost::graph::distributed::numa_priority_queue_gen> (trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, priority_msg_gen, flushFreq, eager_limit, true); // numa true } else if (dc_ds == "ms_numaq") { // priority queue per numa node time = run_distributed_control_node<boost::graph::distributed::ms_numa_priority_queue_gen> (trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, priority_msg_gen, flushFreq, eager_limit, true); // numa true } else if (dc_ds == "pheet64q"){ time = run_distributed_control_pheet<boost::graph::distributed::pheet_priority_queue_gen_64> (trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, priority_msg_gen, flushFreq, eager_limit); } else if (dc_ds == "pheet128q"){ time = run_distributed_control_pheet<boost::graph::distributed::pheet_priority_queue_gen_128> (trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, priority_msg_gen, flushFreq, eager_limit); } else if (dc_ds == "pheet256q"){ time = run_distributed_control_pheet<boost::graph::distributed::pheet_priority_queue_gen_256> (trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, priority_msg_gen, flushFreq, eager_limit); } else if (dc_ds == "pheet512q"){ time = run_distributed_control_pheet<boost::graph::distributed::pheet_priority_queue_gen_512> (trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, priority_msg_gen, flushFreq, eager_limit); } else if (dc_ds == "pheet1024q"){ time = run_distributed_control_pheet<boost::graph::distributed::pheet_priority_queue_gen_1024> (trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, priority_msg_gen, flushFreq, eager_limit); } else if (dc_ds == "threadq"){ time = run_distributed_control(trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, priority_msg_gen, flushFreq, eager_limit); } else if (dc_ds == "buffer") { std::cout << "Ignoring buffer data structure for Distirbuted Cotrol ..." << std::endl; } else { std::cout << "Data structure not specified ! " << std::endl; assert(false); } } else if (run_cc) { if (cc_algo == "run_dd_cc") { time = run_data_driven_cc(trans, barrier_trans, g, num_threads, n, verify, print_cc_stats, allstats, msg_gen, priority_msg_gen, flushFreq, eager_limit); { amplusplus::scoped_epoch epoch(barrier_trans); } } if (cc_algo == "run_sv_cc") { time = run_sv_c_c(trans, g, num_threads, verify, false, // level_sync msg_gen, vertices_per_lock); { amplusplus::scoped_epoch epoch(barrier_trans); } } if (cc_algo == "run_sv_cc_level_sync") { time = run_sv_c_c(trans, g, num_threads, verify, true, // level_sync msg_gen, vertices_per_lock); { amplusplus::scoped_epoch epoch(barrier_trans); } } if (cc_algo == "run_sv_cc_opt") { time = run_sv_cc_optimized(trans, g, num_threads, verify, false, // level_sync msg_gen, vertices_per_lock); { amplusplus::scoped_epoch epoch(barrier_trans); } } if (cc_algo == "run_sv_cc_opt_level_sync") { time = run_sv_cc_optimized(trans, g, num_threads, verify, true, // level_sync msg_gen, vertices_per_lock); { amplusplus::scoped_epoch epoch(barrier_trans); } } if (cc_algo == "run_sv_ps_cc") { time = run_ps_sv_cc(trans, g, num_threads, verify, false, // level_sync msg_gen, vertices_per_lock); { amplusplus::scoped_epoch epoch(barrier_trans); } } if (cc_algo == "run_sv_ps_cc_level_sync") { time = run_ps_sv_cc(trans, g, num_threads, verify, true, // level_sync msg_gen, vertices_per_lock); { amplusplus::scoped_epoch epoch(barrier_trans); } } if (cc_algo == "run_cc_chaotic") { time = run_chaotic_cc(trans, barrier_trans, g, num_threads, n, verify, print_cc_stats, allstats, msg_gen); { amplusplus::scoped_epoch epoch(barrier_trans); } } if (cc_algo == "run_cc_ds") { if (id_distribution == vertical) time = run_delta_cc(trans, barrier_trans, g, num_threads, n, bucket_choice, block_id_distribution<Digraph>(g, n), verify, print_cc_stats, allstats, msg_gen); else time = run_delta_cc(trans, barrier_trans, g, num_threads, n, bucket_choice, row_id_distribution<Digraph>(g, trans.size()), verify, print_cc_stats, allstats, msg_gen); { amplusplus::scoped_epoch epoch(barrier_trans); } } if (cc_algo == "run_level_sync_cc") { time = run_level_sync_cc(trans, barrier_trans, g, num_threads, n, verify, print_cc_stats, allstats, msg_gen); { amplusplus::scoped_epoch epoch(barrier_trans); } } } else if(run_ds) { // run_ds // For now we don't have the parameter for level_sync. It can be added later on. if (dc_ds == "buffer") { time = run_delta_stepping(trans, barrier_trans, g, weight, distance, current_source, delta, num_threads, n, verify, false, msg_gen); } else if (dc_ds == "nodeq") { time = run_delta_stepping_node<boost::graph::distributed::node_priority_queue_gen>(trans, barrier_trans, g, weight, distance, current_source, delta, num_threads, n, verify, false, msg_gen, flushFreq); } else if (dc_ds == "ms_nodeq") { time = run_delta_stepping_node<boost::graph::distributed::ms_node_priority_queue_gen>(trans, barrier_trans, g, weight, distance, current_source, delta, num_threads, n, verify, false, msg_gen, flushFreq); } else if (dc_ds == "threadq") { time = run_delta_stepping_thread<boost::graph::distributed::thread_priority_queue_gen>(trans, barrier_trans, g, weight, distance, current_source, delta, num_threads, n, verify, false, msg_gen, flushFreq); } else if (dc_ds == "mtthreadq") { time = run_delta_stepping_thread<boost::graph::distributed::multi_priority_queue_gen>(trans, barrier_trans, g, weight, distance, current_source, delta, num_threads, n, verify, false, msg_gen, flushFreq); } else if (dc_ds == "numaq") { time = run_delta_stepping_numa<boost::graph::distributed::numa_priority_queue_gen>(trans, barrier_trans, g, weight, distance, current_source, delta, num_threads, n, verify, false, msg_gen, flushFreq); } else if (dc_ds == "ms_numaq") { time = run_delta_stepping_numa<boost::graph::distributed::ms_numa_priority_queue_gen>(trans, barrier_trans, g, weight, distance, current_source, delta, num_threads, n, verify, false, msg_gen, flushFreq); } else { std::cout << "Data structure not specified ! " << std::endl; assert(false); } } else if(run_chaotic) { // chaotic SSSP time = run_distributed_control_chaotic(trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, msg_gen, flushFreq, eager_limit); } else if(run_kla) { if (dc_ds == "buffer") { time = run_kla_sssp(trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, false, msg_gen, k_level); } else if (dc_ds == "numaq") { time = run_kla_sssp_numa<boost::graph::distributed::numa_priority_queue_gen>(trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, false, msg_gen, k_level, flushFreq); } else if (dc_ds == "ms_numaq") { time = run_kla_sssp_numa<boost::graph::distributed::ms_numa_priority_queue_gen>(trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, false, msg_gen, k_level, flushFreq); } else if (dc_ds == "nodeq") { time = run_kla_sssp_node<boost::graph::distributed::node_priority_queue_gen>(trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, false, msg_gen, k_level, flushFreq); } else if (dc_ds == "ms_nodeq") { time = run_kla_sssp_node<boost::graph::distributed::ms_node_priority_queue_gen>(trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, false, msg_gen, k_level, flushFreq); } else if (dc_ds == "threadq"){ time = run_kla_sssp_thread<boost::graph::distributed::thread_priority_queue_gen>(trans, barrier_trans, g, weight, distance, current_source, num_threads, n, verify, false, msg_gen, k_level, flushFreq); } else { assert(false); } } else if(run_ss_mis) { time = run_fix_mis<boost::graph::distributed::thread_priority_queue_gen>(trans, barrier_trans, g, mis, num_threads, n, verify, msg_gen, flushFreq); } else if(run_bucket_mis) { time = run_fix_mis_bucket(trans, barrier_trans, g, mis, num_threads, n, verify, msg_gen, flushFreq); } else if(run_luby_mis) { if (luby_algo == "A") { time = run_luby_maximal_is<boost::graph::distributed::select_a_functor_gen>(trans, barrier_trans, g, mis, num_threads, n, verify, msg_gen, flushFreq); } else if (luby_algo == "AV1") { time = run_luby_maximal_is<boost::graph::distributed::select_a_vertex_functor_gen>(trans, barrier_trans, g, mis, num_threads, n, verify, msg_gen, flushFreq); } else if (luby_algo == "AV2"){ time = run_luby_maximal_is<boost::graph::distributed::select_a_v2_functor_gen>(trans, barrier_trans, g, mis, num_threads, n, verify, msg_gen, flushFreq); } else if (luby_algo == "B") { time = run_luby_maximal_is<boost::graph::distributed::select_b_functor_gen>(trans, barrier_trans, g, mis, num_threads, n, verify, msg_gen, flushFreq); } else { std::cerr << "Invalid algorithm type for Luby MIS." << " Available algorithms are A, AV1, AV2 and B" << std::endl; assert(false); } } else { assert(false); } #ifdef CALCULATE_GTEPS if (!run_cc) { elapsed_time[source_i] = time; edge_traversed[source_i] = get_gteps(trans, g, distance, weight); } #endif if (time == -1.) { // Not enough vertices visited --source_i; continue; } total_time += time; all_times[source_i] = time; } if (trans.rank() == 0) { #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS unsigned long long buffers{}, messages{}; for(unsigned int i = 0; i < cumulative_flushes.size(); ++i) { buffers += cumulative_flushes[i]; messages += cumulative_flushes[i] * i; } float msg_per_buf = -1; if (buffers != 0) { msg_per_buf = messages/buffers; } #endif if(run_dc) { std::cout << "Total Distributed Control (DC)-(" << dc_ds << ") time for " << num_sources << " sources = " << print_time(total_time) << " (" << print_time(total_time / num_sources) << " per source), " #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS << "messages = " << cumulative_messages << " (" << (cumulative_messages / num_sources) << " per source), " << " full buffers = " << cumulative_full << " (" << (cumulative_full / num_sources) << " per source)" << " partial flushes = " << buffers << " (" << (buffers / num_sources) << " per source) with " << msg_per_buf << " messages per buffer on average (-1 means buffer size is 0)." #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES << "\nTests = " << (cumulative_tests / num_sources) << " (per source), hits = " << (cumulative_hits / num_sources) << " (per source), hit rate = " << (double(cumulative_hits) / double(cumulative_tests) * 100.) << "%" #endif #ifdef PBGL2_PRINT_WORK_STATS PBGL2_DC_PRINT // The print macro for work stats #endif << std::endl; } else if(run_chaotic) { std::cout << "Total Chaotic SSSP " << "time for " << num_sources << " sources = " << print_time(total_time) << " (" << print_time(total_time / num_sources) << " per source), " #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS << "messages = " << cumulative_messages << " (" << (cumulative_messages / num_sources) << " per source), " << " full buffers = " << cumulative_full << " (" << (cumulative_full / num_sources) << " per source)" << " partial flushes = " << buffers << " (" << (buffers / num_sources) << " per source) with " << msg_per_buf << " messages per buffer on average (-1 means buffer size is 0)." #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES << "\nTests = " << (cumulative_tests / num_sources) << " (per source), hits = " << (cumulative_hits / num_sources) << " (per source), hit rate = " << (double(cumulative_hits) / double(cumulative_tests) * 100.) << "%" #endif #ifdef PBGL2_PRINT_WORK_STATS PBGL2_DC_PRINT // The print macro for work stats #endif << std::endl; } else if(run_ds) { // run_ds std::cout << "Total Delta-Stepping (DS-" << dc_ds << ") time for " << num_sources << " sources = " << print_time(total_time) << " (" << print_time(total_time / num_sources) << " per source), delta = " << delta #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS << ", messages = " << cumulative_messages << " (" << (cumulative_messages / num_sources) << " per source), " << " full buffers = " << cumulative_full << " (" << (cumulative_full / num_sources) << " per source)" << " partial flushes = " << buffers << " (" << (buffers / num_sources) << " per source) with " << msg_per_buf << " messages per buffer on average (-1 means buffer size is 0)." #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES << "\nTests = " << (cumulative_tests / num_sources) << " (per source), hits = " << (cumulative_hits / num_sources) << " (per source), hit rate = " << (double(cumulative_hits) / double(cumulative_tests) * 100.) << "%" #endif #ifdef PBGL2_PRINT_WORK_STATS PBGL2_DS_PRINT // The print macro for work stats #endif << std::endl; } /*else if (run_cc) { // run connected components #ifdef CC_ALGORITHMS std::cout << "Total data driven cc time for " << num_sources << " sources = " << print_time(total_cc_dd_time) << " (" << print_time(total_cc_dd_time / num_sources) << " per source)" << " Total shiloach-vishkin time " << print_time(total_cc_sv_time) << " (" << print_time(total_cc_sv_time / num_sources) << " per source)" << " Total parallel shiloach-vishkin time " << print_time(total_cc_sv_ps_time) << " (" << print_time(total_cc_sv_ps_time / num_sources) << " per source)" << " Total local difference time " << print_time(total_cc_ld_time) << " (" << print_time(total_cc_ld_time / num_sources) << " per source)." << " Running Scale : " << scale #ifdef AMPLUSPLUS_ENABLE_PERFORMANCE_COUNTERS << ", messages = " << cumulative_messages << " (" << (cumulative_messages / num_sources) << " per source), " << " full buffers = " << cumulative_full << " (" << (cumulative_full / num_sources) << " per source)" << " partial flushes = " << buffers << " (" << (buffers / num_sources) << " per source) with " << msg_per_buf << " messages per buffer on average (-1 means buffer size is 0)." #endif #ifdef AMPLUSPLUS_PRINT_HIT_RATES << "\nTests = " << (cumulative_tests / num_sources) << " (per source), hits = " << (cumulative_hits / num_sources) << " (per source), hit rate = " << (double(cumulative_hits) / double(cumulative_tests) * 100.) << "%" #endif #ifdef PBGL2_PRINT_WORK_STATS PBGL2_DS_PRINT // The print macro for work stats #endif << std::endl; #endif // end of CC_ALGORITHMS }*/ else if(run_kla) { // run_kla std::cout << "Total kla-sssp time for " << num_sources << " sources = " << print_time(total_time) << " (" << print_time(total_time / num_sources) << " per source), klevel = " << k_level << "%" #ifdef PBGL2_PRINT_WORK_STATS PBGL2_DS_PRINT // The print macro for work stats #endif << std::endl; } time_type mean = total_time / num_sources; time_type min = 0; time_type q1 = 0; time_type median = 0; time_type q3 = 0; time_type max = 0; time_type stddev = 0; time_statistics(all_times, mean, min, q1, median, q3, max, stddev); std::cout << "MEAN : " << print_time(mean) << " STDDEV : " << print_time(stddev) << " MIN : " << print_time(min) << " Q1 : " << print_time(q1) << " MEDIAN : " << print_time(median) << " Q3 : " << print_time(q3) << " MAX : " << print_time(max) << std::endl; #ifdef CALCULATE_GTEPS std::cout << "==============TEPS Statistics=================" << std::endl; double *tm = (double*)malloc(sizeof(double)*num_sources); double *stats = (double*)malloc(sizeof(double)*9); // TODO We need to fix stat when num_sources < 4 if (!run_cc && num_sources > 4) { for(int i = 0; i < num_sources; i++) tm[i] = edge_traversed[i]/elapsed_time[i]; statistics (stats, tm, num_sources); PRINT_GRAPH500_STATS("TEPS", 1); } free(tm); free(stats); #endif free(edge_traversed); free(elapsed_time); } } template<typename Graph500Iter, typename Routing, typename Distribution, typename Trans, typename EdgeSize, typename UInt, typename Edges, typename WeightIterator> void do_distribute(Distribution &distrib, Trans &trans, EdgeSize e_start, EdgeSize e_count, UInt a, UInt b, Edges &edges, WeightIterator weight_iter, int num_threads) { typedef amplusplus::routing_generator<amplusplus::counter_coalesced_message_type_gen, Routing> MessageGenerator; MessageGenerator msg_gen(amplusplus::counter_coalesced_message_type_gen(distribution_coalescing_size), Routing(trans.rank(), trans.size())); time_type start = get_time(); // Multithreaded distribution trans.set_nthreads(num_threads); #ifdef PRINT_DEBUG std::cout << "Thread start : " << e_start << "Total edge count : " << e_count << " for rank :" << trans.rank() << std::endl; #endif Edges* thread_edges = new Edges[num_threads]; EdgeSize std_count_per_thread = (e_count + num_threads - 1) / num_threads; // EdgeSize remainder = e_count % num_threads; #ifdef PRINT_DEBUG std::cout << "std_count_per_thread : " << std_count_per_thread << std::endl; #endif EdgeSize thread_start = e_start; EdgeSize count_per_thread = std_count_per_thread; // create message type typedef typename std::iterator_traits<Graph500Iter>::value_type value_type; typedef detail::vector_write_handler<Edges> vec_write_handler; // not sure we need this here amplusplus::register_mpi_datatype<value_type>(); typedef typename MessageGenerator::template call_result<value_type, vec_write_handler, detail::distrib_to_pair_owner_map_t<Distribution>, amplusplus::no_reduction_t>::type write_msg_type; write_msg_type write_msg(msg_gen, trans, detail::distrib_to_pair_owner_map<Distribution>(distrib), amplusplus::no_reduction); // set the handler (must be in main thread) write_msg.set_handler(vec_write_handler(thread_edges)); threaded_distributor<write_msg_type> td(write_msg); boost::scoped_array<boost::thread> threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { #ifdef PRINT_DEBUG if (_RANK == 0) { std::cout << "Thread : " << i+1 << " start : " << thread_start << " thread end : " << (thread_start + count_per_thread) << std::endl; } #endif boost::thread thr(boost::ref(td), i+1, Graph500Iter(scale, thread_start, a, b, weight_iter), Graph500Iter(scale, thread_start + count_per_thread, a, b, weight_iter), flip_pair(), trans); thread_start = thread_start + count_per_thread; threads[i].swap(thr); } // Allocate remainder to main thread count_per_thread = std::min(std_count_per_thread, (e_count-thread_start)); #ifdef PRINT_DEBUG std::cout << "Thread : " << 0 << " start : " << thread_start << " thread end : " << (thread_start + count_per_thread) << std::endl; #endif td(0, Graph500Iter(scale, thread_start, a, b, weight_iter), Graph500Iter(scale, thread_start + count_per_thread, a, b, weight_iter), flip_pair(), trans); // Wait till all threads finish for (int i = 0; i < num_threads - 1; ++i) threads[i].join(); // Merge all edges - in threads // time_type m_start = get_time(); typename Edges::size_type total_sz = 0; std::vector<typename Edges::size_type> positions(num_threads); for (int i = 0; i < num_threads; ++i) { positions[i] = total_sz; total_sz += thread_edges[i].size(); } edges.resize(total_sz); threaded_merger<Edges> tm(edges); boost::scoped_array<boost::thread> m_threads(new boost::thread[num_threads - 1]); for (int i = 0; i < num_threads - 1; ++i) { typename Edges::iterator pos_ite = edges.begin(); std::advance(pos_ite, positions[i+1]); boost::thread thr(boost::ref(tm), pos_ite, thread_edges[i+1].begin(), thread_edges[i+1].end()); m_threads[i].swap(thr); } tm(edges.begin(), thread_edges[0].begin(), thread_edges[0].end()); // Wait till all threads finish for (int i = 0; i < num_threads - 1; ++i) m_threads[i].join(); //time_type m_end = get_time(); trans.set_nthreads(1); delete[] thread_edges; { amplusplus::scoped_epoch epoch(trans); } time_type end = get_time(); std::cout << "Graph distribution permutation took " << (end-start) << " time" << std::endl; // sort edges in parallel //__gnu_parallel::sort(edges.begin(), edges.end()); } }; void q_test() { typedef std::pair<int, int> vertex_distance_data; struct default_comparer { bool operator()(const vertex_distance_data& vd1, const vertex_distance_data& vd2) { return vd1.second > vd2.second; } }; cds::Initialize(); { // Initialize Hazard Pointer singleton cds::gc::HP hpGC(72); // Attach for the main thread cds::threading::Manager::attachThread(); // template<typename vertex_distance, typename Compare> /* struct reverse_compare { private: default_comparer c; public: inline bool operator()(const vertex_distance_data& vd1, const vertex_distance_data& vd2) { return c(vd2, vd1); } };*/ graph::distributed::ms_node_priority_queue<vertex_distance_data, default_comparer> npq(10); graph::distributed::node_priority_queue<vertex_distance_data, default_comparer> pq(10); // graph::distributed::ellen_bin_priority_queue<vertex_distance_data, default_comparer> epq(10); std::priority_queue<vertex_distance_data, std::vector<vertex_distance_data>, default_comparer> dpq; vertex_distance_data vd1(10, 22); vertex_distance_data vd2(1, 23); vertex_distance_data vd3(5, 34); vertex_distance_data vd4(8, 12); vertex_distance_data vd5(11, 210); vertex_distance_data vd6(7, 2); vertex_distance_data vd7(8, 650); vertex_distance_data vd8(5, 30); vertex_distance_data vd9(2, 22); vertex_distance_data vd10(9, 21); npq.put(vd1,0); npq.put(vd2,1); npq.put(vd3,0); npq.put(vd4,2); npq.put(vd5,3); npq.put(vd6,4); npq.put(vd7,5); npq.put(vd8,6); npq.put(vd9,2); npq.put(vd10,4); pq.put(vd1,0); pq.put(vd2,1); pq.put(vd3,0); pq.put(vd4,2); pq.put(vd5,3); pq.put(vd6,4); pq.put(vd7,5); pq.put(vd8,6); pq.put(vd9,2); pq.put(vd10,4); /* epq.put(vd1,0); epq.put(vd2,1); epq.put(vd3,0); epq.put(vd4,2); epq.put(vd5,3); epq.put(vd6,4); epq.put(vd7,5); epq.put(vd8,6); epq.put(vd9,2); epq.put(vd10,4);*/ dpq.push(vd1); dpq.push(vd2); dpq.push(vd3); dpq.push(vd4); dpq.push(vd5); dpq.push(vd6); dpq.push(vd7); dpq.push(vd8); dpq.push(vd9); dpq.push(vd10); std::cout << "========== cds :: mspq ===========" << std::endl; // should give the shortest distance first vertex_distance_data vdx1; while(npq.pop(vdx1, 0)) { std::cout << vdx1.second << std::endl; } assert(npq.empty()); std::cout << "========== cds :: fcpq ===========" << std::endl; // should give the shortest distance first vertex_distance_data vdx2; while(pq.pop(vdx2, 0)) { std::cout << vdx2.second << std::endl; } assert(pq.empty()); /* std::cout << "========== cds :: ellenbin ===========" << std::endl; // should give the shortest distance first vertex_distance_data vdx3; while(epq.pop(vdx3, 0)) { std::cout << vdx3.second << std::endl; } assert(epq.empty());*/ std::cout << "========== std::queue===========" << std::endl; while(!dpq.empty()) { std::cout << dpq.top().second << std::endl; dpq.pop(); } cds::threading::Manager::detachThread(); } cds::Terminate(); exit(0); } int main(int argc, char* argv[]) { // q_test(); dc_test t(argc, argv); t.test_main(argc, argv); }
31.594864
637
0.650848
thejkane
9a830a8865590c235673400e4b769f04a41dc433
4,625
cpp
C++
android-28/org/xml/sax/helpers/AttributesImpl.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/org/xml/sax/helpers/AttributesImpl.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/org/xml/sax/helpers/AttributesImpl.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../../../JArray.hpp" #include "../../../../JString.hpp" #include "./AttributesImpl.hpp" namespace org::xml::sax::helpers { // Fields // QJniObject forward AttributesImpl::AttributesImpl(QJniObject obj) : JObject(obj) {} // Constructors AttributesImpl::AttributesImpl() : JObject( "org.xml.sax.helpers.AttributesImpl", "()V" ) {} AttributesImpl::AttributesImpl(JObject arg0) : JObject( "org.xml.sax.helpers.AttributesImpl", "(Lorg/xml/sax/Attributes;)V", arg0.object() ) {} // Methods void AttributesImpl::addAttribute(JString arg0, JString arg1, JString arg2, JString arg3, JString arg4) const { callMethod<void>( "addAttribute", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", arg0.object<jstring>(), arg1.object<jstring>(), arg2.object<jstring>(), arg3.object<jstring>(), arg4.object<jstring>() ); } void AttributesImpl::clear() const { callMethod<void>( "clear", "()V" ); } jint AttributesImpl::getIndex(JString arg0) const { return callMethod<jint>( "getIndex", "(Ljava/lang/String;)I", arg0.object<jstring>() ); } jint AttributesImpl::getIndex(JString arg0, JString arg1) const { return callMethod<jint>( "getIndex", "(Ljava/lang/String;Ljava/lang/String;)I", arg0.object<jstring>(), arg1.object<jstring>() ); } jint AttributesImpl::getLength() const { return callMethod<jint>( "getLength", "()I" ); } JString AttributesImpl::getLocalName(jint arg0) const { return callObjectMethod( "getLocalName", "(I)Ljava/lang/String;", arg0 ); } JString AttributesImpl::getQName(jint arg0) const { return callObjectMethod( "getQName", "(I)Ljava/lang/String;", arg0 ); } JString AttributesImpl::getType(jint arg0) const { return callObjectMethod( "getType", "(I)Ljava/lang/String;", arg0 ); } JString AttributesImpl::getType(JString arg0) const { return callObjectMethod( "getType", "(Ljava/lang/String;)Ljava/lang/String;", arg0.object<jstring>() ); } JString AttributesImpl::getType(JString arg0, JString arg1) const { return callObjectMethod( "getType", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", arg0.object<jstring>(), arg1.object<jstring>() ); } JString AttributesImpl::getURI(jint arg0) const { return callObjectMethod( "getURI", "(I)Ljava/lang/String;", arg0 ); } JString AttributesImpl::getValue(jint arg0) const { return callObjectMethod( "getValue", "(I)Ljava/lang/String;", arg0 ); } JString AttributesImpl::getValue(JString arg0) const { return callObjectMethod( "getValue", "(Ljava/lang/String;)Ljava/lang/String;", arg0.object<jstring>() ); } JString AttributesImpl::getValue(JString arg0, JString arg1) const { return callObjectMethod( "getValue", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;", arg0.object<jstring>(), arg1.object<jstring>() ); } void AttributesImpl::removeAttribute(jint arg0) const { callMethod<void>( "removeAttribute", "(I)V", arg0 ); } void AttributesImpl::setAttribute(jint arg0, JString arg1, JString arg2, JString arg3, JString arg4, JString arg5) const { callMethod<void>( "setAttribute", "(ILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", arg0, arg1.object<jstring>(), arg2.object<jstring>(), arg3.object<jstring>(), arg4.object<jstring>(), arg5.object<jstring>() ); } void AttributesImpl::setAttributes(JObject arg0) const { callMethod<void>( "setAttributes", "(Lorg/xml/sax/Attributes;)V", arg0.object() ); } void AttributesImpl::setLocalName(jint arg0, JString arg1) const { callMethod<void>( "setLocalName", "(ILjava/lang/String;)V", arg0, arg1.object<jstring>() ); } void AttributesImpl::setQName(jint arg0, JString arg1) const { callMethod<void>( "setQName", "(ILjava/lang/String;)V", arg0, arg1.object<jstring>() ); } void AttributesImpl::setType(jint arg0, JString arg1) const { callMethod<void>( "setType", "(ILjava/lang/String;)V", arg0, arg1.object<jstring>() ); } void AttributesImpl::setURI(jint arg0, JString arg1) const { callMethod<void>( "setURI", "(ILjava/lang/String;)V", arg0, arg1.object<jstring>() ); } void AttributesImpl::setValue(jint arg0, JString arg1) const { callMethod<void>( "setValue", "(ILjava/lang/String;)V", arg0, arg1.object<jstring>() ); } } // namespace org::xml::sax::helpers
21.118721
121
0.663568
YJBeetle
9a87f30402171d900d7ba8421b2866e86d6d186f
61,766
cpp
C++
src/shell/shell_misc.cpp
mediaexplorer74/dosbox-x
be9f94b740234f7813bf5a063a558cef9dc7f9a6
[ "MIT" ]
3
2022-02-20T11:06:29.000Z
2022-03-11T08:16:55.000Z
src/shell/shell_misc.cpp
mediaexplorer74/dosbox-x
be9f94b740234f7813bf5a063a558cef9dc7f9a6
[ "MIT" ]
null
null
null
src/shell/shell_misc.cpp
mediaexplorer74/dosbox-x
be9f94b740234f7813bf5a063a558cef9dc7f9a6
[ "MIT" ]
null
null
null
/* * Copyright (C) 2002-2021 The DOSBox Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <assert.h> #include <stdlib.h> #include <string.h> #include <algorithm> //std::copy #include <iterator> //std::front_inserter #include <regex> #include "logging.h" #include "shell.h" #include "timer.h" #include "bios.h" #include "control.h" #include "regs.h" #include "callback.h" #include "support.h" #include "inout.h" #include "render.h" #include "../ints/int10.h" #include "../dos/drives.h" #ifdef _MSC_VER # if !defined(C_SDL2) # include "process.h" # endif # define MIN(a,b) ((a) < (b) ? (a) : (b)) # define MAX(a,b) ((a) > (b) ? (a) : (b)) #else # define MIN(a,b) std::min(a,b) # define MAX(a,b) std::max(a,b) #endif bool clearline=false, inshell=false, noassoc=false; int autofixwarn=3; extern int lfn_filefind_handle; extern bool ctrlbrk, gbk, rtl, dbcs_sbcs; extern bool DOS_BreakFlag, DOS_BreakConioFlag; extern uint16_t cmd_line_seg; #if defined(USE_TTF) extern bool ttf_dosv; #endif extern std::map<int, int> pc98boxdrawmap; void DOS_Shell::ShowPrompt(void) { char dir[DOS_PATHLENGTH]; dir[0] = 0; //DOS_GetCurrentDir doesn't always return something. (if drive is messed up) DOS_GetCurrentDir(0,dir,uselfn); std::string line; const char * promptstr = "\0"; inshell = true; if(GetEnvStr("PROMPT",line)) { std::string::size_type idx = line.find('='); std::string value=line.substr(idx +1 , std::string::npos); line = std::string(promptstr) + value; promptstr = line.c_str(); } while (*promptstr) { if (!strcasecmp(promptstr,"$")) WriteOut("\0"); else if(*promptstr != '$') WriteOut("%c",*promptstr); else switch (toupper(*++promptstr)) { case 'A': WriteOut("&"); break; case 'B': WriteOut("|"); break; case 'C': WriteOut("("); break; case 'D': WriteOut("%02d-%02d-%04d",dos.date.day,dos.date.month,dos.date.year); break; case 'E': WriteOut("%c",27); break; case 'F': WriteOut(")"); break; case 'G': WriteOut(">"); break; case 'H': WriteOut("\b"); break; case 'L': WriteOut("<"); break; case 'N': WriteOut("%c",DOS_GetDefaultDrive()+'A'); break; case 'P': WriteOut("%c:\\",DOS_GetDefaultDrive()+'A'); WriteOut_NoParsing(dir, true); break; case 'Q': WriteOut("="); break; case 'S': WriteOut(" "); break; case 'T': { Bitu ticks=(Bitu)(((65536.0 * 100.0)/(double)PIT_TICK_RATE)* mem_readd(BIOS_TIMER)); reg_dl=(uint8_t)((Bitu)ticks % 100); ticks/=100; reg_dh=(uint8_t)((Bitu)ticks % 60); ticks/=60; reg_cl=(uint8_t)((Bitu)ticks % 60); ticks/=60; reg_ch=(uint8_t)((Bitu)ticks % 24); WriteOut("%d:%02d:%02d.%02d",reg_ch,reg_cl,reg_dh,reg_dl); break; } case 'V': WriteOut("DOSBox-X version %s. Reported DOS version %d.%d.",VERSION,dos.version.major,dos.version.minor); break; case '$': WriteOut("$"); break; case '_': WriteOut("\n"); break; case 'M': break; case '+': break; } promptstr++; } inshell = false; } static void outc(uint8_t c) { uint16_t n=1; DOS_WriteFile(STDOUT,&c,&n); } static void backone() { BIOS_NCOLS; uint8_t page=real_readb(BIOSMEM_SEG,BIOSMEM_CURRENT_PAGE); if (CURSOR_POS_COL(page)>0) outc(8); else if (CURSOR_POS_ROW(page)>0) INT10_SetCursorPos(CURSOR_POS_ROW(page)-1, ncols-1, page); } //! \brief Moves the caret to prev row/last column when column is 0 (video mode 0). void MoveCaretBackwards() { uint8_t col, row; const uint8_t page(0); INT10_GetCursorPos(&row, &col, page); if (col != 0) return; uint16_t cols; INT10_GetScreenColumns(&cols); INT10_SetCursorPos(row - 1, static_cast<uint8_t>(cols), page); } bool DOS_Shell::BuildCompletions(char * line, uint16_t str_len) { // build new completion list // Lines starting with CD/MD/RD will only get directories in the list bool dir_only = (strncasecmp(ltrim(line),"CD ",3)==0)||(strncasecmp(ltrim(line),"MD ",3)==0)||(strncasecmp(ltrim(line),"RD ",3)==0)|| (strncasecmp(ltrim(line),"CHDIR ",6)==0)||(strncasecmp(ltrim(line),"MKDIR ",3)==0)||(strncasecmp(ltrim(line),"RMDIR ",6)==0); int q=0, r=0, k=0; // get completion mask const char *p_completion_start = strrchr(line, ' '); while (p_completion_start) { q=0; char *i; for (i=line;i<p_completion_start;i++) if (*i=='\"') q++; if (q/2*2==q) break; *i=0; p_completion_start = strrchr(line, ' '); *i=' '; } char c[]={'<','>','|'}; for (unsigned int j=0; j<sizeof(c); j++) { const char *sp = strrchr_dbcs(line, c[j]); while (sp) { q=0; char *i; for (i=line;i<sp;i++) if (*i=='\"') q++; if (q/2*2==q) break; *i=0; sp = strrchr_dbcs(line, c[j]); *i=c[j]; } if (!p_completion_start || p_completion_start<sp) p_completion_start = sp; } if (p_completion_start) { p_completion_start ++; completion_index = (uint16_t)(str_len - strlen(p_completion_start)); } else { p_completion_start = line; completion_index = 0; } k=completion_index; const char *path; if ((path = strrchr(line+completion_index,':'))) completion_index = (uint16_t)(path-line+1); if ((path = strrchr_dbcs(line+completion_index,'\\'))) completion_index = (uint16_t)(path-line+1); if ((path = strrchr(line+completion_index,'/'))) completion_index = (uint16_t)(path-line+1); // build the completion list char mask[DOS_PATHLENGTH+2] = {0}, smask[DOS_PATHLENGTH] = {0}; if (p_completion_start && strlen(p_completion_start) + 3 >= DOS_PATHLENGTH) { // TODO: This really should be done in the CON driver so that this code can just print ASCII code 7 instead if (IS_PC98_ARCH) { // TODO: BEEP. I/O PORTS ARE DIFFERENT AS IS THE PIT CLOCK RATE } else { // IBM PC/XT/AT IO_Write(0x43,0xb6); IO_Write(0x42,1750&0xff); IO_Write(0x42,1750>>8); IO_Write(0x61,IO_Read(0x61)|0x3); for(Bitu i=0; i < 333; i++) CALLBACK_Idle(); IO_Write(0x61,IO_Read(0x61)&~0x3); } return false; } if (p_completion_start) { safe_strncpy(mask, p_completion_start,DOS_PATHLENGTH); const char* dot_pos = strrchr(mask, '.'); const char* bs_pos = strrchr_dbcs(mask, '\\'); const char* fs_pos = strrchr(mask, '/'); const char* cl_pos = strrchr(mask, ':'); // not perfect when line already contains wildcards, but works if ((dot_pos-bs_pos>0) && (dot_pos-fs_pos>0) && (dot_pos-cl_pos>0)) strncat(mask, "*",DOS_PATHLENGTH - 1); else strncat(mask, "*.*",DOS_PATHLENGTH - 1); } else { strcpy(mask, "*.*"); } RealPt save_dta=dos.dta(); dos.dta(dos.tables.tempdta); bool res = false; if (DOS_GetSFNPath(mask,smask,false)) { sprintf(mask,"\"%s\"",smask); int fbak=lfn_filefind_handle; lfn_filefind_handle=uselfn?LFN_FILEFIND_INTERNAL:LFN_FILEFIND_NONE; res = DOS_FindFirst(mask, 0xffff & ~DOS_ATTR_VOLUME); lfn_filefind_handle=fbak; } if (!res) { dos.dta(save_dta); // TODO: This really should be done in the CON driver so that this code can just print ASCII code 7 instead if (IS_PC98_ARCH) { // TODO: BEEP. I/O PORTS ARE DIFFERENT AS IS THE PIT CLOCK RATE } else { // IBM PC/XT/AT IO_Write(0x43,0xb6); IO_Write(0x42,1750&0xff); IO_Write(0x42,1750>>8); IO_Write(0x61,IO_Read(0x61)|0x3); for(Bitu i=0; i < 300; i++) CALLBACK_Idle(); IO_Write(0x61,IO_Read(0x61)&~0x3); } return false; } DOS_DTA dta(dos.dta()); char name[DOS_NAMELENGTH_ASCII], lname[LFN_NAMELENGTH], qlname[LFN_NAMELENGTH+2]; uint32_t sz;uint16_t date;uint16_t time;uint8_t att; std::list<std::string> executable; q=0;r=0; while (*p_completion_start) { k++; if (*p_completion_start++=='\"') { if (k<=completion_index) q++; else r++; } } int fbak=lfn_filefind_handle; lfn_filefind_handle=uselfn?LFN_FILEFIND_INTERNAL:LFN_FILEFIND_NONE; while (res) { dta.GetResult(name,lname,sz,date,time,att); if ((strchr(uselfn?lname:name,' ')!=NULL&&q/2*2==q)||r) sprintf(qlname,q/2*2!=q?"%s\"":"\"%s\"",uselfn?lname:name); else strcpy(qlname,uselfn?lname:name); // add result to completion list if (strcmp(name, ".") && strcmp(name, "..")) { if (dir_only) { //Handle the dir only case different (line starts with cd) if(att & DOS_ATTR_DIRECTORY) l_completion.emplace_back(qlname); } else { const char *ext = strrchr(name, '.'); // file extension if ((ext && (strcmp(ext, ".BAT") == 0 || strcmp(ext, ".COM") == 0 || strcmp(ext, ".EXE") == 0)) || hasAssociation(name).size()) // we add executables to a separate list and place that list in front of the normal files executable.emplace_front(qlname); else l_completion.emplace_back(qlname); } } res=DOS_FindNext(); } lfn_filefind_handle=fbak; /* Add executable list to front of completion list. */ std::copy(executable.begin(),executable.end(),std::front_inserter(l_completion)); dos.dta(save_dta); return true; } extern bool isKanji1(uint8_t chr), isKanji2(uint8_t chr); extern bool CheckHat(uint8_t code); static uint16_t GetWideCount(char *line, uint16_t str_index) { bool kanji_flag = false; uint16_t count = 1; for(uint16_t pos = 0 ; pos < str_index ; pos++) { if(!kanji_flag) { if(isKanji1(line[pos])) { kanji_flag = true; } count = 1; } else { if(isKanji2(line[pos])) { count = 2; } kanji_flag = false; } } return count; } static uint16_t GetLastCount(char *line, uint16_t str_index) { bool kanji_flag = false; uint16_t count = 1; for(uint16_t pos = 0 ; pos < str_index ; pos++) { if(!kanji_flag) { if(isKanji1(line[pos])) { kanji_flag = true; } count = 1; } else { if(isKanji2(line[pos])) { bool found=false; if (IS_PC98_ARCH && line[pos-1] == 0xFFFFFF86) { for (auto it = pc98boxdrawmap.begin(); it != pc98boxdrawmap.end(); ++it) if (it->second ==line[pos]) { found=true; break; } } if (!found) count = 2; } kanji_flag = false; } } return count; } static uint16_t GetRemoveCount(char *line, uint16_t str_index) { bool kanji_flag = false; uint16_t count = 1, total = 0; for(uint16_t pos = 0 ; pos < str_index ; pos++) { if(!kanji_flag) { if(isKanji1(line[pos])) { kanji_flag = true; } count = 1; } else { if(isKanji2(line[pos])) { bool found=false; if (IS_PC98_ARCH && line[pos-1] == 0xFFFFFF86) { for (auto it = pc98boxdrawmap.begin(); it != pc98boxdrawmap.end(); ++it) if (it->second ==line[pos]) { found=true; break; } } count = found?0:1; } kanji_flag = false; } total += count; } return total; } static void RemoveAllChar(char *line, uint16_t str_index) { for ( ; str_index > 0 ; str_index--) { // removes all characters if(CheckHat(line[str_index])) { backone(); backone(); outc(' '); outc(' '); backone(); backone(); } else { backone(); outc(' '); backone(); } } if(CheckHat(line[0])) { backone(); outc(' '); backone(); } } static uint16_t DeleteBackspace(bool delete_flag, char *line, uint16_t &str_index, uint16_t &str_len) { uint16_t count, pos, len; pos = str_index; if(delete_flag) { if(isKanji1(line[pos])&&line[pos+1]) { pos += 2; } else { pos += 1; } } count = GetWideCount(line, pos); pos = str_index; while(pos < str_len) { len = 1; DOS_WriteFile(STDOUT, (uint8_t *)&line[pos], &len); pos++; } if (delete_flag && str_index >= str_len) return 0; RemoveAllChar(line, GetRemoveCount(line, pos)); pos = delete_flag ? str_index : str_index - count; while(pos < str_len - count) { line[pos] = line[pos + count]; pos++; } line[pos] = 0; if(!delete_flag) { str_index -= count; } str_len -= count; len = str_len; DOS_WriteFile(STDOUT, (uint8_t *)line, &len); pos = GetRemoveCount(line, str_len); while(pos > str_index) { backone(); if(CheckHat(line[pos - 1])) { backone(); } pos--; } return count; } extern bool isDBCSCP(); /* NTS: buffer pointed to by "line" must be at least CMD_MAXLINE+1 large */ void DOS_Shell::InputCommand(char * line) { Bitu size=CMD_MAXLINE-2; //lastcharacter+0 uint8_t c;uint16_t n=1; uint16_t str_len=0;uint16_t str_index=0; uint16_t len=0; bool current_hist=false; // current command stored in history? uint16_t cr; #if defined(USE_TTF) if(IS_DOSV || ttf_dosv) { #else if(IS_DOSV) { #endif uint16_t int21_seg = mem_readw(0x0086); if(int21_seg != 0xf000) { if(real_readw(int21_seg - 1, 8) == 0x5a56) { // Vz editor resident real_writeb(cmd_line_seg, 0, 250); reg_dx = 0; reg_ah = 0x0a; SegSet16(ds, cmd_line_seg); CALLBACK_RunRealInt(0x21); str_len = real_readb(cmd_line_seg, 1); for(len = 0 ; len < str_len ; len++) { line[len] = real_readb(cmd_line_seg, 2 + len); } line[str_len] = '\0'; return; } } } inshell = true; input_eof = false; line[0] = '\0'; std::list<std::string>::iterator it_history = l_history.begin(), it_completion = l_completion.begin(); while (size) { dos.echo=false; if (!DOS_ReadFile(input_handle,&c,&n)) { LOG(LOG_MISC,LOG_ERROR)("SHELL: Lost the input handle, dropping shell input loop"); n = 0; } if (!n) { input_eof = true; size=0; //Kill the while loop continue; } if (clearline) { clearline = false; *line=0; if (l_completion.size()) l_completion.clear(); //reset the completion list. str_index = 0; str_len = 0; } if (input_handle != STDIN) { /* FIXME: Need DOS_IsATTY() or somesuch */ cr = (uint16_t)c; /* we're not reading from the console */ } else if (IS_PC98_ARCH) { extern uint16_t last_int16_code; /* shift state is needed for some key combinations not directly supported by CON driver. * bit 4 = CTRL * bit 3 = GRPH/ALT * bit 2 = kana * bit 1 = caps * bit 0 = SHIFT */ uint8_t shiftstate = mem_readb(0x52A + 0x0E); /* NTS: PC-98 keyboards lack the US layout HOME / END keys, therefore there is no mapping here */ /* NTS: Since left arrow and backspace map to the same byte value, PC-98 treats it the same at the DOS prompt. * However the PC-98 version of DOSKEY seems to be able to differentiate the two anyway and let the left * arrow move the cursor back (perhaps it's calling INT 18h directly then?) */ if (c == 0x0B) cr = 0x4800; /* IBM extended code up arrow */ else if (c == 0x0A) cr = 0x5000; /* IBM extended code down arrow */ else if (c == 0x0C) { if (shiftstate & 0x10/*CTRL*/) cr = 0x7400; /* IBM extended code CTRL + right arrow */ else cr = 0x4D00; /* IBM extended code right arrow */ } else if (c == 0x08) { /* IBM extended code left arrow OR backspace. use last scancode to tell which as DOSKEY apparently can. */ if (last_int16_code == 0x3B00) { if (shiftstate & 0x10/*CTRL*/) cr = 0x7300; /* CTRL + left arrow */ else cr = 0x4B00; /* left arrow */ } else { cr = 0x08; /* backspace */ } } else if (c == 0x1B) { /* escape */ /* Either it really IS the ESC key, or an ANSI code */ if (last_int16_code != 0x001B) { DOS_ReadFile(input_handle,&c,&n); if (c == 0x44) // DEL cr = 0x5300; else if (c == 0x50) // INS cr = 0x5200; else if (c == 0x53) // F1 cr = 0x3B00; else if (c == 0x54) // F2 cr = 0x3C00; else if (c == 0x55) // F3 cr = 0x3D00; else if (c == 0x56) // F4 cr = 0x3E00; else if (c == 0x57) // F5 cr = 0x3F00; else if (c == 0x45) // F6 cr = 0x4000; else if (c == 0x4A) // F7 cr = 0x4100; else if (c == 0x51) // F9 cr = 0x4300; else if (c == 0x5A) // F10 cr = 0x4400; else cr = 0; } else { cr = (uint16_t)c; } } else { cr = (uint16_t)c; } } else { if (c == 0) { DOS_ReadFile(input_handle,&c,&n); cr = (uint16_t)c << (uint16_t)8; } else { cr = (uint16_t)c; } } #if defined(USE_TTF) if (ttf.inUse && rtl) { if (cr == 0x4B00) cr = 0x4D00; else if (cr == 0x4D00) cr = 0x4B00; else if (cr == 0x7300) cr = 0x7400; else if (cr == 0x7400) cr = 0x7300; } #endif switch (cr) { case 0x3d00: /* F3 */ if (!l_history.size()) break; it_history = l_history.begin(); if (it_history != l_history.end() && it_history->length() > str_len) { const char *reader = &(it_history->c_str())[str_len]; while ((c = (uint8_t)(*reader++))) { line[str_index ++] = (char)c; DOS_WriteFile(STDOUT,&c,&n); } str_len = str_index = (uint16_t)it_history->length(); size = (unsigned int)CMD_MAXLINE - str_index - 2u; line[str_len] = 0; } break; case 0x4B00: /* LEFT */ if(IS_PC98_ARCH || (isDBCSCP() #if defined(USE_TTF) && dbcs_sbcs #endif && IS_DOS_JAPANESE)) { if (str_index) { uint16_t count = GetLastCount(line, str_index); uint8_t ch = line[str_index - 1]; while(count > 0) { uint16_t wide = GetWideCount(line, str_index); backone(); str_index --; if (wide > count) str_index --; count--; } if(CheckHat(ch)) { backone(); } } } else { if (isDBCSCP() #if defined(USE_TTF) &&dbcs_sbcs #endif &&str_index>1&&(line[str_index-1]<0||((dos.loaded_codepage==932||(dos.loaded_codepage==936&&gbk)||dos.loaded_codepage==950||dos.loaded_codepage==951)&&line[str_index-1]>=0x40))&&line[str_index-2]<0) { backone(); str_index --; MoveCaretBackwards(); } if (str_index) { backone(); str_index --; MoveCaretBackwards(); } } break; case 0x7400: /*CTRL + RIGHT : cmd.exe-like next word*/ { auto pos = line + str_index; auto spc = *pos == ' '; const auto end = line + str_len; while (pos < end) { if (spc && *pos != ' ') break; if (*pos == ' ') spc = true; pos++; } const auto lgt = MIN(pos, end) - (line + str_index); for (auto i = 0; i < lgt; i++) outc(static_cast<uint8_t>(line[str_index++])); } break; case 0x7300: /*CTRL + LEFT : cmd.exe-like previous word*/ { auto pos = line + str_index - 1; const auto beg = line; const auto spc = *pos == ' '; if (spc) { while(*pos == ' ') pos--; while(*pos != ' ') pos--; pos++; } else { while(*pos != ' ') pos--; pos++; } const auto lgt = std::abs(MAX(pos, beg) - (line + str_index)); for (auto i = 0; i < lgt; i++) { backone(); str_index--; MoveCaretBackwards(); } } break; case 0x4D00: /* RIGHT */ if(IS_PC98_ARCH || (isDBCSCP() #if defined(USE_TTF) && dbcs_sbcs #endif && IS_DOS_JAPANESE)) { if (str_index < str_len) { uint16_t count = 1; if(str_index < str_len - 1) { count = GetLastCount(line, str_index + 2); } while(count > 0) { outc(line[str_index++]); count--; } } } else { if (isDBCSCP() #if defined(USE_TTF) &&dbcs_sbcs #endif &&str_index<str_len-1&&line[str_index]<0&&(line[str_index+1]<0||((dos.loaded_codepage==932||(dos.loaded_codepage==936&&gbk)||dos.loaded_codepage==950||dos.loaded_codepage==951)&&line[str_index+1]>=0x40))) { outc((uint8_t)line[str_index++]); } if (str_index < str_len) { outc((uint8_t)line[str_index++]); } } break; case 0x4700: /* HOME */ while (str_index) { backone(); str_index--; } break; case 0x5200: /* INS */ if (IS_PC98_ARCH) { // INS state handled by IBM PC/AT BIOS, faked for PC-98 mode extern bool pc98_doskey_insertmode; // NTS: No visible change to the cursor, just like DOSKEY on PC-98 MS-DOS pc98_doskey_insertmode = !pc98_doskey_insertmode; } break; case 0x4F00: /* END */ while (str_index < str_len) { outc((uint8_t)line[str_index++]); } break; case 0x4800: /* UP */ if (l_history.empty() || it_history == l_history.end()) break; // store current command in history if we are at beginning if (it_history == l_history.begin() && !current_hist) { current_hist=true; l_history.emplace_front(line); } // ensure we're at end to handle all cases while (str_index < str_len) { outc((uint8_t)line[str_index++]); } for (;str_index>0; str_index--) { // removes all characters backone(); outc(' '); backone(); } strcpy(line, it_history->c_str()); len = (uint16_t)it_history->length(); str_len = str_index = len; size = (unsigned int)CMD_MAXLINE - str_index - 2u; DOS_WriteFile(STDOUT, (uint8_t *)line, &len); ++it_history; break; case 0x5000: /* DOWN */ if (l_history.empty() || it_history == l_history.begin()) break; // not very nice but works .. --it_history; if (it_history == l_history.begin()) { // no previous commands in history ++it_history; // remove current command from history if (current_hist) { current_hist=false; l_history.pop_front(); } break; } else --it_history; // ensure we're at end to handle all cases while (str_index < str_len) { outc((uint8_t)line[str_index++]); } for (;str_index>0; str_index--) { // removes all characters backone(); outc(' '); backone(); } strcpy(line, it_history->c_str()); len = (uint16_t)it_history->length(); str_len = str_index = len; size = (unsigned int)CMD_MAXLINE - str_index - 2u; DOS_WriteFile(STDOUT, (uint8_t *)line, &len); ++it_history; break; case 0x5300:/* DELETE */ if(IS_PC98_ARCH || (isDBCSCP() #if defined(USE_TTF) && dbcs_sbcs #endif && IS_DOS_JAPANESE)) { if(str_len) { size += DeleteBackspace(true, line, str_index, str_len); } } else { if(str_index>=str_len) break; int k=1; if (isDBCSCP() #if defined(USE_TTF) &&dbcs_sbcs #endif &&str_index<str_len-1&&line[str_index]<0&&(line[str_index+1]<0||((dos.loaded_codepage==932||(dos.loaded_codepage==936&&gbk)||dos.loaded_codepage==950||dos.loaded_codepage==951)&&line[str_index+1]>=0x40))) k=2; for (int i=0; i<k; i++) { uint16_t a=str_len-str_index-1; uint8_t* text=reinterpret_cast<uint8_t*>(&line[str_index+1]); DOS_WriteFile(STDOUT,text,&a);//write buffer to screen outc(' ');backone(); for(Bitu i=str_index;i<(str_len-1u);i++) { line[i]=line[i+1u]; backone(); } line[--str_len]=0; size++; } } break; case 0x0F00: /* Shift-Tab */ if (!l_completion.size()) { if (BuildCompletions(line, str_len)) it_completion = l_completion.end(); else break; } if (l_completion.size()) { if (it_completion == l_completion.begin()) it_completion = l_completion.end (); --it_completion; if (it_completion->length()) { for (;str_index > completion_index; str_index--) { // removes all characters backone(); outc(' '); backone(); } strcpy(&line[completion_index], it_completion->c_str()); len = (uint16_t)it_completion->length(); str_len = str_index = (Bitu)(completion_index + len); size = (unsigned int)CMD_MAXLINE - str_index - 2u; DOS_WriteFile(STDOUT, (uint8_t *)it_completion->c_str(), &len); } } break; case 0x08: /* BackSpace */ if(IS_PC98_ARCH || (isDBCSCP() #if defined(USE_TTF) && dbcs_sbcs #endif && IS_DOS_JAPANESE)) { if(str_index) { size += DeleteBackspace(false, line, str_index, str_len); } } else { int k=1; if (isDBCSCP() #if defined(USE_TTF) &&dbcs_sbcs #endif &&str_index>1&&(line[str_index-1]<0||((dos.loaded_codepage==932||(dos.loaded_codepage==936&&gbk)||dos.loaded_codepage==950||dos.loaded_codepage==951)&&line[str_index-1]>=0x40))&&line[str_index-2]<0) k=2; for (int i=0; i<k; i++) if (str_index) { backone(); uint32_t str_remain=(uint32_t)(str_len - str_index); size++; if (str_remain) { memmove(&line[str_index-1],&line[str_index],str_remain); line[--str_len]=0; str_index --; /* Go back to redraw */ for (uint16_t i=str_index; i < str_len; i++) outc((uint8_t)line[i]); } else { line[--str_index] = '\0'; str_len--; } outc(' '); backone(); // moves the cursor left while (str_remain--) backone(); } } if (l_completion.size()) l_completion.clear(); break; case 0x0a: /* Give a new Line */ outc('\n'); break; case '': // FAKE CTRL-C *line = 0; // reset the line. if (l_completion.size()) l_completion.clear(); //reset the completion list. size = 0; // stop the next loop str_len = 0; // prevent multiple adds of the same line DOS_BreakFlag = false; // clear break flag so the next program doesn't get hit with it DOS_BreakConioFlag = false; break; case 0x0d: /* Don't care, and return */ if(!echo) { outc('\r'); outc('\n'); } size=0; //Kill the while loop break; case 0x9400: /* Ctrl-Tab */ { if (!l_completion.size()) { if (BuildCompletions(line, str_len)) it_completion = l_completion.begin(); else break; } size_t w_count, p_count, col; unsigned int max[15], total, tcols=IS_PC98_ARCH?80:real_readw(BIOSMEM_SEG,BIOSMEM_NB_COLS); if (!tcols) tcols=80; int mrow=tcols>80?15:10; for (col=mrow; col>0; col--) { for (int i=0; i<mrow; i++) max[i]=2; if (col==1) break; w_count=0; for (std::list<std::string>::iterator source = l_completion.begin(); source != l_completion.end(); ++source) { std::string name = source->c_str(); if (name.size()+2>max[w_count%col]) max[w_count%col]=(unsigned int)(name.size()+2); ++w_count; } total=0; for (size_t i=0; i<col; i++) total+=max[i]; if (total<tcols) break; } w_count = p_count = 0; bool lastcr=false; if (l_completion.size()) {WriteOut_NoParsing("\n");lastcr=true;} for (std::list<std::string>::iterator source = l_completion.begin(); source != l_completion.end(); ++source) { std::string name = source->c_str(); if (col==1) { WriteOut_NoParsing(name.c_str(), true); WriteOut("\n"); lastcr=true; p_count++; } else { WriteOut("%s%-*s", name.c_str(), max[w_count % col]-name.size(), ""); lastcr=false; } if (col>1) { ++w_count; if (w_count % col == 0) {p_count++;WriteOut_NoParsing("\n");lastcr=true;} } size_t GetPauseCount(); if (p_count>GetPauseCount()) { WriteOut(MSG_Get("SHELL_CMD_PAUSE")); lastcr=false; w_count = p_count = 0; uint8_t c;uint16_t n=1; DOS_ReadFile(STDIN,&c,&n); if (c==3) {ctrlbrk=false;WriteOut("^C\r\n");break;} if (c==0) DOS_ReadFile(STDIN,&c,&n); } } if (l_completion.size()) { if (!lastcr) WriteOut_NoParsing("\n"); ShowPrompt(); WriteOut("%s", line); } break; } case'\t': if (l_completion.size()) { ++it_completion; if (it_completion == l_completion.end()) it_completion = l_completion.begin(); } else if (BuildCompletions(line, str_len)) it_completion = l_completion.begin(); else break; if (l_completion.size() && it_completion->length()) { for (;str_index > completion_index; str_index--) { // removes all characters backone(); outc(' '); backone(); } strcpy(&line[completion_index], it_completion->c_str()); len = (uint16_t)it_completion->length(); str_len = str_index = (Bitu)(completion_index + len); size = (unsigned int)CMD_MAXLINE - str_index - 2u; DOS_WriteFile(STDOUT, (uint8_t *)it_completion->c_str(), &len); } break; case 0x1b: /* ESC */ // NTS: According to real PC-98 DOS: // If DOSKEY is loaded, ESC clears the prompt // If DOSKEY is NOT loaded, ESC does nothing. In fact, after ESC, // the next character input is thrown away before resuming normal keyboard input. // // DOSBox / DOSBox-X have always acted as if DOSKEY is loaded in a fashion, so // we'll emulate the PC-98 DOSKEY behavior here. // // DOSKEY on PC-98 is able to clear the whole prompt and even bring the cursor // back up to the first line if the input crosses multiple lines. // NTS: According to real IBM/Microsoft PC/AT DOS: // If DOSKEY is loaded, ESC clears the prompt // If DOSKEY is NOT loaded, ESC prints a backslash and goes to the next line. // The Windows 95 version of DOSKEY puts the cursor at a horizontal position // that matches the DOS prompt (not emulated here). // // DOSBox / DOSBox-X have always acted as if DOSKEY is loaded in a fashion, so // we'll emulate DOSKEY behavior here. while (str_index < str_len) { uint16_t count = 1, wide = 1; if(IS_PC98_ARCH || (isDBCSCP() #if defined(USE_TTF) && dbcs_sbcs #endif && IS_DOS_JAPANESE)) { count = GetLastCount(line, str_index+1); wide = GetWideCount(line, str_index+1); } outc(' '); str_index++; if (wide > count) str_index ++; } while (str_index > 0) { uint16_t count = 1, wide = 1; if(IS_PC98_ARCH || (isDBCSCP() #if defined(USE_TTF) && dbcs_sbcs #endif && IS_DOS_JAPANESE)) { count = GetLastCount(line, str_index); wide = GetWideCount(line, str_index); } backone(); outc(' '); backone(); MoveCaretBackwards(); str_index--; if (wide > count) str_index --; } *line = 0; // reset the line. if (l_completion.size()) l_completion.clear(); //reset the completion list. str_index = 0; str_len = 0; break; default: if(IS_PC98_ARCH || (isDBCSCP() #if defined(USE_TTF) && dbcs_sbcs #endif && IS_DOS_JAPANESE)) { bool kanji_flag = false; uint16_t pos = str_index; while(1) { if (l_completion.size()) l_completion.clear(); if(str_index < str_len && true) { for(Bitu i=str_len;i>str_index;i--) { line[i]=line[i-1]; } line[++str_len]=0; size--; } line[str_index]=c; str_index ++; if (str_index > str_len) { line[str_index] = '\0'; str_len++; size--; } if(!isKanji1(c) || kanji_flag) { break; } DOS_ReadFile(input_handle,&c,&n); kanji_flag = true; } while(pos < str_len) { outc(line[pos]); pos++; } pos = GetRemoveCount(line, str_len); while(pos > str_index) { backone(); pos--; if (CheckHat(line[pos])) { backone(); } } } else { if (cr >= 0x100) break; if (l_completion.size()) l_completion.clear(); if(str_index < str_len && !INT10_GetInsertState()) { //mem_readb(BIOS_KEYBOARD_FLAGS1)&0x80) dev_con.h ? outc(' ');//move cursor one to the right. uint16_t a = str_len - str_index; uint8_t* text=reinterpret_cast<uint8_t*>(&line[str_index]); DOS_WriteFile(STDOUT,text,&a);//write buffer to screen backone();//undo the cursor the right. for(Bitu i=str_len;i>str_index;i--) { line[i]=line[i-1]; //move internal buffer backone(); //move cursor back (from write buffer to screen) } line[++str_len]=0;//new end (as the internal buffer moved one place to the right size--; } line[str_index]=(char)(cr&0xFF); str_index ++; if (str_index > str_len){ line[str_index] = '\0'; str_len++; size--; } DOS_WriteFile(STDOUT,&c,&n); } break; } } inshell = false; if (!str_len) return; str_len++; // remove current command from history if it's there if (current_hist) { // current_hist=false; l_history.pop_front(); } // add command line to history. Win95 behavior with DOSKey suggests // that the original string is preserved, not the expanded string. l_history.emplace_front(line); it_history = l_history.begin(); if (l_completion.size()) l_completion.clear(); /* DOS %variable% substitution */ ProcessCmdLineEnvVarStitution(line); } void XMS_DOS_LocalA20DisableIfNotEnabled(void); /* Note: Buffer pointed to by "line" must be at least CMD_MAXLINE+1 bytes long! */ void DOS_Shell::ProcessCmdLineEnvVarStitution(char *line) { // Wengier: Rewrote the code using regular expressions (a lot shorter) // Tested by both myself and kcgen with various boundary cases /* DOS7/Win95 testing: * * "%" = "%" * "%%" = "%" * "% %" = "" * "% %" = "" * "% % %" = " %" * * ^ WTF? * * So the below code has funny conditions to match Win95's weird rules on what * consitutes valid or invalid %variable% names. */ /* continue scanning for the ending '%'. variable names are apparently meant to be * alphanumeric, start with a letter, without spaces (if Windows 95 COMMAND.COM is * any good example). If it doesn't end in '%' or is broken by space or starts with * a number, substitution is not carried out. In the middle of the variable name * it seems to be acceptable to use hyphens. * * since spaces break up a variable name to prevent substitution, these commands * act differently from one another: * * C:\>echo %PATH% * C:\DOS;C:\WINDOWS * * C:\>echo %PATH % * %PATH % */ /* initial scan: is there anything to substitute? */ /* if not, then just return without modifying "line" */ /* not really needed but keep this code as is for now */ char *r=line; while (*r != 0 && *r != '%') r++; if (*r != '%') return; /* if the incoming string is already too long, then that's a problem too! */ if (((size_t)(r+1-line)) >= CMD_MAXLINE) { LOG_MSG("DOS_Shell::ProcessCmdLineEnvVarStitution WARNING incoming string to substitute is already too long!\n"); *line = 0; /* clear string (C-string chop with NUL) */ WriteOut("Command input error: string expansion overflow\n"); return; } // Begin the process of shell variable substitutions using regular expressions // Variable names must start with non-digits. Space and special symbols like _ and ~ are apparently valid too (MS-DOS 7/Windows 9x). constexpr char surrogate_percent = 8; const static std::regex re("\\%([^%0-9][^%]*)?%"); bool isfor = !strncasecmp(ltrim(line),"FOR ",4); char *p = isfor?strchr(line, '%'):NULL; std::string text = p?p+1:line; std::smatch match; /* Iterate over potential %var1%, %var2%, etc matches found in the text string */ while (std::regex_search(text, match, re)) { // Get the first matching %'s position and length const auto percent_pos = static_cast<size_t>(match.position(0)); const auto percent_len = static_cast<size_t>(match.length(0)); std::string variable_name = match[1].str(); if (variable_name.empty()) { /* Replace %% with the character "surrogate_percent", then (eventually) % */ text.replace(percent_pos, percent_len, std::string(1, surrogate_percent)); continue; } /* Trim preceding spaces from the variable name */ variable_name.erase(0, variable_name.find_first_not_of(' ')); std::string variable_value; if (variable_name.size() && GetEnvStr(variable_name.c_str(), variable_value)) { const size_t equal_pos = variable_value.find_first_of('='); /* Replace the original %var% with its corresponding value from the environment */ const std::string replacement = equal_pos != std::string::npos ? variable_value.substr(equal_pos + 1) : ""; text.replace(percent_pos, percent_len, replacement); } else text.replace(percent_pos, percent_len, ""); } std::replace(text.begin(), text.end(), surrogate_percent, '%'); if (p) { *(p+1) = 0; text = std::string(line) + text; } assert(text.size() <= CMD_MAXLINE); strcpy(line, text.c_str()); } int infix=-1; std::string full_arguments = ""; bool dos_a20_disable_on_exec=false; extern bool packerr, mountwarning, nowarn; bool DOS_Shell::Execute(char* name, const char* args) { /* return true => don't check for hardware changes in do_command * return false => check for hardware changes in do_command */ char fullname[DOS_PATHLENGTH+4]; //stores results from Which const char* p_fullname; char line[CMD_MAXLINE]; if(strlen(args)!= 0){ if(*args != ' '){ //put a space in front line[0]=' ';line[1]=0; strncat(line,args,CMD_MAXLINE-2); line[CMD_MAXLINE-1]=0; } else { safe_strncpy(line,args,CMD_MAXLINE); } }else{ line[0]=0; } const Section_prop* sec = static_cast<Section_prop*>(control->GetSection("dos")); /* check for a drive change */ if (((strcmp(name + 1, ":") == 0) || (strcmp(name + 1, ":\\") == 0)) && isalpha(*name) && !control->SecureMode()) { uint8_t c;uint16_t n; if (strrchr_dbcs(name,'\\')) { WriteOut(MSG_Get("SHELL_EXECUTE_ILLEGAL_COMMAND"),name); return true; } if (!DOS_SetDrive(toupper(name[0])-'A')) { #ifdef WIN32 if(!sec->Get_bool("automount")) { WriteOut(MSG_Get("SHELL_EXECUTE_DRIVE_NOT_FOUND"),toupper(name[0])); return true; } // automount: attempt direct letter to drive map. int type=GetDriveType(name); if(!mountwarning && type!=DRIVE_NO_ROOT_DIR) goto continue_1; if(type==DRIVE_FIXED && (strcasecmp(name,"C:")==0)) WriteOut(MSG_Get("PROGRAM_MOUNT_WARNING_WIN")); first_1: if(type==DRIVE_CDROM) WriteOut(MSG_Get("SHELL_EXECUTE_DRIVE_ACCESS_CDROM"),toupper(name[0])); else if(type==DRIVE_REMOVABLE && (strcasecmp(name,"A:")==0||strcasecmp(name,"B:")==0)) WriteOut(MSG_Get("SHELL_EXECUTE_DRIVE_ACCESS_FLOPPY"),toupper(name[0])); else if(type==DRIVE_REMOVABLE) WriteOut(MSG_Get("SHELL_EXECUTE_DRIVE_ACCESS_REMOVABLE"),toupper(name[0])); else if(type==DRIVE_REMOTE) WriteOut(MSG_Get("SHELL_EXECUTE_DRIVE_ACCESS_NETWORK"),toupper(name[0])); else if(type==DRIVE_FIXED||type==DRIVE_RAMDISK||type==DRIVE_UNKNOWN) WriteOut(MSG_Get("SHELL_EXECUTE_DRIVE_ACCESS_FIXED"),toupper(name[0])); else { WriteOut(MSG_Get("SHELL_EXECUTE_DRIVE_NOT_FOUND"),toupper(name[0])); return true; } first_2: n=1; DOS_ReadFile (STDIN,&c,&n); do switch (c) { case 'n': case 'N': { DOS_WriteFile (STDOUT,&c, &n); DOS_ReadFile (STDIN,&c,&n); do switch (c) { case 0xD: WriteOut("\n\n"); WriteOut(MSG_Get("SHELL_EXECUTE_DRIVE_NOT_FOUND"),toupper(name[0])); return true; case 0x3: return true; case 0x8: WriteOut("\b \b"); goto first_2; } while (DOS_ReadFile (STDIN,&c,&n)); } case 'y': case 'Y': { DOS_WriteFile (STDOUT,&c, &n); DOS_ReadFile (STDIN,&c,&n); do switch (c) { case 0xD: WriteOut("\n"); goto continue_1; case 0x3: return true; case 0x8: WriteOut("\b \b"); goto first_2; } while (DOS_ReadFile (STDIN,&c,&n)); } case 0x3: return true; case 0xD: WriteOut("\n"); goto first_1; case '\t': case 0x08: goto first_2; default: { DOS_WriteFile (STDOUT,&c, &n); DOS_ReadFile (STDIN,&c,&n); do switch (c) { case 0xD: WriteOut("\n");goto first_1; case 0x3: return true; case 0x8: WriteOut("\b \b"); goto first_2; } while (DOS_ReadFile (STDIN,&c,&n)); goto first_2; } } while (DOS_ReadFile (STDIN,&c,&n)); continue_1: char mountstring[DOS_PATHLENGTH+CROSS_LEN+20]; sprintf(mountstring,"MOUNT %s ",name); if(type==DRIVE_CDROM) strcat(mountstring,"-t cdrom "); else if(type==DRIVE_REMOVABLE && (strcasecmp(name,"A:")==0||strcasecmp(name,"B:")==0)) strcat(mountstring,"-t floppy "); strcat(mountstring,name); strcat(mountstring,"\\"); // if(GetDriveType(name)==5) strcat(mountstring," -ioctl"); nowarn=true; this->ParseLine(mountstring); nowarn=false; //failed: if (!DOS_SetDrive(toupper(name[0])-'A')) #endif WriteOut(MSG_Get("SHELL_EXECUTE_DRIVE_NOT_FOUND"),toupper(name[0])); } return true; } /* Check for a full name */ p_fullname = Which(name); if (!p_fullname) return false; strcpy(fullname,p_fullname); std::string assoc = hasAssociation(fullname); if (assoc.size()) { noassoc=true; DoCommand((char *)(assoc+" "+fullname).c_str()); noassoc=false; return true; } const char* extension = strrchr(fullname,'.'); /*always disallow files without extension from being executed. */ /*only internal commands can be run this way and they never get in this handler */ if(extension == 0) { //Check if the result will fit in the parameters. Else abort if(strlen(fullname) >( DOS_PATHLENGTH - 1) ) return false; char temp_name[DOS_PATHLENGTH + 4]; const char* temp_fullname; //try to add .com, .exe and .bat extensions to filename strcpy(temp_name,fullname); strcat(temp_name,".COM"); temp_fullname=Which(temp_name); if (temp_fullname) { extension=".com";strcpy(fullname,temp_fullname); } else { strcpy(temp_name,fullname); strcat(temp_name,".EXE"); temp_fullname=Which(temp_name); if (temp_fullname) { extension=".exe";strcpy(fullname,temp_fullname);} else { strcpy(temp_name,fullname); strcat(temp_name,".BAT"); temp_fullname=Which(temp_name); if (temp_fullname) { extension=".bat";strcpy(fullname,temp_fullname);} else { return false; } } } } if (strcasecmp(extension, ".bat") == 0) { /* Run the .bat file */ /* delete old batch file if call is not active*/ bool temp_echo=echo; /*keep the current echostate (as delete bf might change it )*/ if(bf && !call) delete bf; bf=new BatchFile(this,fullname,name,line); echo=temp_echo; //restore it. } else { /* only .bat .exe .com extensions maybe be executed by the shell */ if(strcasecmp(extension, ".com") !=0) { if(strcasecmp(extension, ".exe") !=0) return false; } /* Run the .exe or .com file from the shell */ /* Allocate some stack space for tables in physical memory */ reg_sp-=0x200; //Add Parameter block DOS_ParamBlock block(SegPhys(ss)+reg_sp); block.Clear(); //Add a filename RealPt file_name=RealMakeSeg(ss,reg_sp+0x20); MEM_BlockWrite(Real2Phys(file_name),fullname,(Bitu)(strlen(fullname)+1)); /* HACK: Store full commandline for mount and imgmount */ full_arguments.assign(line); /* Fill the command line */ CommandTail cmdtail; cmdtail.count = 0; memset(&cmdtail.buffer,0,CTBUF); //Else some part of the string is unitialized (valgrind) if (strlen(line)>=CTBUF) line[CTBUF-1]=0; cmdtail.count=(uint8_t)strlen(line); memcpy(cmdtail.buffer,line,strlen(line)); cmdtail.buffer[strlen(line)]=0xd; /* Copy command line in stack block too */ MEM_BlockWrite(SegPhys(ss)+reg_sp+0x100,&cmdtail,CTBUF+1); /* Split input line up into parameters, using a few special rules, most notable the one for /AAA => A\0AA * Qbix: It is extremly messy, but this was the only way I could get things like /:aa and :/aa to work correctly */ //Prepare string first char parseline[258] = { 0 }; for(char *pl = line,*q = parseline; *pl ;pl++,q++) { if (*pl == '=' || *pl == ';' || *pl ==',' || *pl == '\t' || *pl == ' ') *q = 0; else *q = *pl; //Replace command seperators with 0. } //No end of string \0 needed as parseline is larger than line for(char* p = parseline; (p-parseline) < 250 ;p++) { //Stay relaxed within boundaries as we have plenty of room if (*p == '/') { //Transform /Hello into H\0ello *p = 0; p++; while ( *p == 0 && (p-parseline) < 250) p++; //Skip empty fields if ((p-parseline) < 250) { //Found something. Lets get the first letter and break it up p++; memmove(static_cast<void*>(p + 1),static_cast<void*>(p),(250u-(unsigned int)(p-parseline))); if ((p-parseline) < 250) *p = 0; } } } parseline[255] = parseline[256] = parseline[257] = 0; //Just to be safe. /* Parse FCB (first two parameters) and put them into the current DOS_PSP */ uint8_t add; uint16_t skip = 0; //find first argument, we end up at parseline[256] if there is only one argument (similar for the second), which exists and is 0. while(skip < 256 && parseline[skip] == 0) skip++; FCB_Parsename(dos.psp(),0x5C,0x01,parseline + skip,&add); skip += add; //Move to next argument if it exists while(parseline[skip] != 0) skip++; //This is safe as there is always a 0 in parseline at the end. while(skip < 256 && parseline[skip] == 0) skip++; //Which is higher than 256 FCB_Parsename(dos.psp(),0x6C,0x01,parseline + skip,&add); block.exec.fcb1=RealMake(dos.psp(),0x5C); block.exec.fcb2=RealMake(dos.psp(),0x6C); /* Set the command line in the block and save it */ block.exec.cmdtail=RealMakeSeg(ss,reg_sp+0x100); block.SaveData(); #if 0 /* Save CS:IP to some point where i can return them from */ uint32_t oldeip=reg_eip; uint16_t oldcs=SegValue(cs); RealPt newcsip=CALLBACK_RealPointer(call_shellstop); SegSet16(cs,RealSeg(newcsip)); reg_ip=RealOff(newcsip); #endif packerr=false; /* Start up a dos execute interrupt */ reg_ax=0x4b00; //Filename pointer SegSet16(ds,SegValue(ss)); reg_dx=RealOff(file_name); //Paramblock SegSet16(es,SegValue(ss)); reg_bx=reg_sp; SETFLAGBIT(IF,false); CALLBACK_RunRealInt(0x21); /* Restore CS:IP and the stack */ reg_sp+=0x200; #if 0 reg_eip=oldeip; SegSet16(cs,oldcs); #endif if (packerr&&infix<0&&sec->Get_bool("autoa20fix")) { LOG(LOG_DOSMISC,LOG_DEBUG)("Attempting autoa20fix workaround for EXEPACK error"); if (autofixwarn==1||autofixwarn==3) WriteOut("\r\n\033[41;1m\033[1;37;1mDOSBox-X\033[0m Failed to load the executable\r\n\033[41;1m\033[37;1mDOSBox-X\033[0m Now try again with A20 fix...\r\n"); infix=0; dos_a20_disable_on_exec=true; Execute(name, args); dos_a20_disable_on_exec=false; infix=-1; } else if (packerr&&infix<1&&sec->Get_bool("autoloadfix")) { uint16_t segment; uint16_t blocks = (uint16_t)(1); /* start with one paragraph, resize up later. see if it comes up below the 64KB mark */ if (DOS_AllocateMemory(&segment,&blocks)) { DOS_MCB mcb((uint16_t)(segment-1)); if (segment < 0x1000) { uint16_t needed = 0x1000 - segment; DOS_ResizeMemory(segment,&needed); } mcb.SetPSPSeg(0x40); /* FIXME: Wouldn't 0x08, a magic value used to show ownership by MS-DOS, be more appropriate here? */ LOG(LOG_DOSMISC,LOG_DEBUG)("Attempting autoloadfix workaround for EXEPACK error"); if (autofixwarn==2||autofixwarn==3) WriteOut("\r\n\033[41;1m\033[1;37;1mDOSBox-X\033[0m Failed to load the executable\r\n\033[41;1m\033[37;1mDOSBox-X\033[0m Now try again with LOADFIX...\r\n"); infix=1; Execute(name, args); infix=-1; DOS_FreeMemory(segment); } } else if (packerr&&infix<2&&!autofixwarn) { WriteOut("Packed file is corrupt"); } packerr=false; } return true; //Executable started } static const char * bat_ext=".BAT"; static const char * com_ext=".COM"; static const char * exe_ext=".EXE"; static char which_ret[DOS_PATHLENGTH+4], s_ret[DOS_PATHLENGTH+4]; extern bool wild_match(const char *haystack, char *needle); static std::string assocs = ""; std::string DOS_Shell::hasAssociation(const char* name) { if (noassoc) { assocs = ""; return assocs; } std::string extension = strrchr(name, '.') ? strrchr(name, '.') : "."; cmd_assoc_map_t::iterator iter = cmd_assoc.find(extension.c_str()); if (iter != cmd_assoc.end()) { assocs = strcasecmp(extension.c_str(), iter->second.c_str()) ? iter->second : ""; return assocs; } std::transform(extension.begin(), extension.end(), extension.begin(), ::toupper); for (cmd_assoc_map_t::iterator iter = cmd_assoc.begin(); iter != cmd_assoc.end(); ++iter) { std::string ext = iter->first; if (ext.find('*')==std::string::npos && ext.find('?')==std::string::npos) continue; std::transform(ext.begin(), ext.end(), ext.begin(), ::toupper); if (wild_match(extension.c_str(), (char *)ext.c_str())) { assocs = strcasecmp(extension.c_str(), iter->second.c_str()) ? iter->second : ""; return assocs; } } assocs = ""; return assocs; } bool DOS_Shell::hasExecutableExtension(const char* name) { auto extension = strrchr(name, '.'); if (!extension) return false; return (!strcasecmp(extension, com_ext) || !strcasecmp(extension, exe_ext) || !strcasecmp(extension, bat_ext)); } char * DOS_Shell::Which(char * name) { size_t name_len = strlen(name); if(name_len >= DOS_PATHLENGTH) return 0; /* Parse through the Path to find the correct entry */ /* Check if name is already ok but just misses an extension */ std::string upname = name; std::transform(upname.begin(), upname.end(), upname.begin(), ::toupper); if (hasAssociation(name).size() && DOS_FileExists(name)) return name; else if (hasAssociation(name).size() && DOS_FileExists(upname.c_str())) { strcpy(name, upname.c_str()); return name; } else if (hasExecutableExtension(name)) { if (DOS_FileExists(name)) return name; strcpy(name, upname.c_str()); if (DOS_FileExists(name)) return name; } else { /* try to find .com .exe .bat */ strcpy(which_ret,name); strcat(which_ret,com_ext); if (DOS_FileExists(which_ret)) return which_ret; strcpy(which_ret,name); strcat(which_ret,exe_ext); if (DOS_FileExists(which_ret)) return which_ret; strcpy(which_ret,name); strcat(which_ret,bat_ext); if (DOS_FileExists(which_ret)) return which_ret; } /* No Path in filename look through path environment string */ char path[DOS_PATHLENGTH];std::string temp; if (!GetEnvStr("PATH",temp)) return 0; const char * pathenv=temp.c_str(); if (!pathenv) return 0; pathenv = strchr(pathenv,'='); if (!pathenv) return 0; pathenv++; while (*pathenv) { /* remove ; and ;; at the beginning. (and from the second entry etc) */ while(*pathenv == ';') pathenv++; /* get next entry */ Bitu i_path = 0; /* reset writer */ while(*pathenv && (*pathenv !=';') && (i_path < DOS_PATHLENGTH) ) path[i_path++] = *pathenv++; if(i_path == DOS_PATHLENGTH) { /* If max size. move till next ; and terminate path */ while(*pathenv && (*pathenv != ';')) pathenv++; path[DOS_PATHLENGTH - 1] = 0; } else path[i_path] = 0; int k=0; for (int i=0;i<(int)strlen(path);i++) if (path[i]!='\"') path[k++]=path[i]; path[k]=0; /* check entry */ if(size_t len = strlen(path)){ if(len >= (DOS_PATHLENGTH - 2)) continue; if (uselfn&&len>3) { if (path[len - 1]=='\\') path[len - 1]=0; if (DOS_GetSFNPath(("\""+std::string(path)+"\"").c_str(), s_ret, false)) strcpy(path, s_ret); len = strlen(path); } if(path[len - 1] != '\\') { strcat(path,"\\"); len++; } //If name too long =>next if((name_len + len + 1) >= DOS_PATHLENGTH) continue; strcat(path,strchr(name, ' ')?("\""+std::string(name)+"\"").c_str():name); if (hasAssociation(path).size() && DOS_FileExists(path)) { strcpy(which_ret,path); return strchr(which_ret, '\"')&&DOS_GetSFNPath(which_ret, s_ret, false)?s_ret:which_ret; } else if (hasExecutableExtension(path)) { strcpy(which_ret,path); if (DOS_FileExists(which_ret)) return strchr(which_ret, '\"')&&DOS_GetSFNPath(which_ret, s_ret, false)?s_ret:which_ret; } else { strcpy(which_ret,path); strcat(which_ret,com_ext); if (DOS_FileExists(which_ret)) return strchr(which_ret, '\"')&&DOS_GetSFNPath(which_ret, s_ret, false)?s_ret:which_ret; strcpy(which_ret,path); strcat(which_ret,exe_ext); if (DOS_FileExists(which_ret)) return strchr(which_ret, '\"')&&DOS_GetSFNPath(which_ret, s_ret, false)?s_ret:which_ret; strcpy(which_ret,path); strcat(which_ret,bat_ext); if (DOS_FileExists(which_ret)) return strchr(which_ret, '\"')&&DOS_GetSFNPath(which_ret, s_ret, false)?s_ret:which_ret; } } } return 0; }
36.853222
230
0.531862
mediaexplorer74
893c71e6fee5711ebd8b2e222cd3c594e69455d9
1,925
cpp
C++
firmware/examples/PinConfigure/source/main.cpp
2721Aperez/SJSU-Dev2
87052080d2754803dbd1dae2864bd9024d123086
[ "Apache-2.0" ]
1
2018-07-07T01:41:34.000Z
2018-07-07T01:41:34.000Z
firmware/examples/PinConfigure/source/main.cpp
2721Aperez/SJSU-Dev2
87052080d2754803dbd1dae2864bd9024d123086
[ "Apache-2.0" ]
null
null
null
firmware/examples/PinConfigure/source/main.cpp
2721Aperez/SJSU-Dev2
87052080d2754803dbd1dae2864bd9024d123086
[ "Apache-2.0" ]
1
2018-09-19T01:58:48.000Z
2018-09-19T01:58:48.000Z
#include <cstdarg> #include <cstdint> #include <cstdio> #include <cstdlib> #include "config.hpp" #include "L0_LowLevel/LPC40xx.h" #include "L1_Drivers/pin_configure.hpp" #include "L2_Utilities/debug_print.hpp" int main(void) { // This application assumes that all pins are set to function 0 (GPIO) DEBUG_PRINT("Pin Configure Application Starting..."); // Using constructor directly to constuct PinConfigure object // This is discouraged, since this constructor does not perform any compile // time checks on the port or pin value PinConfigure p0_0(0, 7); p0_0.SetPinMode(PinConfigureInterface::PinMode::kInactive); DEBUG_PRINT("Disabling both pull up and down resistors for P0.0..."); // Prefered option of constructing PinConfigure, since this factory call is // done in compile time and will perform compile time validation on the port // and pin template parameters. PinConfigure p1_24 = PinConfigure::CreatePinConfigure<1, 24>(); p1_24.SetPinMode(PinConfigureInterface::PinMode::kPullDown); DEBUG_PRINT("Enabling P1.24 pull down resistor..."); PinConfigure p2_0 = PinConfigure::CreatePinConfigure<2, 0>(); p2_0.SetPinMode(PinConfigureInterface::PinMode::kPullUp); DEBUG_PRINT("Enabling P2.0 pull up resistor..."); PinConfigure p4_28 = PinConfigure::CreatePinConfigure<4, 29>(); p4_28.SetPinMode(PinConfigureInterface::PinMode::kRepeater); DEBUG_PRINT("Setting P4.29 to repeater mode..."); DEBUG_PRINT( "Use some jumpers and a multimeter to test each pin to see if the " "internal pull up and pull down resistors are working."); DEBUG_PRINT( "Use a jumper and resistor to pull P4.28 high or low. If you check the " "pin with a multimeter you will see that the pin retains the previous " "input value."); DEBUG_PRINT("Halting any action."); while (1) { continue; } return 0; }
40.104167
80
0.714805
2721Aperez
893dfb6e98893ed83575b82458c15e8f2a1ae6a6
3,405
cpp
C++
Source/Components/MenuComponent.cpp
Aavu/MIDI-Editor
4991beec683e75d5867117230dcafb2709192c81
[ "MIT" ]
5
2020-06-06T02:14:00.000Z
2020-12-03T12:54:57.000Z
Source/Components/MenuComponent.cpp
Aavu/MIDI-Editor
4991beec683e75d5867117230dcafb2709192c81
[ "MIT" ]
9
2020-03-28T22:26:10.000Z
2020-04-29T04:55:08.000Z
Source/Components/MenuComponent.cpp
Aavu/MIDI-Editor
4991beec683e75d5867117230dcafb2709192c81
[ "MIT" ]
1
2020-12-01T22:42:48.000Z
2020-12-01T22:42:48.000Z
/* ============================================================================== MenuComponent.cpp Created: 12 Jan 2020 12:28:18pm Author: Raghavasimhan Sankaranarayanan ============================================================================== */ #include "../JuceLibraryCode/JuceHeader.h" #include "MenuComponent.h" //============================================================================== MenuComponent::MenuComponent() { // In your constructor, you should add any child components, and // initialise any special settings that your component needs. menuBar.reset(new MenuBarComponent(this)); addAndMakeVisible(menuBar.get()); setApplicationCommandManagerToWatch(&commandManager); commandManager.registerAllCommandsForTarget(this); addKeyListener(commandManager.getKeyMappings()); // addAndMakeVisible(editCommandTarget); MenuBarModel::setMacMainMenu(this); commandManager.setFirstCommandTarget(this); } MenuComponent::~MenuComponent() { MenuBarModel::setMacMainMenu(nullptr); } void MenuComponent::setPlayer(std::shared_ptr<PlayerComponent> player) { m_pPlayer = std::move(player); } void MenuComponent::paint (Graphics& g) {} void MenuComponent::resized() {} StringArray MenuComponent::getMenuBarNames() { return {"File"}; } PopupMenu MenuComponent::getMenuForIndex(int menuIndex, const String& name) { PopupMenu menu; if (menuIndex == 0) { menu.addCommandItem(&commandManager, fileOpen); menu.addCommandItem(&commandManager, fileExportAudio); // menu.addCommandItem(&commandManager, fileExportMIDI); } // else if (menuIndex == 1) { // menu.addCommandItem(&commandManager, helpDocumentation); // } return menu; } ApplicationCommandTarget* MenuComponent::getNextCommandTarget() { return nullptr; } void MenuComponent::getAllCommands (Array<CommandID>& c) { Array<CommandID> commands { fileOpen, fileExportAudio }; c.addArray (commands); } void MenuComponent::getCommandInfo (CommandID commandID, ApplicationCommandInfo& result) { switch (commandID) { case fileOpen: result.setInfo ("Open", "Open MIDI file", "File", 0); result.addDefaultKeypress ('i', ModifierKeys::commandModifier); break; case fileExportAudio: result.setInfo ("Export Audio", "Export Audio", "File", 0); result.addDefaultKeypress ('b', ModifierKeys::commandModifier); if (m_pPlayer) result.setActive(m_pPlayer->isSequenceLoaded()); else result.setActive(false); break; // case fileExportMIDI: // result.setInfo ("Export MIDI", "Export MIDI", "File", 0); // result.addDefaultKeypress ('b', ModifierKeys::shiftModifier | ModifierKeys::commandModifier); // break; default: break; } } void MenuComponent::menuItemSelected (int /*menuItemID*/, int /*topLevelMenuIndex*/) {} bool MenuComponent::perform (const InvocationInfo& info) { return callbackFunc(static_cast<CommandIDs>(info.commandID)); } void MenuComponent::setCallback(cbfunc func) { callbackFunc = func; } void MenuComponent::actionListenerCallback (const String& message) { if (message == Globals::ActionMessage::EnableTransport) { commandManager.commandStatusChanged(); } }
31.238532
107
0.636417
Aavu
8947090d3e9a56d48781d56c2698dc154885bdf0
420
cpp
C++
hackerrank/sansa-and-xor/solution.cpp
SamProkopchuk/coding-problems
fa0ca2c05ac90e41945de1a5751e5545a8459ac4
[ "MIT" ]
null
null
null
hackerrank/sansa-and-xor/solution.cpp
SamProkopchuk/coding-problems
fa0ca2c05ac90e41945de1a5751e5545a8459ac4
[ "MIT" ]
null
null
null
hackerrank/sansa-and-xor/solution.cpp
SamProkopchuk/coding-problems
fa0ca2c05ac90e41945de1a5751e5545a8459ac4
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> typedef signed long long ll; typedef unsigned long long ull; #define FOR(x, to) for (x = 0; x < (to); ++x) #define FORR(x, arr) for (auto &x : arr) using namespace std; int main() { int t; cin >> t; while (t--) { int n, i, x, ans; ans = 0; cin >> n; FOR(i, n) { cin >> x; if (n % 2 && (i + 1) % 2) ans ^= x; } cout << ans << endl; } return 0; }
16.153846
45
0.485714
SamProkopchuk
894745f19fa7a9f07ecace1540adf076cd461e69
2,180
hpp
C++
src/avatar.hpp
tilnewman/halloween
7cea37e31b2e566be76707cd8dc48527cec95bc5
[ "MIT" ]
null
null
null
src/avatar.hpp
tilnewman/halloween
7cea37e31b2e566be76707cd8dc48527cec95bc5
[ "MIT" ]
null
null
null
src/avatar.hpp
tilnewman/halloween
7cea37e31b2e566be76707cd8dc48527cec95bc5
[ "MIT" ]
null
null
null
#ifndef AVATAR_HPP_INCLUDED #define AVATAR_HPP_INCLUDED // // avatar.hpp // #include "avatar-anim.hpp" #include "blood.hpp" #include <vector> #include <SFML/Graphics/Sprite.hpp> #include <SFML/Graphics/Texture.hpp> namespace halloween { struct Settings; struct Context; enum class Action { Idle, Attack, Run, Jump, Throw, Dead }; class Avatar { public: Avatar(); void setup(const Settings & settings); void draw(sf::RenderTarget & target, sf::RenderStates states) const; sf::FloatRect collisionRect() const; sf::FloatRect attackCollisionRect() const; void setPosition(const sf::FloatRect & RECT); void update(Context & context, const float FRAME_TIME_SEC); private: void moveMap(Context & context); void setAction(const Action ACTION); bool handleDeath(Context & context, const float FRAME_TIME_SEC); bool handleAttacking(Context & context, const float FRAME_TIME_SEC); bool handleThrowing(Context & context, const float FRAME_TIME_SEC); void sideToSideMotion(Context & context, const float FRAME_TIME_SEC); void jumping(Context & context); void walkCollisions(Context & context); void killCollisions(Context & context); void exitCollisions(Context & context) const; void coinCollisions(Context & context) const; void preventBacktracking(const Context & context); void respawnIfOutOfBounds(Context & context); private: Blood m_blood; AvatarAnim m_runAnim; AvatarAnim m_attackAnim; AvatarAnim m_deathAnim; AvatarAnim m_throwAnim; sf::Texture m_idleTexture; sf::Texture m_jumpTexture; sf::Sprite m_sprite; sf::Vector2f m_velocity; sf::Vector2f m_acceleration; Action m_action; bool m_hasLanded; bool m_isFacingRight; const float m_jumpSpeed; const float m_walkSpeed; const float m_walkSpeedLimit; float m_deadDelaySec; }; } // namespace halloween #endif // AVATAR_HPP_INCLUDED
27.25
77
0.649083
tilnewman
89475fdf52859e38581f578ec22f6a95c93fd0e6
61,755
cpp
C++
lighthub/main.cpp
anklimov/lighthub
99e9c1a27aca52bf38efec000547720fb8f82860
[ "Apache-2.0" ]
83
2017-11-05T14:05:16.000Z
2022-02-21T16:34:53.000Z
lighthub/main.cpp
anklimov/lighthub
99e9c1a27aca52bf38efec000547720fb8f82860
[ "Apache-2.0" ]
27
2018-03-12T21:49:33.000Z
2022-01-20T19:06:05.000Z
lighthub/main.cpp
anklimov/lighthub
99e9c1a27aca52bf38efec000547720fb8f82860
[ "Apache-2.0" ]
20
2017-11-20T08:27:17.000Z
2022-03-28T02:26:17.000Z
/* Copyright © 2017-2018 Andrey Klimov. 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. Homepage: http://lazyhome.ru GIT: https://github.com/anklimov/lighthub e-mail anklimov@gmail.com * * * Done: * MQMT/openhab * 1-wire * DMX - out * DMX IN * 1809 strip out (discarded) * Modbus master Out * DHCP * JSON config * cli * PWM Out 7,8,9 * 1-w relay out * Termostat out Todo (backlog) === rotary encoder local ctrl ? analog in local ctrl Smooth regulation/fading PID Termostat out ? dmx relay out Relay array channel Relay DMX array channel Config URL & MQTT password commandline configuration 1-wire Update refactoring (save memory) Topic configuration Timer Modbus response check control/debug (Commandline) over MQTT more Modbus dimmers todo DUE related: PWM freq fix Config webserver SSL todo ESP: Config webserver SSL ESP32 PWM Out */ #include "main.h" #include "statusled.h" extern long timer0_overflow_count; #ifdef WIFI_ENABLE WiFiClient ethClient; #if not defined(WIFI_MANAGER_DISABLE) WiFiManager wifiManager; #endif #else #include <Dhcp.h> EthernetClient ethClient; #endif #if defined(OTA) #include <ArduinoOTA.h> //bool OTA_initialized=false; #endif #if defined(__SAM3X8E__) DueFlashStorage EEPROM; #endif #ifdef ARDUINO_ARCH_ESP32 NRFFlashStorage EEPROM; #endif #ifdef ARDUINO_ARCH_STM32 NRFFlashStorage EEPROM; #endif #ifdef NRF5 NRFFlashStorage EEPROM; #endif #ifdef SYSLOG_ENABLE #include <Syslog.h> #ifndef WIFI_ENABLE EthernetUDP udpSyslogClient; #else WiFiUDP udpSyslogClient; #endif Syslog udpSyslog(udpSyslogClient, SYSLOG_PROTO_BSD); unsigned long timerSyslogPingTime; static char syslogDeviceHostname[16]; Streamlog debugSerial(&debugSerialPort,LOG_DEBUG,&udpSyslog); Streamlog errorSerial(&debugSerialPort,LOG_ERROR,&udpSyslog,ledRED); Streamlog infoSerial (&debugSerialPort,LOG_INFO,&udpSyslog); #else Streamlog debugSerial(&debugSerialPort,LOG_DEBUG); Streamlog errorSerial(&debugSerialPort,LOG_ERROR, ledRED); Streamlog infoSerial (&debugSerialPort,LOG_INFO); #endif statusLED LED(ledRED); lan_status lanStatus = INITIAL_STATE; const char configserver[] PROGMEM = CONFIG_SERVER; const char verval_P[] PROGMEM = QUOTE(PIO_SRC_REV); #if defined(__SAM3X8E__) UID UniqueID; #endif char *deviceName = NULL; aJsonObject *topics = NULL; aJsonObject *root = NULL; aJsonObject *items = NULL; aJsonObject *inputs = NULL; aJsonObject *mqttArr = NULL; #ifdef _modbus aJsonObject *modbusObj = NULL; #endif #ifdef _owire aJsonObject *owArr = NULL; #endif #ifdef _dmxout aJsonObject *dmxArr = NULL; #endif #ifdef SYSLOG_ENABLE bool syslogInitialized = false; #endif uint32_t timerPollingCheck = 0; uint32_t timerInputCheck = 0; uint32_t timerLanCheckTime = 0; uint32_t timerThermostatCheck = 0; uint32_t timerSensorCheck =0; uint32_t WiFiAwaitingTime =0; aJsonObject *pollingItem = NULL; bool owReady = false; bool configOk = false; // At least once connected to MQTT bool configLoaded = false; bool initializedListeners = false; int8_t ethernetIdleCount =0; int8_t configLocked = 0; #if defined (_modbus) ModbusMaster node; #endif byte mac[6]; PubSubClient mqttClient(ethClient); bool wifiInitialized; int mqttErrorRate; #if defined(__SAM3X8E__) void watchdogSetup(void) {} //Do not remove - strong re-definition WDT Init for DUE #endif void cleanConf() { if (!root) return; debugSerial<<F("Unlocking config ...")<<endl; while (configLocked) { //wdt_res(); cmdPoll(); #ifdef _owire if (owReady && owArr) owLoop(); #endif #ifdef _dmxin DMXCheck(); #endif if (isNotRetainingStatus()) pollingLoop(); thermoLoop(); inputLoop(); yield(); } debugSerial<<F("Stopping channels ...")<<endl; //Stoping the channels aJsonObject * item = items->child; while (items && item) { if (item->type == aJson_Array && aJson.getArraySize(item)>0) { Item it(item->name); if (it.isValid()) it.Stop(); yield(); } item = item->next; } pollingItem = NULL; debugSerial<<F("Stopped")<<endl; #ifdef SYSLOG_ENABLE syslogInitialized=false; //Garbage in memory #endif debugSerial<<F("Deleting conf. RAM was:")<<freeRam(); aJson.deleteItem(root); root = NULL; inputs = NULL; items = NULL; topics = NULL; mqttArr = NULL; #ifdef _dmxout dmxArr = NULL; #endif #ifdef _owire owArr = NULL; #endif #ifdef _modbus modbusObj = NULL; #endif debugSerial<<F(" is ")<<freeRam()<<endl; configLoaded=false; configOk=false; } bool isNotRetainingStatus() { return (lanStatus != RETAINING_COLLECTING); } void mqttCallback(char *topic, byte *payload, unsigned int length) { debugSerial<<F("\n[")<<topic<<F("] "); if (!payload) return; payload[length] = 0; int fr = freeRam(); if (fr < 250) { errorSerial<<F("OutOfMemory!")<<endl; return; } LED.flash(ledBLUE); for (unsigned int i = 0; i < length; i++) debugSerial<<((char) payload[i]); debugSerial<<endl; short intopic = 0; short pfxlen = 0; char * itemName = NULL; char * subItem = NULL; { char buf[MQTT_TOPIC_LENGTH + 1]; if (lanStatus == RETAINING_COLLECTING) { setTopic(buf,sizeof(buf),T_OUT); pfxlen = strlen(buf); intopic = strncmp(topic, buf, pfxlen); } else { setTopic(buf,sizeof(buf),T_BCST); pfxlen = strlen(buf); intopic = strncmp(topic, buf, pfxlen ); if (intopic) { setTopic(buf,sizeof(buf),T_DEV); pfxlen = strlen(buf); intopic = strncmp(topic, buf, pfxlen); } } } // in Retaining status - trying to restore previous state from retained output topic. Retained input topics are not relevant. if (intopic) { debugSerial<<F("Skipping.."); return; } itemName=topic+pfxlen; if(!strcmp(itemName,CMDTOPIC) && payload && (strlen((char*) payload)>1)) { // mqttClient.publish(topic, ""); cmd_parse((char *)payload); return; } if (subItem = strchr(itemName, '/')) { *subItem = 0; subItem++; if (*subItem=='$') return; //Skipping homie stuff // debugSerial<<F("Subitem:")<<subItem<<endl; } // debugSerial<<F("Item:")<<itemName<<endl; if (itemName[0]=='$') return; //Skipping homie stuff Item item(itemName); if (item.isValid()) { /* if (item.itemType == CH_GROUP && (lanStatus == RETAINING_COLLECTING)) return; //Do not restore group channels - they consist not relevant data */ item.Ctrl((char *)payload,subItem); } //valid item } void printMACAddress() { infoSerial<<F("MAC:"); for (byte i = 0; i < 6; i++) { if (mac[i]<16) infoSerial<<"0"; #ifdef WITH_PRINTEX_LIB (i < 5) ?infoSerial<<hex <<(mac[i])<<F(":"):infoSerial<<hex<<(mac[i])<<endl; #else (i < 5) ?infoSerial<<_HEX(mac[i])<<F(":"):infoSerial<<_HEX(mac[i])<<endl; #endif } } char* getStringFromConfig(aJsonObject * a, int i) { aJsonObject * element = NULL; if (!a) return NULL; if (a->type == aJson_Array) element = aJson.getArrayItem(a, i); // TODO - human readable JSON objects as alias if (element && element->type == aJson_String) return element->valuestring; return NULL; } char* getStringFromConfig(aJsonObject * a, char * name) { aJsonObject * element = NULL; if (!a) return NULL; if (a->type == aJson_Object) element = aJson.getObjectItem(a, name); if (element && element->type == aJson_String) return element->valuestring; return NULL; } void setupOTA(void) { #ifdef OTA //if (OTA_initialized) return; // ArduinoOTA.end(); // start the OTEthernet library with internal (flash) based storage ArduinoOTA.begin(Ethernet.localIP(), "Lighthub", "password", InternalStorage); infoSerial<<F("OTA initialized\n"); //OTA_initialized=true; #endif } void setupSyslog() { #ifdef SYSLOG_ENABLE int syslogPort = 514; short n = 0; aJsonObject *udpSyslogArr = NULL; if (syslogInitialized) return; if (lanStatus<HAVE_IP_ADDRESS) return; if (!root) return; udpSyslogClient.begin(SYSLOG_LOCAL_SOCKET); udpSyslogArr = aJson.getObjectItem(root, "syslog"); if (udpSyslogArr && (n = aJson.getArraySize(udpSyslogArr))) { char *syslogServer = getStringFromConfig(udpSyslogArr, 0); if (n>1) syslogPort = aJson.getArrayItem(udpSyslogArr, 1)->valueint; _inet_ntoa_r(Ethernet.localIP(),syslogDeviceHostname,sizeof(syslogDeviceHostname)); infoSerial<<F("Syslog params:")<<syslogServer<<":"<<syslogPort<<":"<<syslogDeviceHostname<<endl; udpSyslog.server(syslogServer, syslogPort); udpSyslog.deviceHostname(syslogDeviceHostname); if (mqttArr) deviceName = getStringFromConfig(mqttArr, 0); if (deviceName) udpSyslog.appName(deviceName); udpSyslog.defaultPriority(LOG_KERN); syslogInitialized=true; infoSerial<<F("UDP Syslog initialized.\n"); } #endif } lan_status lanLoop() { #ifdef NOETHER lanStatus=DO_NOTHING;//-14; #endif //Serial.println(lanStatus); switch (lanStatus) { case INITIAL_STATE: // LED.set(ledRED|((configLoaded)?ledBLINK:0)); LED.set(ledRED|((configLoaded)?ledBLINK:0)); #if defined(WIFI_ENABLE) onInitialStateInitLAN(); // Moves state to AWAITING_ADDRESS or HAVE_IP_ADDRESS #else if (Ethernet.linkStatus() != LinkOFF) onInitialStateInitLAN(); // Moves state to AWAITING_ADDRESS or HAVE_IP_ADDRESS #endif break; case AWAITING_ADDRESS: #if defined(WIFI_ENABLE) if (WiFi.status() == WL_CONNECTED) { infoSerial<<F("WiFi connected. IP address: ")<<WiFi.localIP()<<endl; wifiInitialized = true; lanStatus = HAVE_IP_ADDRESS; } else // if (millis()>WiFiAwaitingTime) if (isTimeOver(WiFiAwaitingTime,millis(),WIFI_TIMEOUT)) { errorSerial<<F("\nProblem with WiFi!"); return lanStatus = DO_REINIT; } #else lanStatus = HAVE_IP_ADDRESS; #endif break; case HAVE_IP_ADDRESS: if (!initializedListeners) { setupSyslog(); setupOTA(); #ifdef _artnet if (artnet) artnet->begin(); #endif initializedListeners = true; } lanStatus = LIBS_INITIALIZED; break; case LIBS_INITIALIZED: LED.set(ledRED|ledGREEN|((configLoaded)?ledBLINK:0)); if (configLocked) return LIBS_INITIALIZED; if (!configOk) lanStatus = loadConfigFromHttp(0, NULL); else lanStatus = IP_READY_CONFIG_LOADED_CONNECTING_TO_BROKER; break; case IP_READY_CONFIG_LOADED_CONNECTING_TO_BROKER: wdt_res(); LED.set(ledRED|ledGREEN|((configLoaded)?ledBLINK:0)); ip_ready_config_loaded_connecting_to_broker(); break; case RETAINING_COLLECTING: //if (millis() > timerLanCheckTime) if (isTimeOver(timerLanCheckTime,millis(),TIMEOUT_RETAIN)) { char buf[MQTT_TOPIC_LENGTH+1]; //Unsubscribe from status topics.. //strncpy_P(buf, outprefix, sizeof(buf)); setTopic(buf,sizeof(buf),T_OUT); strncat(buf, "+/+/#", sizeof(buf)); // Subscribing only on separated command/parameters topics mqttClient.unsubscribe(buf); lanStatus = OPERATION;//3; infoSerial<<F("Accepting commands...\n"); } break; case OPERATION: LED.set(ledGREEN|((configLoaded)?ledBLINK:0)); if (!mqttClient.connected()) lanStatus = IP_READY_CONFIG_LOADED_CONNECTING_TO_BROKER;//2; break; case DO_REINIT: // Pause and re-init LAN //if (mqttClient.connected()) mqttClient.disconnect(); // Hmm hungs then cable disconnected timerLanCheckTime = millis();// + 5000; lanStatus = REINIT; LED.set(ledRED|((configLoaded)?ledBLINK:0)); break; case REINIT: // Pause and re-init LAN //if (millis() > timerLanCheckTime) if (isTimeOver(timerLanCheckTime,millis(),TIMEOUT_REINIT)) { lanStatus = INITIAL_STATE; } break; case DO_RECONNECT: // Pause and re-connect MQTT if (mqttClient.connected()) mqttClient.disconnect(); timerLanCheckTime = millis();// + 5000; lanStatus = RECONNECT; break; case RECONNECT: //if (millis() > timerLanCheckTime) if (isTimeOver(timerLanCheckTime,millis(),TIMEOUT_RECONNECT)) lanStatus = IP_READY_CONFIG_LOADED_CONNECTING_TO_BROKER;//2; break; case READ_RE_CONFIG: // Restore config from FLASH, re-init LAN if (loadConfigFromEEPROM()) lanStatus = IP_READY_CONFIG_LOADED_CONNECTING_TO_BROKER;//2; else { //timerLanCheckTime = millis();// + 5000; lanStatus = DO_REINIT;//-10; } break; case DO_NOTHING:; } { #if defined(ARDUINO_ARCH_AVR) || defined(__SAM3X8E__) || defined (NRF5) wdt_dis(); if (lanStatus >= HAVE_IP_ADDRESS) { int etherStatus = Ethernet.maintain(); #ifndef Wiz5500 #define NO_LINK 5 if (Ethernet.linkStatus() == LinkOFF) etherStatus = NO_LINK; #endif switch (etherStatus) { case NO_LINK: errorSerial<<F("\nNo link")<<endl; lanStatus = DO_REINIT; break; case DHCP_CHECK_RENEW_FAIL: errorSerial<<F("Error: renewed fail"); lanStatus = DO_REINIT; break; case DHCP_CHECK_RENEW_OK: infoSerial<<F("Renewed success. IP address:"); printIPAddress(Ethernet.localIP()); break; case DHCP_CHECK_REBIND_FAIL: errorSerial<<F("Error: rebind fail"); if (mqttClient.connected()) mqttClient.disconnect(); //timerLanCheckTime = millis();// + 1000; lanStatus = DO_REINIT; break; case DHCP_CHECK_REBIND_OK: infoSerial<<F("Rebind success. IP address:"); printIPAddress(Ethernet.localIP()); break; default: break; } } wdt_en(); #endif } return lanStatus; } void onMQTTConnect(){ char topic[64] = ""; char buf[128] = ""; // High level homie topics publishing //strncpy_P(topic, outprefix, sizeof(topic)); setTopic(topic,sizeof(topic),T_DEV); strncat_P(topic, state_P, sizeof(topic)); strncpy_P(buf, ready_P, sizeof(buf)); mqttClient.publish(topic,buf,true); //strncpy_P(topic, outprefix, sizeof(topic)); setTopic(topic,sizeof(topic),T_DEV); strncat_P(topic, name_P, sizeof(topic)); strncpy_P(buf, nameval_P, sizeof(buf)); strncat_P(buf,(verval_P),sizeof(buf)); mqttClient.publish(topic,buf,true); //strncpy_P(topic, outprefix, sizeof(topic)); setTopic(topic,sizeof(topic),T_DEV); strncat_P(topic, stats_P, sizeof(topic)); strncpy_P(buf, statsval_P, sizeof(buf)); mqttClient.publish(topic,buf,true); #ifndef NO_HOMIE // strncpy_P(topic, outprefix, sizeof(topic)); setTopic(topic,sizeof(topic),T_DEV); strncat_P(topic, homie_P, sizeof(topic)); strncpy_P(buf, homiever_P, sizeof(buf)); mqttClient.publish(topic,buf,true); configLocked++; if (items) { char datatype[32]="\0"; char format [64]="\0"; aJsonObject * item = items->child; while (items && item) if (item->type == aJson_Array && aJson.getArraySize(item)>0) { /// strncat(buf,item->name,sizeof(buf)); /// strncat(buf,",",sizeof(buf)); switch ( aJson.getArrayItem(item, I_TYPE)->valueint) { case CH_THERMO: strncpy_P(datatype,float_P,sizeof(datatype)); format[0]=0; break; case CH_RELAY: case CH_GROUP: strncpy_P(datatype,enum_P,sizeof(datatype)); strncpy_P(format,enumformat_P,sizeof(format)); break; case CH_RGBW: case CH_RGB: strncpy_P(datatype,color_P,sizeof(datatype)); strncpy_P(format,hsv_P,sizeof(format)); break; case CH_DIMMER: case CH_MODBUS: case CH_PWM: case CH_VCTEMP: case CH_VC: strncpy_P(datatype,int_P,sizeof(datatype)); strncpy_P(format,intformat_P,sizeof(format)); break; } //switch //strncpy_P(topic, outprefix, sizeof(topic)); setTopic(topic,sizeof(topic),T_DEV); strncat(topic,item->name,sizeof(topic)); strncat(topic,"/",sizeof(topic)); strncat_P(topic,datatype_P,sizeof(topic)); mqttClient.publish(topic,datatype,true); if (format[0]) { //strncpy_P(topic, outprefix, sizeof(topic)); setTopic(topic,sizeof(topic),T_DEV); strncat(topic,item->name,sizeof(topic)); strncat(topic,"/",sizeof(topic)); strncat_P(topic,format_P,sizeof(topic)); mqttClient.publish(topic,format,true); } yield(); item = item->next; } //if //strncpy_P(topic, outprefix, sizeof(topic)); setTopic(topic,sizeof(topic),T_DEV); strncat_P(topic, nodes_P, sizeof(topic)); /// mqttClient.publish(topic,buf,true); } configLocked--; #endif } void ip_ready_config_loaded_connecting_to_broker() { int port = 1883; char empty = 0; short n = 0; char *user = &empty; char passwordBuf[16] = ""; char *password = passwordBuf; if (mqttClient.connected()) { lanStatus = RETAINING_COLLECTING; return; } if (!mqttArr || ((n = aJson.getArraySize(mqttArr)) < 2)) //At least device name and broker IP must be configured { lanStatus = READ_RE_CONFIG; return; } deviceName = getStringFromConfig(mqttArr, 0); infoSerial<<F("Device Name:")<<deviceName<<endl; debugSerial<<F("N:")<<n<<endl; char *servername = getStringFromConfig(mqttArr, 1); if (n >= 3) port = aJson.getArrayItem(mqttArr, 2)->valueint; if (n >= 4) user = getStringFromConfig(mqttArr, 3); if (!loadFlash(OFFSET_MQTT_PWD, passwordBuf, sizeof(passwordBuf)) && (n >= 5)) { password = getStringFromConfig(mqttArr, 4); infoSerial<<F("Using MQTT password from config")<<endl; } mqttClient.setServer(servername, port); mqttClient.setCallback(mqttCallback); char willMessage[16]; char willTopic[32]; strncpy_P(willMessage,disconnected_P,sizeof(willMessage)); // strncpy_P(willTopic, outprefix, sizeof(willTopic)); setTopic(willTopic,sizeof(willTopic),T_DEV); strncat_P(willTopic, state_P, sizeof(willTopic)); infoSerial<<F("\nAttempting MQTT connection to ")<<servername<<F(":")<<port<<F(" user:")<<user<<F(" ..."); if (!strlen(user)) { user = NULL; password= NULL; } // wdt_dis(); //potential unsafe for ethernetIdle(), but needed to avoid cyclic reboot if mosquitto out of order if (mqttClient.connect(deviceName, user, password,willTopic,MQTTQOS1,true,willMessage)) { mqttErrorRate = 0; infoSerial<<F("connected as ")<<deviceName <<endl; configOk = true; // ... Temporary subscribe to status topic char buf[MQTT_TOPIC_LENGTH+1]; setTopic(buf,sizeof(buf),T_OUT); strncat(buf, "+/+/#", sizeof(buf)); // Only on separated cmd/val topics mqttClient.subscribe(buf); //Subscribing for command topics //strncpy_P(buf, inprefix, sizeof(buf)); setTopic(buf,sizeof(buf),T_BCST); strncat(buf, "#", sizeof(buf)); Serial.println(buf); mqttClient.subscribe(buf); setTopic(buf,sizeof(buf),T_DEV); strncat(buf, "#", sizeof(buf)); Serial.println(buf); mqttClient.subscribe(buf); onMQTTConnect(); // if (_once) {DMXput(); _once=0;} lanStatus = RETAINING_COLLECTING;//4; timerLanCheckTime = millis();// + 5000; infoSerial<<F("Awaiting for retained topics"); } else { errorSerial<<F("failed, rc=")<<mqttClient.state()<<F(" try again in 5 seconds")<<endl; timerLanCheckTime = millis();// + 5000; #ifdef RESTART_LAN_ON_MQTT_ERRORS mqttErrorRate++; if(mqttErrorRate>50){ errorSerial<<F("Too many MQTT connection errors. Restart LAN")); mqttErrorRate=0; #ifdef RESET_PIN resetHard(); #endif lanStatus=DO_REINIT;// GO INITIAL_STATE; return; } #endif lanStatus = DO_RECONNECT;//12; } } void onInitialStateInitLAN() { #if defined(WIFI_ENABLE) #if defined(WIFI_MANAGER_DISABLE) if(WiFi.status() != WL_CONNECTED) { WiFi.mode(WIFI_STA); // ESP 32 - WiFi.disconnect(); instead infoSerial<<F("WIFI AP/Password:")<<QUOTE(ESP_WIFI_AP)<<F("/")<<QUOTE(ESP_WIFI_PWD)<<endl; #ifndef ARDUINO_ARCH_ESP32 wifi_set_macaddr(STATION_IF,mac); //ESP32 to check #endif WiFi.begin(QUOTE(ESP_WIFI_AP), QUOTE(ESP_WIFI_PWD)); // int wifi_connection_wait = 10000; // while (WiFi.status() != WL_CONNECTED && wifi_connection_wait > 0) { // delay(500); // wifi_connection_wait -= 500; // debugSerial<<"."; // yield(); // } // wifiInitialized = true; //??? } #endif lanStatus = AWAITING_ADDRESS; WiFiAwaitingTime = millis();// + 60000L; return; /* if (WiFi.status() == WL_CONNECTED) { infoSerial<<F("WiFi connected. IP address: ")<<WiFi.localIP()<<endl; wifiInitialized = true; lanStatus = HAVE_IP_ADDRESS;//1; //setupOTA(); } else { errorSerial<<F("\nProblem with WiFi!"); lanStatus = DO_REINIT; //timerLanCheckTime = millis() + DHCP_RETRY_INTERVAL; } */ #else // Ethernet connection IPAddress ip, dns, gw, mask; int res = 1; infoSerial<<F("Starting lan")<<endl; if (ipLoadFromFlash(OFFSET_IP, ip)) { infoSerial<<F("Loaded from flash IP:"); printIPAddress(ip); if (ipLoadFromFlash(OFFSET_DNS, dns)) { infoSerial<<F(" DNS:"); printIPAddress(dns); if (ipLoadFromFlash(OFFSET_GW, gw)) { infoSerial<<F(" GW:"); printIPAddress(gw); if (ipLoadFromFlash(OFFSET_MASK, mask)) { infoSerial<<F(" MASK:"); printIPAddress(mask); Ethernet.begin(mac, ip, dns, gw, mask); } else Ethernet.begin(mac, ip, dns, gw); } else Ethernet.begin(mac, ip, dns); } else Ethernet.begin(mac, ip); infoSerial<<endl; lanStatus = HAVE_IP_ADDRESS; } else { infoSerial<<F("\nuses DHCP\n"); wdt_dis(); #if defined(ARDUINO_ARCH_STM32) res = Ethernet.begin(mac); #else res = Ethernet.begin(mac, 12000); #endif wdt_en(); wdt_res(); if (res == 0) { errorSerial<<F("Failed to configure Ethernet using DHCP. You can set ip manually!")<<F("'ip [ip[,dns[,gw[,subnet]]]]' - set static IP\n"); lanStatus = DO_REINIT;//-10; //timerLanCheckTime = millis();// + DHCP_RETRY_INTERVAL; #ifdef RESET_PIN resetHard(); #endif } else { infoSerial<<F("Got IP address:"); printIPAddress(Ethernet.localIP()); lanStatus = HAVE_IP_ADDRESS; } } #endif } void resetHard() { #ifdef RESET_PIN infoSerial<<F("Reset Arduino with digital pin "); infoSerial<<QUOTE(RESET_PIN); delay(500); pinMode(RESET_PIN, OUTPUT); digitalWrite(RESET_PIN,LOW); delay(500); digitalWrite(RESET_PIN,HIGH); delay(500); #endif } #ifdef _owire void Changed(int i, DeviceAddress addr, float currentTemp) { char addrstr[32] = "NIL"; //char addrbuf[17]; //char valstr[16] = "NIL"; //char *owEmitString = NULL; char *owItem = NULL; SetBytes(addr, 8, addrstr); addrstr[17] = 0; if (!root) return; //printFloatValueToStr(currentTemp,valstr); debugSerial<<endl<<F("T:")<<currentTemp<<F("<")<<addrstr<<F(">")<<endl; aJsonObject *owObj = aJson.getObjectItem(owArr, addrstr); if ((currentTemp != -127.0) && (currentTemp != 85.0) && (currentTemp != 0.0)) executeCommand(owObj,-1,itemCmd(currentTemp)); /* if (owObj) { owEmitString = getStringFromConfig(owObj, "emit"); debugSerial<<owEmitString<<F(">")<<endl; if ((currentTemp != -127.0) && (currentTemp != 85.0) && (currentTemp != 0.0)) { if (owEmitString) // publish temperature to MQTT if configured { #ifdef WITH_DOMOTICZ aJsonObject *idx = aJson.getObjectItem(owObj, "idx"); if (idx && && idx->type ==aJson_String && idx->valuestring) {//DOMOTICZ json format support debugSerial << endl << idx->valuestring << F(" Domoticz valstr:"); char valstr[50]; sprintf(valstr, "{\"idx\":%s,\"svalue\":\"%.1f\"}", idx->valuestring, currentTemp); debugSerial << valstr; if (mqttClient.connected() && !ethernetIdleCount) mqttClient.publish(owEmitString, valstr); return; } #endif //strcpy_P(addrstr, outprefix); setTopic(addrstr,sizeof(addrstr),T_OUT); strncat(addrstr, owEmitString, sizeof(addrstr)); if (mqttClient.connected() && !ethernetIdleCount) mqttClient.publish(addrstr, valstr); } // And translate temp to internal items owItem = getStringFromConfig(owObj, "item"); if (owItem) thermoSetCurTemp(owItem, currentTemp); ///TODO: Refactore using Items interface } // if valid temperature } // if Address in config else debugSerial<<addrstr<<F(">")<<endl; // No item found */ } #endif //_owire void cmdFunctionHelp(int arg_cnt, char **args) { printFirmwareVersionAndBuildOptions(); printCurentLanConfig(); // printFreeRam(); infoSerial<<F("\nUse these commands: 'help' - this text\n" "'mac de:ad:be:ef:fe:00' set and store MAC-address in EEPROM\n" "'ip [ip[,dns[,gw[,subnet]]]]' - set static IP\n" "'save' - save config in NVRAM\n" "'get' [config addr]' - get config from pre-configured URL and store addr\n" "'load' - load config from NVRAM\n" "'pwd' - define MQTT password\n" "'kill' - test watchdog\n" "'clear' - clear EEPROM\n" "'reboot' - reboot controller"); } void printCurentLanConfig() { infoSerial << F("Current LAN config(ip,dns,gw,subnet):"); printIPAddress(Ethernet.localIP()); // printIPAddress(Ethernet.dnsServerIP()); printIPAddress(Ethernet.gatewayIP()); printIPAddress(Ethernet.subnetMask()); } void cmdFunctionKill(int arg_cnt, char **args) { for (byte i = 1; i < 20; i++) { delay(1000); infoSerial<<i; }; } void cmdFunctionReboot(int arg_cnt, char **args) { infoSerial<<F("Soft rebooting..."); softRebootFunc(); } void applyConfig() { if (!root) return; configLocked++; items = aJson.getObjectItem(root, "items"); topics = aJson.getObjectItem(root, "topics"); inputs = aJson.getObjectItem(root, "in"); mqttArr = aJson.getObjectItem(root, "mqtt"); setupSyslog(); #ifdef _dmxin int itemsCount; dmxArr = aJson.getObjectItem(root, "dmxin"); if (dmxArr && (itemsCount = aJson.getArraySize(dmxArr))) { DMXinSetup(itemsCount * 4); infoSerial<<F("DMX in started. Channels:")<<itemsCount * 4<<endl; } #endif #ifdef _dmxout int maxChannels; short numParams; aJsonObject *dmxoutArr = aJson.getObjectItem(root, "dmx"); if (dmxoutArr && (numParams=aJson.getArraySize(dmxoutArr)) >=1 ) { DMXoutSetup(maxChannels = aJson.getArrayItem(dmxoutArr, numParams-1)->valueint); infoSerial<<F("DMX out started. Channels: ")<<maxChannels<<endl; debugSerial<<F("Free:")<<freeRam()<<endl; } #endif #ifdef _modbus modbusObj = aJson.getObjectItem(root, "modbus"); #endif #ifdef _owire owArr = aJson.getObjectItem(root, "ow"); if (owArr && !owReady) { aJsonObject *item = owArr->child; owReady = owSetup(&Changed); if (owReady) infoSerial<<F("One wire Ready\n"); t_count = 0; while (item && owReady) { if ((item->type == aJson_Object)) { DeviceAddress addr; //infoSerial<<F("Add:")),infoSerial<<item->name); SetAddr(item->name, addr); owAdd(addr); } yield(); item = item->next; } } #endif // Digital output related Items initialization pollingItem=NULL; if (items) { aJsonObject * item = items->child; while (items && item) if (item->type == aJson_Array && aJson.getArraySize(item)>1) { Item it(item); if (it.isValid() && !it.Setup()) { //Legacy Setup short inverse = 0; int pin=it.getArg(); if (pin<0) {pin=-pin; inverse = 1;} int cmd = it.getCmd(); switch (it.itemType) { case CH_THERMO: if (cmd<1) it.setCmd(CMD_OFF); pinMode(pin, OUTPUT); digitalWrite(pin, false); //Initially, all thermostates are LOW (OFF for electho heaters, open for water NO) debugSerial<<F("Thermo:")<<pin<<F("=LOW")<<F(";"); break; case CH_RELAY: { int k; pinMode(pin, OUTPUT); if (inverse) digitalWrite(pin, k = ((cmd == CMD_ON) ? LOW : HIGH)); else digitalWrite(pin, k = ((cmd == CMD_ON) ? HIGH : LOW)); debugSerial<<F("Pin:")<<pin<<F("=")<<k<<F(";"); } break; } //switch } //isValid yield(); item = item->next; } //if pollingItem = items->child; } debugSerial<<endl; inputSetup(); printConfigSummary(); configLoaded=true; configLocked--; } void printConfigSummary() { infoSerial<<F("\nConfigured:")<<F("\nitems "); printBool(items); infoSerial<<F("\ninputs "); printBool(inputs); #ifndef MODBUS_DISABLE infoSerial<<F("\nmodbus v1 (+)"); // printBool(modbusObj); #endif #ifndef MBUS_DISABLE infoSerial<<F("\nmodbus v2"); printBool(modbusObj); #endif infoSerial<<F("\nmqtt "); printBool(mqttArr); #ifdef _owire infoSerial<<F("\n1-wire "); printBool(owArr); #endif /* #ifdef SYSLOG_ENABLE infoSerial<<F("\nudp syslog "); printBool(udpSyslogArr); #endif */ infoSerial << endl; infoSerial<<F("RAM=")<<freeRam()<<endl; } void cmdFunctionLoad(int arg_cnt, char **args) { loadConfigFromEEPROM(); } int loadConfigFromEEPROM() { char ch; infoSerial<<F("Loading Config from EEPROM")<<endl; ch = EEPROM.read(EEPROM_offsetJSON); if (ch == '{') { aJsonEEPROMStream as = aJsonEEPROMStream(EEPROM_offsetJSON); cleanConf(); root = aJson.parse(&as); if (!root) { errorSerial<<F("load failed")<<endl; return 0; } infoSerial<<F("Loaded")<<endl; applyConfig(); ethClient.stop(); //Refresh MQTT connect to get retained info return 1; } else { infoSerial<<F("No stored config")<<endl; return 0; } return 0; } void cmdFunctionReq(int arg_cnt, char **args) { mqttConfigRequest(arg_cnt, args); } int mqttConfigRequest(int arg_cnt, char **args) { char buf[25] = "/"; infoSerial<<F("\nrequest MQTT Config"); SetBytes((uint8_t *) mac, 6, buf + 1); buf[13] = 0; strncat(buf, "/resp/#", 25); debugSerial<<buf; mqttClient.subscribe(buf); buf[13] = 0; strncat(buf, "/req/conf", 25); debugSerial<<buf; mqttClient.publish(buf, "1"); return 1; } int mqttConfigResp(char *as) { infoSerial<<F("got MQTT Config"); root = aJson.parse(as); if (!root) { errorSerial<<F("\nload failed\n"); return 0; } infoSerial<<F("\nLoaded"); applyConfig(); return 1; } #if defined(__SAM3X8E__) #define saveBufLen 16000 void cmdFunctionSave(int arg_cnt, char **args) { char* outBuf = (char*) malloc(saveBufLen); /* XXX: Dynamic size. */ if (outBuf == NULL) { return; } infoSerial<<F("Saving config to EEPROM.."); aJsonStringStream stringStream(NULL, outBuf, saveBufLen); aJson.print(root, &stringStream); int len = strlen(outBuf); outBuf[len++]= EOF; EEPROM.write(EEPROM_offsetJSON,(byte*) outBuf,len); free (outBuf); infoSerial<<F("Saved to EEPROM"); } #else void cmdFunctionSave(int arg_cnt, char **args) { aJsonEEPROMStream jsonEEPROMStream = aJsonEEPROMStream(EEPROM_offsetJSON); infoSerial<<F("Saving config to EEPROM.."); aJson.print(root, &jsonEEPROMStream); jsonEEPROMStream.putEOF(); infoSerial<<F("Saved to EEPROM"); } #endif void cmdFunctionIp(int arg_cnt, char **args) { IPAddress ip0(0, 0, 0, 0); IPAddress ip; /* #if defined(ARDUINO_ARCH_AVR) || defined(__SAM3X8E__) || defined(NRF5) DNSClient dns; #define _inet_aton(cp, addr) dns._inet_aton(cp, addr) #else #define _inet_aton(cp, addr) _inet_aton(cp, addr) #endif */ // switch (arg_cnt) { // case 5: if (arg_cnt>4 && _inet_aton(args[4], ip)) saveFlash(OFFSET_MASK, ip); else saveFlash(OFFSET_MASK, ip0); // case 4: if (arg_cnt>3 && _inet_aton(args[3], ip)) saveFlash(OFFSET_GW, ip); else saveFlash(OFFSET_GW, ip0); // case 3: if (arg_cnt>2 && _inet_aton(args[2], ip)) saveFlash(OFFSET_DNS, ip); else saveFlash(OFFSET_DNS, ip0); // case 2: if (arg_cnt>1 && _inet_aton(args[1], ip)) saveFlash(OFFSET_IP, ip); else saveFlash(OFFSET_IP, ip0); // break; // case 1: //dynamic IP if (arg_cnt==1) { saveFlash(OFFSET_IP,ip0); infoSerial<<F("Set dynamic IP\n"); } /* IPAddress current_ip = Ethernet.localIP(); IPAddress current_mask = Ethernet.subnetMask(); IPAddress current_gw = Ethernet.gatewayIP(); IPAddress current_dns = Ethernet.dnsServerIP(); saveFlash(OFFSET_IP, current_ip); saveFlash(OFFSET_MASK, current_mask); saveFlash(OFFSET_GW, current_gw); saveFlash(OFFSET_DNS, current_dns); debugSerial<<F("Saved current config(ip,dns,gw,subnet):"); printIPAddress(current_ip); printIPAddress(current_dns); printIPAddress(current_gw); printIPAddress(current_mask); */ //} infoSerial<<F("Saved\n"); } void cmdFunctionClearEEPROM(int arg_cnt, char **args){ for (int i = OFFSET_MAC; i < OFFSET_MAC+EEPROM_FIX_PART_LEN+1; i++) //Fi[ part +{] EEPROM.write(i, 0); for (int i = 0; i < EEPROM_SIGNATURE_LENGTH; i++) EEPROM.write(i+OFFSET_SIGNATURE,EEPROM_signature[i]); infoSerial<<F("EEPROM cleared\n"); } void cmdFunctionPwd(int arg_cnt, char **args) { char empty[]=""; if (arg_cnt) saveFlash(OFFSET_MQTT_PWD,args[1]); else saveFlash(OFFSET_MQTT_PWD,empty); infoSerial<<F("Password updated\n"); } void cmdFunctionSetMac(int arg_cnt, char **args) { char dummy; if (sscanf(args[1], "%x:%x:%x:%x:%x:%x%c", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5], &dummy) < 6) { errorSerial<<F("could not parse: ")<<args[1]; return; } printMACAddress(); for (short i = 0; i < 6; i++) { EEPROM.write(i, mac[i]); } infoSerial<<F("Updated\n"); } void cmdFunctionGet(int arg_cnt, char **args) { lanStatus= loadConfigFromHttp(arg_cnt, args); ethClient.stop(); //Refresh MQTT connect to get retained info //restoreState(); } void printBool(bool arg) { (arg) ? infoSerial<<F("+") : infoSerial<<F("-"); } void saveFlash(short n, char *str) { short len=strlen(str); if (len>MAXFLASHSTR-1) len=MAXFLASHSTR-1; for(int i=0;i<len;i++) EEPROM.write(n+i,str[i]); EEPROM.write(n+len,0); #if defined(ARDUINO_ARCH_ESP8266) // write the data to EEPROM short res = EEPROM.commitReset(); Serial.println((res) ? "EEPROM Commit OK" : "Commit failed"); #endif } int loadFlash(short n, char *str, short l) { short i; uint8_t ch = EEPROM.read(n); if (!ch || (ch == 0xff)) return 0; for (i=0;i<l-1 && (str[i] = EEPROM.read(n++));i++); str[i]=0; return 1; } void saveFlash(short n, IPAddress& ip) { for(int i=0;i<4;i++) EEPROM.write(n++,ip[i]); #if defined(ARDUINO_ARCH_ESP8266) // write the data to EEPROM short res = EEPROM.commitReset(); Serial.println((res) ? "EEPROM Commit OK" : "Commit failed"); #endif } int ipLoadFromFlash(short n, IPAddress &ip) { for (int i = 0; i < 4; i++) ip[i] = EEPROM.read(n++); return (ip[0] && ((ip[0] != 0xff) || (ip[1] != 0xff) || (ip[2] != 0xff) || (ip[3] != 0xff))); } lan_status loadConfigFromHttp(int arg_cnt, char **args) { int responseStatusCode = 0; char URI[64]; char configServer[32]=""; if (arg_cnt > 1) { strncpy(configServer, args[1], sizeof(configServer) - 1); saveFlash(OFFSET_CONFIGSERVER, configServer); infoSerial<<configServer<<F(" Saved")<<endl; } else if (!loadFlash(OFFSET_CONFIGSERVER, configServer)) { strncpy_P(configServer,configserver,sizeof(configServer)); infoSerial<<F(" Default config server used: ")<<configServer<<endl; } #ifndef DEVICE_NAME snprintf(URI, sizeof(URI), "/cnf/%02x-%02x-%02x-%02x-%02x-%02x.config.json", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); #else #ifndef FLASH_64KB snprintf(URI, sizeof(URI), "/cnf/%s_config.json",QUOTE(DEVICE_NAME)); #else strncpy(URI, "/cnf/", sizeof(URI)); strncat(URI, QUOTE(DEVICE_NAME), sizeof(URI)); strncat(URI, "_config.json", sizeof(URI)); #endif #endif infoSerial<<F("Config URI: http://")<<configServer<<URI<<endl; #if defined(ARDUINO_ARCH_AVR) FILE *configStream; //wdt_dis(); //if (freeRam()<512) cleanConf(); HTTPClient hclient(configServer, 80); // FILE is the return STREAM type of the HTTPClient configStream = hclient.getURI(URI); responseStatusCode = hclient.getLastReturnCode(); //wdt_en(); if (configStream != NULL) { if (responseStatusCode == 200) { infoSerial<<F("got Config\n"); char c; aJsonFileStream as = aJsonFileStream(configStream); noInterrupts(); cleanConf(); root = aJson.parse(&as); interrupts(); hclient.closeStream(configStream); // this is very important -- be sure to close the STREAM if (!root) { errorSerial<<F("Config parsing failed\n"); // timerLanCheckTime = millis();// + 15000; return READ_RE_CONFIG;//-11; } else { infoSerial<<F("Applying.\n"); applyConfig(); infoSerial<<F("Done.\n"); } } else { errorSerial<<F("ERROR: Server returned "); errorSerial<<responseStatusCode<<endl; // timerLanCheckTime = millis();// + 5000; return READ_RE_CONFIG;//-11; } } else { debugSerial<<F("failed to connect\n"); // debugSerial<<F(" try again in 5 seconds\n"); // timerLanCheckTime = millis();// + 5000; return READ_RE_CONFIG;//-11; } #endif #if defined(__SAM3X8E__) || defined(ARDUINO_ARCH_STM32) || defined (NRF5) //|| defined(ARDUINO_ARCH_ESP32) //|| defined(ARDUINO_ARCH_ESP8266) #if defined(WIFI_ENABLE) WiFiClient configEthClient; #else EthernetClient configEthClient; #endif String response; HttpClient htclient = HttpClient(configEthClient, configServer, 80); //htclient.stop(); //_socket =MAX htclient.setHttpResponseTimeout(4000); wdt_res(); //debugSerial<<"making GET request");get htclient.beginRequest(); responseStatusCode = htclient.get(URI); htclient.endRequest(); if (responseStatusCode == HTTP_SUCCESS) { // read the status code and body of the response responseStatusCode = htclient.responseStatusCode(); response = htclient.responseBody(); htclient.stop(); wdt_res(); infoSerial<<F("HTTP Status code: ")<<responseStatusCode<<endl; //delay(1000); if (responseStatusCode == 200) { debugSerial<<F("GET Response: ")<<response<<endl; debugSerial<<F("Free:")<<freeRam()<<endl; cleanConf(); debugSerial<<F("Configuration cleaned")<<endl; debugSerial<<F("Free:")<<freeRam()<<endl; root = aJson.parse((char *) response.c_str()); if (!root) { errorSerial<<F("Config parsing failed\n"); return READ_RE_CONFIG;//-11; //Load from NVRAM } else { debugSerial<<F("Parsed. Free:")<<freeRam()<<endl; //debugSerial<<response; applyConfig(); infoSerial<<F("Done.\n"); } } else { errorSerial<<F("Config retrieving failed\n"); return READ_RE_CONFIG;//-11; //Load from NVRAM } } else { errorSerial<<F("Connect failed\n"); return READ_RE_CONFIG;//-11; //Load from NVRAM } #endif #if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) //|| defined (NRF5) HTTPClient httpClient; #if defined(WIFI_ENABLE) WiFiClient configEthClient; #else EthernetClient configEthClient; #endif String fullURI = "http://"; fullURI+=configServer; fullURI+=URI; #if defined(ARDUINO_ARCH_ESP8266) httpClient.begin(configEthClient,fullURI); #else httpClient.begin(fullURI); #endif int httpResponseCode = httpClient.GET(); if (httpResponseCode > 0) { infoSerial.printf("[HTTP] GET... code: %d\n", httpResponseCode); if (httpResponseCode == HTTP_CODE_OK) { String response = httpClient.getString(); debugSerial<<response; cleanConf(); root = aJson.parse((char *) response.c_str()); if (!root) { errorSerial<<F("Config parsing failed\n"); return READ_RE_CONFIG; } else { infoSerial<<F("Config OK, Applying\n"); applyConfig(); infoSerial<<F("Done.\n"); } } else { errorSerial<<F("Config retrieving failed\n"); return READ_RE_CONFIG;//-11; //Load from NVRAM } } else { errorSerial.printf("[HTTP] GET... failed, error: %s\n", httpClient.errorToString(httpResponseCode).c_str()); httpClient.end(); return READ_RE_CONFIG; } httpClient.end(); #endif return IP_READY_CONFIG_LOADED_CONNECTING_TO_BROKER; } void preTransmission() { #ifdef CONTROLLINO // set DE and RE on HIGH PORTJ |= B01100000; #else digitalWrite(TXEnablePin, 1); #endif } void postTransmission() { #ifdef CONTROLLINO // set DE and RE on LOW PORTJ &= B10011111; #else digitalWrite(TXEnablePin, 0); #endif } void setup_main() { #if defined(__SAM3X8E__) memset(&UniqueID,0,sizeof(UniqueID)); #endif #if defined(M5STACK) // Initialize the M5Stack object M5.begin(); #endif setupCmdArduino(); printFirmwareVersionAndBuildOptions(); //Checkin EEPROM integrity (signature) for (int i=0;i<EEPROM_SIGNATURE_LENGTH;i++) if (EEPROM.read(i+OFFSET_SIGNATURE)!=EEPROM_signature[i]) { cmdFunctionClearEEPROM(0,NULL); break; } // scan_i2c_bus(); #ifdef SD_CARD_INSERTED sd_card_w5100_setup(); #endif setupMacAddress(); #if defined(ARDUINO_ARCH_ESP8266) EEPROM.begin(ESP_EEPROM_SIZE); #endif #ifdef _modbus #ifdef CONTROLLINO //set PORTJ pin 5,6 direction (RE,DE) DDRJ |= B01100000; //set RE,DE on LOW PORTJ &= B10011111; #else pinMode(TXEnablePin, OUTPUT); #endif modbusSerial.begin(MODBUS_SERIAL_BAUD); node.idle(&modbusIdle); node.preTransmission(preTransmission); node.postTransmission(postTransmission); #endif delay(20); //owReady = 0; #ifdef _owire setupOwIdle(&owIdle); #endif mqttClient.setCallback(mqttCallback); #ifdef _artnet ArtnetSetup(); #endif #if defined(WIFI_ENABLE) and not defined(WIFI_MANAGER_DISABLE) // WiFiManager wifiManager; wifiManager.setTimeout(180); #if defined(ESP_WIFI_AP) and defined(ESP_WIFI_PWD) wifiInitialized = wifiManager.autoConnect(QUOTE(ESP_WIFI_AP), QUOTE(ESP_WIFI_PWD)); #else wifiInitialized = wifiManager.autoConnect(); #endif #endif delay(LAN_INIT_DELAY);//for LAN-shield initializing //TODO: checkForRemoteSketchUpdate(); #if defined(W5500_CS_PIN) && ! defined(WIFI_ENABLE) Ethernet.init(W5500_CS_PIN); infoSerial<<F("Use W5500 pin: "); infoSerial<<QUOTE(W5500_CS_PIN)<<endl; #endif loadConfigFromEEPROM(); } void printFirmwareVersionAndBuildOptions() { infoSerial<<F("\nLazyhome.ru LightHub controller ")<<F(QUOTE(PIO_SRC_REV))<<F(" C++ version:")<<F(QUOTE(__cplusplus))<<endl; #ifdef CONTROLLINO infoSerial<<F("\n(+)CONTROLLINO"); #endif #ifndef WATCH_DOG_TICKER_DISABLE infoSerial<<F("\n(+)WATCHDOG"); #else infoSerial<<F("\n(-)WATCHDOG"); #endif infoSerial<<F("\nConfig server:")<<F(CONFIG_SERVER)<<F("\nFirmware MAC Address ")<<F(QUOTE(CUSTOM_FIRMWARE_MAC)); #ifdef DISABLE_FREERAM_PRINT infoSerial<<F("\n(-)FreeRam printing"); #else infoSerial<<F("\n(+)FreeRam printing"); #endif #ifdef USE_1W_PIN infoSerial<<F("\n(-)DS2482-100 USE_1W_PIN=")<<QUOTE(USE_1W_PIN); #else infoSerial<<F("\n(+)DS2482-100"); #endif #ifdef WIFI_ENABLE infoSerial<<F("\n(+)WiFi"); #elif Wiz5500 infoSerial<<F("\n(+)WizNet5500"); #elif Wiz5100 infoSerial<<F("\n(+)Wiznet5100"); #else infoSerial<<F("\n(+)Wiznet5x00"); #endif #ifndef DMX_DISABLE infoSerial<<F("\n(+)DMX"); #ifdef FASTLED infoSerial<<F("\n(+)FASTLED"); #else infoSerial<<F("\n(+)ADAFRUIT LED"); #endif #else infoSerial<<F("\n(-)DMX"); #endif #ifdef _modbus infoSerial<<F("\n(+)MODBUS"); #else infoSerial<<F("\n(-)MODBUS"); #endif #ifndef OWIRE_DISABLE infoSerial<<F("\n(+)OWIRE"); #else infoSerial<<F("\n(-)OWIRE"); #endif #ifndef DHT_DISABLE infoSerial<<F("\n(+)DHT"); #else infoSerial<<F("\n(-)DHT"); #endif #ifndef COUNTER_DISABLE infoSerial<<F("\n(+)COUNTER"); #else infoSerial<<F("\n(-)COUNTER"); #endif #ifdef SD_CARD_INSERTED infoSerial<<F("\n(+)SDCARD"); #endif #ifdef RESET_PIN infoSerial<<F("\n(+)HARDRESET on pin=")<<QUOTE(RESET_PIN); #else infoSerial<<F("\n(-)HARDRESET, using soft"); #endif #ifdef RESTART_LAN_ON_MQTT_ERRORS infoSerial<<F("\n(+)RESTART_LAN_ON_MQTT_ERRORS"); #else infoSerial<<F("\n(-)RESTART_LAN_ON_MQTT_ERRORS"); #endif #ifndef CSSHDC_DISABLE infoSerial<<F("\n(+)CCS811 & HDC1080"); #else infoSerial<<F("\n(-)CCS811 & HDC1080"); #endif #ifndef AC_DISABLE infoSerial<<F("\n(+)AC HAIER"); #else infoSerial<<F("\n(-)AC HAIER"); #endif #ifndef MOTOR_DISABLE infoSerial<<F("\n(+)MOTOR CTR"); #else infoSerial<<F("\n(-)MOTOR CTR"); #endif #ifndef SPILED_DISABLE infoSerial<<F("\n(+)SPI LED"); #else infoSerial<<F("\n(-)SPI LED"); #endif #ifdef OTA infoSerial<<F("\n(+)OTA"); #else infoSerial<<F("\n(-)OTA"); #endif #ifdef ARTNET_ENABLE infoSerial<<F("\n(+)ARTNET"); #else infoSerial<<F("\n(-)ARTNET"); #endif #ifdef MCP23017 infoSerial<<F("\n(+)MCP23017"); #else infoSerial<<F("\n(-)MCP23017"); #endif #ifndef PID_DISABLE infoSerial<<F("\n(+)PID"); #else infoSerial<<F("\n(-)PID"); #endif #ifdef SYSLOG_ENABLE //udpSyslogClient.begin(SYSLOG_LOCAL_SOCKET); infoSerial<<F("\n(+)SYSLOG"); #else infoSerial<<F("\n(-)SYSLOG"); #endif infoSerial<<endl; // WDT_Disable( WDT ) ; #if defined(__SAM3X8E__) debugSerial<<F("Reading 128 bits unique identifier")<<endl ; ReadUniqueID( UniqueID.UID_Long ) ; infoSerial<< F ("ID: "); for (byte b = 0 ; b < 4 ; b++) infoSerial<< _HEX((unsigned int) UniqueID.UID_Long [b]); infoSerial<< endl; #endif } void publishStat(){ long fr = freeRam(); char topic[64]; char intbuf[16]; uint32_t ut = millis()/1000UL; if (!mqttClient.connected() || ethernetIdleCount) return; setTopic(topic,sizeof(topic),T_DEV); strncat_P(topic, stats_P, sizeof(topic)); strncat(topic, "/", sizeof(topic)); strncat_P(topic, freeheap_P, sizeof(topic)); printUlongValueToStr(intbuf, fr); mqttClient.publish(topic,intbuf,true); setTopic(topic,sizeof(topic),T_DEV); strncat_P(topic, stats_P, sizeof(topic)); strncat(topic, "/", sizeof(topic)); strncat_P(topic, uptime_P, sizeof(topic)); printUlongValueToStr(intbuf, ut); mqttClient.publish(topic,intbuf,true); } void setupMacAddress() { //Check MAC, stored in NVRAM bool isMacValid = false; for (short i = 0; i < 6; i++) { mac[i] = EEPROM.read(i); if (mac[i] != 0 && mac[i] != 0xff) isMacValid = true; } if (!isMacValid) { infoSerial<<F("No MAC configured: set firmware's MAC\n"); #if defined (CUSTOM_FIRMWARE_MAC) //Forced MAC from compiler's directive const char *macStr = QUOTE(CUSTOM_FIRMWARE_MAC);//colon(:) separated from build options parseBytes(macStr, ':', mac, 6, 16); mac[0]&=0xFE; mac[0]|=2; #elif defined(WIFI_ENABLE) //Using original MPU MAC WiFi.begin(); WiFi.macAddress(mac); #elif defined(__SAM3X8E__) //Lets make MAC from MPU serial# mac[0]=0xDE; for (byte b = 0 ; b < 5 ; b++) mac[b+1]=UniqueID.UID_Byte [b*3] + UniqueID.UID_Byte [b*3+1] + UniqueID.UID_Byte [b*3+2]; #elif defined DEFAULT_FIRMWARE_MAC uint8_t defaultMac[6] = DEFAULT_FIRMWARE_MAC;//comma(,) separated hex-array, hard-coded memcpy(mac,defaultMac,6); #endif } printMACAddress(); } void setupCmdArduino() { cmdInit(uint32_t(SERIAL_BAUD)); debugSerial<<(F(">>>")); cmdAdd("help", cmdFunctionHelp); cmdAdd("save", cmdFunctionSave); cmdAdd("load", cmdFunctionLoad); cmdAdd("get", cmdFunctionGet); #ifndef FLASH_64KB cmdAdd("mac", cmdFunctionSetMac); #endif cmdAdd("kill", cmdFunctionKill); cmdAdd("req", cmdFunctionReq); cmdAdd("ip", cmdFunctionIp); cmdAdd("pwd", cmdFunctionPwd); cmdAdd("clear",cmdFunctionClearEEPROM); cmdAdd("reboot",cmdFunctionReboot); } void loop_main() { LED.poll(); #if defined(M5STACK) // Initialize the M5Stack object yield(); M5.update(); #endif wdt_res(); yield(); cmdPoll(); if (lanLoop() > HAVE_IP_ADDRESS) { mqttClient.loop(); #if defined(OTA) yield(); ArduinoOTA.poll(); #endif #ifdef _artnet yield(); if (artnet) artnet->read(); ///hung #endif } #ifdef _owire yield(); if (owReady && owArr) owLoop(); #endif #ifdef _dmxin yield(); DMXCheck(); #endif if (items) { if (isNotRetainingStatus()) pollingLoop(); yield(); thermoLoop(); } yield(); inputLoop(); #if defined (_espdmx) yield(); dmxout.update(); #endif } void owIdle(void) { #ifdef _artnet if (artnet && (lanStatus>=HAVE_IP_ADDRESS)) artnet->read(); #endif wdt_res(); return; #ifdef _dmxin yield(); DMXCheck(); #endif #if defined (_espdmx) yield(); dmxout.update(); #endif } void ethernetIdle(void){ ethernetIdleCount++; wdt_res(); yield(); inputLoop(); ethernetIdleCount--; }; void modbusIdle(void) { LED.poll(); yield(); cmdPoll(); wdt_res(); if (lanLoop() > HAVE_IP_ADDRESS) { yield(); mqttClient.loop(); #ifdef _artnet if (artnet) artnet->read(); #endif yield(); inputLoop(); } #ifdef _dmxin DMXCheck(); #endif #if defined (_espdmx) dmxout.update(); #endif } void inputLoop(void) { if (!inputs) return; configLocked++; //if (millis() > timerInputCheck) if (isTimeOver(timerInputCheck,millis(),INTERVAL_CHECK_INPUT)) { aJsonObject *input = inputs->child; while (input) { if (input->type == aJson_Object) { // Check for nested inputs aJsonObject * inputArray = aJson.getObjectItem(input, "act"); if (inputArray && (inputArray->type == aJson_Array)) { aJsonObject *inputObj = inputArray->child; while(inputObj) { Input in(inputObj,input); in.Poll(CHECK_INPUT); yield(); inputObj = inputObj->next; } } else { Input in(input); in.Poll(CHECK_INPUT); } } yield(); input = input->next; } timerInputCheck = millis();// + INTERVAL_CHECK_INPUT; inCache.invalidateInputCache(); } //if (millis() > timerSensorCheck) if (isTimeOver(timerSensorCheck,millis(),INTERVAL_CHECK_SENSOR)) { aJsonObject *input = inputs->child; while (input) { if ((input->type == aJson_Object)) { Input in(input); in.Poll(CHECK_SENSOR); } yield(); input = input->next; } timerSensorCheck = millis();// + INTERVAL_CHECK_SENSOR; } configLocked--; } void inputSetup(void) { if (!inputs) return; configLocked++; aJsonObject *input = inputs->child; while (input) { if ((input->type == aJson_Object)) { Input in(input); in.setup(); } yield(); input = input->next; } configLocked--; } void pollingLoop(void) { // FAST POLLINT - as often AS possible every item configLocked++; if (items) { aJsonObject * item = items->child; while (items && item) if (item->type == aJson_Array && aJson.getArraySize(item)>1) { Item it(item); if (it.isValid()) { it.Poll(POLLING_FAST); } //isValid yield(); item = item->next; } //if } configLocked--; // SLOW POLLING boolean done = false; if (lanStatus == RETAINING_COLLECTING) return; //if (millis() > timerPollingCheck) if (isTimeOver(timerPollingCheck,millis(),INTERVAL_SLOW_POLLING)) { while (pollingItem && !done) { if (pollingItem->type == aJson_Array) { Item it(pollingItem); uint32_t ret = it.Poll(POLLING_SLOW); if (ret) { timerPollingCheck = millis();// + ret; //INTERVAL_CHECK_MODBUS; done = true; } }//if if (!pollingItem) return; //Config was re-readed yield(); pollingItem = pollingItem->next; if (!pollingItem) { pollingItem = items->child; return; } //start from 1-st element } //while }//if } ////// Legacy Thermostat code below - to be moved in module ///// void thermoRelay(int pin, bool on) { int thermoPin = abs(pin); pinMode(thermoPin, OUTPUT); if (on) { digitalWrite(thermoPin, (pin<0)?LOW:HIGH); debugSerial<<F(" ON")<<endl; } else { digitalWrite(thermoPin, (pin<0)?HIGH:LOW); debugSerial<<F(" OFF")<<endl; } } void thermoLoop(void) { if (!isTimeOver(timerThermostatCheck,millis(),THERMOSTAT_CHECK_PERIOD)) return; if (!items) return; bool thermostatCheckPrinted = false; configLocked++; for (aJsonObject *thermoItem = items->child; thermoItem; thermoItem = thermoItem->next) { if ((thermoItem->type == aJson_Array) && (aJson.getArrayItem(thermoItem, I_TYPE)->valueint == CH_THERMO)) { Item thermostat(thermoItem); //Init Item if (!thermostat.isValid()) continue; itemCmd thermostatCmd(&thermostat); // Got itemCmd thermostatStore tStore; tStore.asint=thermostat.getExt(); int thermoPin = thermostat.getArg(0); float thermoSetting = thermostatCmd.getFloat(); int thermoStateCommand = thermostat.getCmd(); float curTemp = (float) tStore.tempX100/100.; bool active = thermostat.isActive(); debugSerial << F(" Set:") << thermoSetting << F(" Cur:") << curTemp << F(" cmd:") << thermoStateCommand; if (tStore.timestamp16) //Valid temperature { if (isTimeOver(tStore.timestamp16,millisNZ(8) & 0xFFFF,PERIOD_THERMOSTAT_FAILED,0xFFFF)) { errorSerial<<thermoItem->name<<F(" Alarm Expired\n"); mqttClient.publish("/alarm/snsr", thermoItem->name); tStore.timestamp16=0; //Stop termostat thermostat.setExt(tStore.asint); thermoRelay(thermoPin,false); } else { // Not expired yet if (curTemp > THERMO_OVERHEAT_CELSIUS) mqttClient.publish("/alarm/ovrht", thermoItem->name); if (!active) thermoRelay(thermoPin,false);//OFF else if (curTemp < thermoSetting - THERMO_GIST_CELSIUS) thermoRelay(thermoPin,true);//ON else if (curTemp >= thermoSetting) thermoRelay(thermoPin,false);//OFF else debugSerial<<F(" -target zone-")<<endl; // Nothing to do } } else debugSerial<<F(" Expired\n"); thermostatCheckPrinted = true; } //item is termostat } //for configLocked--; timerThermostatCheck = millis();// + THERMOSTAT_CHECK_PERIOD; publishStat(); #ifndef DISABLE_FREERAM_PRINT (thermostatCheckPrinted) ? debugSerial<<F("\nRAM=")<<freeRam()<<" " : debugSerial<<F(" ")<<freeRam()<<F(" "); #endif }
28.160055
146
0.580147
anklimov
8947c0699f9f8d747a3eea649857d17fb32f2382
284
hpp
C++
include/Pomdog/Math/Vector3.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
include/Pomdog/Math/Vector3.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
include/Pomdog/Math/Vector3.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license. #pragma once #include "Pomdog/Math/detail/FloatingPointVector3.hpp" namespace Pomdog { ///@brief vector in three-dimensional space. using Vector3 = Detail::FloatingPointVector3<float>; } // namespace Pomdog
21.846154
71
0.767606
ValtoForks
894e2e35083a65042d02fb0e8fae5f3caef5d4e8
1,749
cpp
C++
code/client/src/core/hooks/camera.cpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
16
2021-10-08T17:47:04.000Z
2022-03-28T13:26:37.000Z
code/client/src/core/hooks/camera.cpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
4
2022-01-19T08:11:57.000Z
2022-01-29T19:02:24.000Z
code/client/src/core/hooks/camera.cpp
mufty/MafiaMP
2dc0e3362c505079e26e598bd4a7f4b5de7400bc
[ "OpenSSL" ]
4
2021-10-09T11:15:08.000Z
2022-01-27T22:42:26.000Z
#include <MinHook.h> #include <utils/hooking/hook_function.h> #include <utils/hooking/hooking.h> #include <logging/logger.h> typedef int64_t(__fastcall *C_Camera__ModeChangeImmediate_t)(void *_this, int, void *, bool, bool, bool); C_Camera__ModeChangeImmediate_t C_Camera__ModeChangeImmediate_original = nullptr; typedef int64_t(__fastcall *C_Camera__SendCommand_t)(void *, unsigned int, void *, void *); C_Camera__SendCommand_t C_Camera__SendCommand_original = nullptr; int64_t C_Camera__ModeChangeImmediate(void* _this, int mode, void* data, bool unk1, bool unk2, bool unk3) { Framework::Logging::GetLogger("Hooks")->debug("[Camera::ModeChangeImmediate]: id {}, ptr {:p}, {} {} {}", mode, fmt::ptr(data), unk1, unk2, unk3); return C_Camera__ModeChangeImmediate_original(_this, mode, data, unk1, unk2, unk3); } int64_t C_Camera__SendCommand(void* _this, unsigned int mode, void*unk1, void*unk2) { Framework::Logging::GetLogger("Hooks")->debug("[Camera::SendCommand]: id {}, unk1 {:p}, unk2 {:p}", mode, fmt::ptr(unk1), fmt::ptr(unk2)); return C_Camera__SendCommand_original(_this, mode, unk1, unk2); } static InitFunction init([]() { const auto modeChangePattern = reinterpret_cast<uint64_t>(hook::pattern("48 89 5C 24 ? 57 48 83 EC 30 0F B6 44 24 ? 48 8B D9").get_first()); MH_CreateHook((LPVOID)modeChangePattern, (PBYTE)C_Camera__ModeChangeImmediate, reinterpret_cast<void **>(&C_Camera__ModeChangeImmediate_original)); const auto sendCommandPattern = reinterpret_cast<uint64_t>(hook::pattern("48 8B 81 ? ? ? ? 48 8B 48 F8 48 8B 01 48 FF A0 D8 01 00 00").get_first()); MH_CreateHook((LPVOID)sendCommandPattern, (PBYTE)C_Camera__SendCommand, reinterpret_cast<void **>(&C_Camera__SendCommand_original)); });
58.3
152
0.748428
mufty
8955f6a271f64452ec97e572e655f66fc1c54a7f
2,488
cpp
C++
libs/fnd/algorithm/test/src/ranges/unit_test_fnd_algorithm_ranges_set_union.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/algorithm/test/src/ranges/unit_test_fnd_algorithm_ranges_set_union.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/algorithm/test/src/ranges/unit_test_fnd_algorithm_ranges_set_union.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file unit_test_fnd_algorithm_ranges_set_union.cpp * * @brief ranges::set_union のテスト * * @author myoukaku */ #include <bksge/fnd/algorithm/ranges/set_union.hpp> #include <bksge/fnd/algorithm/ranges/equal.hpp> #include <bksge/fnd/functional/ranges/greater.hpp> #include <bksge/fnd/iterator/ranges/next.hpp> #include <gtest/gtest.h> #include "constexpr_test.hpp" #include "ranges_test.hpp" namespace bksge_algorithm_test { namespace ranges_set_union_test { #define VERIFY(...) if (!(__VA_ARGS__)) { return false; } inline BKSGE_CXX14_CONSTEXPR bool test01() { namespace ranges = bksge::ranges; { int const x[] = { 1,3,3,5,5,5 }; int const y[] = { 2,3,4,5 }; int z[8] = {}; test_range<int const, input_iterator_wrapper> rx(x); test_range<int const, input_iterator_wrapper> ry(y); test_range<int, output_iterator_wrapper> rz(z); auto res = ranges::set_union(rx, ry, rz.begin()); VERIFY(res.in1 == rx.end()); VERIFY(res.in2 == ry.end()); VERIFY(res.out == rz.end()); int const a[] = { 1,2,3,3,4,5,5,5 }; VERIFY(ranges::equal(z, a)); } { int const x[] = { 4,2,1,1,0 }; int const y[] = { 3,2,1 }; int z[6] = {}; test_range<int const, input_iterator_wrapper> rx(x); test_range<int const, input_iterator_wrapper> ry(y); test_range<int, output_iterator_wrapper> rz(z); auto res = ranges::set_union(rx, ry, rz.begin(), ranges::greater{}); VERIFY(res.in1 == ranges::next(rx.begin(), 5)); VERIFY(res.in2 == ranges::next(ry.begin(), 3)); VERIFY(res.out == rz.end()); int const a[] = { 4,3,2,1,1,0 }; VERIFY(ranges::equal(z, a)); } return true; } struct X { int i; }; inline bool test02() { namespace ranges = bksge::ranges; { X const x[] = { {1},{3},{5} }; X const y[] = { {2},{4},{6} }; X z[6] = {}; test_range<X const, input_iterator_wrapper> rx(x); test_range<X const, input_iterator_wrapper> ry(y); test_range<X, output_iterator_wrapper> rz(z); auto res = ranges::set_union(rx, ry, rz.begin(), {}, &X::i, &X::i); VERIFY(res.in1 == rx.end()); VERIFY(res.in2 == ry.end()); VERIFY(res.out == rz.end()); int const a[] = { 1,2,3,4,5,6 }; VERIFY(ranges::equal(z, a, {}, &X::i)); } return true; } #undef VERIFY GTEST_TEST(AlgorithmTest, RangesSetUnionTest) { BKSGE_CXX14_CONSTEXPR_EXPECT_TRUE(test01()); EXPECT_TRUE(test02()); } } // namespace ranges_set_union_test } // namespace bksge_algorithm_test
26.189474
71
0.62701
myoukaku
895d8d8fa1e492c2c93fb1b44909c01965beb426
2,147
cpp
C++
src/bonefish/roles/wamp_role_type.cpp
aiwc/extlib-bonefish
2f0d15960b5178d2ab24fd8e11965a80ace2cb5a
[ "Apache-2.0" ]
58
2015-08-24T18:43:56.000Z
2022-01-09T00:55:06.000Z
src/bonefish/roles/wamp_role_type.cpp
aiwc/extlib-bonefish
2f0d15960b5178d2ab24fd8e11965a80ace2cb5a
[ "Apache-2.0" ]
47
2015-08-25T11:04:51.000Z
2018-02-28T22:38:12.000Z
src/bonefish/roles/wamp_role_type.cpp
aiwc/extlib-bonefish
2f0d15960b5178d2ab24fd8e11965a80ace2cb5a
[ "Apache-2.0" ]
32
2015-08-25T15:14:45.000Z
2020-03-23T09:35:31.000Z
/** * Copyright (C) 2015 Topology LP * * 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 <bonefish/roles/wamp_role_type.hpp> #include <cassert> #include <stdexcept> namespace bonefish { const char* role_type_to_string(const wamp_role_type& type) { const char* str = nullptr; switch(type) { case wamp_role_type::CALLEE: str = "callee"; break; case wamp_role_type::CALLER: str = "caller"; break; case wamp_role_type::PUBLISHER: str = "publisher"; break; case wamp_role_type::SUBSCRIBER: str = "subscriber"; break; case wamp_role_type::DEALER: str = "dealer"; break; case wamp_role_type::BROKER: str = "broker"; break; default: throw std::invalid_argument("unknown role type"); break; } return str; } wamp_role_type role_type_from_string(const std::string& type) { if (type.compare("callee") == 0) { return wamp_role_type::CALLEE; } if (type.compare("caller") == 0) { return wamp_role_type::CALLER; } if (type.compare("publisher") == 0) { return wamp_role_type::PUBLISHER; } if (type.compare("subscriber") == 0) { return wamp_role_type::SUBSCRIBER; } if (type.compare("dealer") == 0) { return wamp_role_type::DEALER; } if (type.compare("broker") == 0) { return wamp_role_type::BROKER; } throw std::invalid_argument("unknown role type"); } } // namespace bonefish
25.258824
76
0.607825
aiwc
89602bfa213172311b2146bed903d2192a822b2f
397
cpp
C++
MOS_6502_Emulator/ProcessingUnit_Shift.cpp
yu830425/MOS-6502-Simulator
b08495e1225b65df51ba2ad561f27b048a506c31
[ "MIT" ]
null
null
null
MOS_6502_Emulator/ProcessingUnit_Shift.cpp
yu830425/MOS-6502-Simulator
b08495e1225b65df51ba2ad561f27b048a506c31
[ "MIT" ]
null
null
null
MOS_6502_Emulator/ProcessingUnit_Shift.cpp
yu830425/MOS-6502-Simulator
b08495e1225b65df51ba2ad561f27b048a506c31
[ "MIT" ]
null
null
null
#include "ProcessingUnit.h" BYTE ProcessingUnit::ASL(BYTE value) { BYTE result = value << 1; m_negative = (result & 0x80) != 0; m_zero = result == 0; m_carry = (value & 0x80) != 0; return result; } BYTE ProcessingUnit::LSR(BYTE value) { BYTE result = value >> 1; m_zero = result == 0; m_carry = (value & 0x01) != 0; m_negative = false; //bit 7 will always be zero return result; }
17.26087
49
0.639798
yu830425
89632196bcc20b530d1612c02a82d34e5a9764cd
2,086
cpp
C++
Phoenix/Server/Source/Server.cpp
NicolasRicard/Phoenix
5eae2bd716a933fd405487d93c0e91e5ca56b3e4
[ "BSD-3-Clause" ]
1
2020-05-02T14:46:39.000Z
2020-05-02T14:46:39.000Z
Phoenix/Server/Source/Server.cpp
NicolasRicard/Phoenix
5eae2bd716a933fd405487d93c0e91e5ca56b3e4
[ "BSD-3-Clause" ]
null
null
null
Phoenix/Server/Source/Server.cpp
NicolasRicard/Phoenix
5eae2bd716a933fd405487d93c0e91e5ca56b3e4
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019-20 Genten Studios // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <Server/Server.hpp> #include <Common/Settings.hpp> #include <iostream> using namespace phx::server; using namespace phx; void Server::run() { std::cout << "Hello, Server!\nType \"exit\" to exit" << std::endl; Settings::get()->load("config.txt"); m_running = true; while(m_running == true){ std::cout << "\n>"; std::string input; std::cin >> input; if (input == "exit"){ m_running = false; } std::cout << input; } Settings::get()->save("config.txt"); }
40.901961
80
0.719559
NicolasRicard
896328db15c7251956079514284a32b07b515624
311
cpp
C++
package/standalone_kr_usn/lib/nvs_flash/src/cpp_config.cpp
teledatics/nrc7292_sdk
d0ba3f17e1bef3d6fec7370e7f0ffa77db56e3a4
[ "MIT" ]
7
2020-07-20T03:58:40.000Z
2022-03-15T13:29:18.000Z
package/standalone_kr_usn/lib/nvs_flash/src/cpp_config.cpp
teledatics/nrc7292_sdk
d0ba3f17e1bef3d6fec7370e7f0ffa77db56e3a4
[ "MIT" ]
3
2021-07-16T12:39:36.000Z
2022-02-02T18:19:51.000Z
package/standalone_kr_usn/lib/nvs_flash/src/cpp_config.cpp
teledatics/nrc7292_sdk
d0ba3f17e1bef3d6fec7370e7f0ffa77db56e3a4
[ "MIT" ]
4
2020-09-19T18:03:04.000Z
2022-02-02T13:17:34.000Z
/* below parameters defined to get around build error */ /* must check if there's any side effect */ void *__dso_handle = 0; extern "C" int __aeabi_atexit(void *object, void (*destructor)(void *), void *dso_handle) { return 0; } namespace __gnu_cxx { void __verbose_terminate_handler() { while(1); } }
17.277778
56
0.700965
teledatics
8966877555ac45ef7737404533a0b76718f8289b
2,530
cpp
C++
ModelViewer/ViewerFoundation/Utilities/Mac/NuoMathVectorMac.cpp
erpapa/NuoModelViewer
0dcb8bf99cb49c6e2c9535ed178e01674fa26824
[ "MIT" ]
265
2017-03-15T17:11:27.000Z
2022-03-30T07:50:00.000Z
ModelViewer/ViewerFoundation/Utilities/Mac/NuoMathVectorMac.cpp
erpapa/NuoModelViewer
0dcb8bf99cb49c6e2c9535ed178e01674fa26824
[ "MIT" ]
6
2017-07-03T01:57:49.000Z
2020-01-24T19:28:22.000Z
ModelViewer/ViewerFoundation/Utilities/Mac/NuoMathVectorMac.cpp
erpapa/NuoModelViewer
0dcb8bf99cb49c6e2c9535ed178e01674fa26824
[ "MIT" ]
39
2016-09-30T03:26:44.000Z
2022-01-24T07:37:20.000Z
// // NuoMathVectorMac.cpp // ModelViewer // // Created by Dong on 5/11/18. // Copyright © 2018 middleware. All rights reserved. // #include "NuoMathVector.h" NuoMatrix<float, 4> NuoMatrixPerspective(float aspect, float fovy, float near, float far) { // NOT use OpenGL persepctive! // Metal uses a 2x2x1 canonical cube (z in [0,1]), rather than the 2x2x2 one in OpenGL. // glm::mat4x4 gmat = glm::perspective(fovy, aspect, near, far); /* T const tanHalfFovy = tan(fovy / static_cast<T>(2)); tmat4x4<T, defaultp> Result(static_cast<T>(0)); Result[0][0] = static_cast<T>(1) / (aspect * tanHalfFovy); Result[1][1] = static_cast<T>(1) / (tanHalfFovy); Result[2][2] = - (zFar + zNear) / (zFar - zNear); Result[2][3] = - static_cast<T>(1); Result[3][2] = - (static_cast<T>(2) * zFar * zNear) / (zFar - zNear); return Result; */ float yScale = 1 / tan(fovy * 0.5); float xScale = yScale / aspect; float zRange = far - near; float zScale = -(far) / zRange; float wzScale = - far * near / zRange; vector_float4 P = { xScale, 0, 0, 0 }; vector_float4 Q = { 0, yScale, 0, 0 }; vector_float4 R = { 0, 0, zScale, -1 }; vector_float4 S = { 0, 0, wzScale, 0 }; matrix_float4x4 mat = { P, Q, R, S }; return mat; } NuoMatrix<float, 4> NuoMatrixOrthor(float left, float right, float top, float bottom, float near, float far) { /* Ortho in OpenGL tmat4x4<T, defaultp> Result(1); Result[0][0] = static_cast<T>(2) / (right - left); Result[1][1] = static_cast<T>(2) / (top - bottom); Result[2][2] = - static_cast<T>(2) / (zFar - zNear); Result[3][0] = - (right + left) / (right - left); Result[3][1] = - (top + bottom) / (top - bottom); Result[3][2] = - (zFar + zNear) / (zFar - zNear); */ // Ortho in Metal // http://blog.athenstean.com/post/135771439196/from-opengl-to-metal-the-projection-matrix float yScale = 2 / (top - bottom); float xScale = 2 / (right - left); float zRange = far - near; float zScale = - 1 / zRange; float wzScale = - near / zRange; float wyScale = - (top + bottom) / (top - bottom); float wxScale = - (right + left) / (right - left); vector_float4 P = { xScale, 0, 0, 0 }; vector_float4 Q = { 0, yScale, 0, 0 }; vector_float4 R = { 0, 0, zScale, 0 }; vector_float4 S = { wxScale, wyScale, wzScale, 1 }; matrix_float4x4 mat = { P, Q, R, S }; return mat; }
32.025316
108
0.574308
erpapa
89767ac7fa89a5fa716a4ebbcc997fddb5c791c1
674
cpp
C++
Source/DemoScene/Vector2.cpp
ookumaneko/PC-Psp-Cross-Platform-Demoscene
0c192f9ecf5a4fd9db3c9a2c9998b365bf480c1e
[ "MIT" ]
null
null
null
Source/DemoScene/Vector2.cpp
ookumaneko/PC-Psp-Cross-Platform-Demoscene
0c192f9ecf5a4fd9db3c9a2c9998b365bf480c1e
[ "MIT" ]
null
null
null
Source/DemoScene/Vector2.cpp
ookumaneko/PC-Psp-Cross-Platform-Demoscene
0c192f9ecf5a4fd9db3c9a2c9998b365bf480c1e
[ "MIT" ]
null
null
null
#include "Vector2.h" //--------------------------------------// //---------------Common Methods---------// //--------------------------------------// Vector2::Vector2(void) { _vec.x = 0; _vec.y = 0; } Vector2::Vector2(float x, float y) { _vec.x = x; _vec.y = y; } Vector2::~Vector2(void) { } float& Vector2::X() { return _vec.x; } float Vector2::X() const { return _vec.x; } float& Vector2::Y() { return _vec.y; } float Vector2::Y() const { return _vec.y; } float Vector2::GetX() const { return _vec.x; } float Vector2::GetY() const { return _vec.y; } void Vector2::SetX(float x) { _vec.x = x; } inline void Vector2::SetY(float y) { _vec.y = y; }
10.369231
42
0.510386
ookumaneko
8977a8c6504a2a0c971d8880dbe16757ec3d590f
297
cpp
C++
getdate.cpp
eqvpkbz/old.eqvpkbz.github.io
0adb4b7400248d3caf4a8e12525279d19c2ba83f
[ "MIT" ]
null
null
null
getdate.cpp
eqvpkbz/old.eqvpkbz.github.io
0adb4b7400248d3caf4a8e12525279d19c2ba83f
[ "MIT" ]
null
null
null
getdate.cpp
eqvpkbz/old.eqvpkbz.github.io
0adb4b7400248d3caf4a8e12525279d19c2ba83f
[ "MIT" ]
null
null
null
#include<iostream> #include<ctime> #include<cstdio> using namespace std; int main() { time_t tt;time(&tt); tt = tt + 8*3600; tm* t= gmtime(&tt); printf("%d-%02d-%02d %02d:%02d:%02d\n",t->tm_year + 1900,t->tm_mon + 1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec); return 0; }
17.470588
118
0.599327
eqvpkbz
897d147d0850d676513a5ba5caea01cb3371d90d
2,007
cpp
C++
DiscoveryService.cpp
jambamamba/DiscoveryService
0eae060bb9ac43ee91ca7c5596862588d130a4f6
[ "Apache-2.0" ]
null
null
null
DiscoveryService.cpp
jambamamba/DiscoveryService
0eae060bb9ac43ee91ca7c5596862588d130a4f6
[ "Apache-2.0" ]
null
null
null
DiscoveryService.cpp
jambamamba/DiscoveryService
0eae060bb9ac43ee91ca7c5596862588d130a4f6
[ "Apache-2.0" ]
null
null
null
#include "DiscoveryService.h" #include <arpa/inet.h> #include <iostream> #include <netinet/in.h> #include <regex> #include <string> #include <sys/socket.h> #include <sys/stat.h> #include "Utils.h" namespace { }//namespace //------------------------------------------------------------------------------- DiscoveryService::DiscoveryService(const std::string &device_id_file) : m_udp_socket(SERVER_PORT, sizeof(DiscoveryData), MAX_QUEUE_SIZE, "DiscoveryService", false, [this](const uint8_t *dataFromClient, size_t dataLen, const sockaddr_in &sa){ HandleUdpDatagram(dataFromClient, dataLen, sa); }) { Utils::ReadDeviceId(m_discover_message, device_id_file); std::cout << "Device Name: " << m_discover_message.m_name << ", Device Serial Number: " << m_discover_message.m_serial_number << "\n"; } //------------------------------------------------------------------------------- DiscoveryService::~DiscoveryService() { m_udp_socket.Stop(); std::cout << "dtor\n"; } void DiscoveryService::UpdateDeviceId(const std::string &device_id_file) { Utils::ReadDeviceId(m_discover_message, device_id_file); } //------------------------------------------------------------------------------- void DiscoveryService::HandleUdpDatagram(const uint8_t *dataFromClient, size_t dataLen, const sockaddr_in &sa) { auto msg = reinterpret_cast<const DiscoveryData*>(dataFromClient); // std::cout << "Received discovery datagram from " << // inet_ntoa(sa.sin_addr) << ":" << ntohs(sa.sin_port) << "\n"; if(msg->m_version != DiscoveryData::DISCOVERY_VERSION) { std::cout << "Failed: Incompatible Discovery message received\n"; return; } Utils::SaveServerIpAddress(inet_ntoa(sa.sin_addr)); m_udp_socket.SendToClient(sa, reinterpret_cast<char*>(&m_discover_message)); }
35.839286
139
0.567015
jambamamba
89869fe4cb06b29a57c1a2e7077528ea2a55a90d
12,463
cpp
C++
test/OpenDDLIntegrationTest.cpp
lerppana/openddl-parser
a9bc8a5dee880d546136e33a5977d7a0a28eaa20
[ "MIT" ]
24
2015-02-08T23:16:05.000Z
2021-07-15T07:31:08.000Z
test/OpenDDLIntegrationTest.cpp
lerppana/openddl-parser
a9bc8a5dee880d546136e33a5977d7a0a28eaa20
[ "MIT" ]
64
2015-01-28T21:42:06.000Z
2021-11-01T07:49:24.000Z
test/OpenDDLIntegrationTest.cpp
lerppana/openddl-parser
a9bc8a5dee880d546136e33a5977d7a0a28eaa20
[ "MIT" ]
10
2015-11-17T09:18:57.000Z
2021-10-06T18:59:05.000Z
/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2014-2020 Kim Kulling Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -----------------------------------------------------------------------------------------------*/ #include "gtest/gtest.h" #include <openddlparser/OpenDDLParser.h> #include "UnitTestCommon.h" #include <vector> BEGIN_ODDLPARSER_NS class OpenDDLIntegrationTest : public testing::Test { // empty }; TEST_F( OpenDDLIntegrationTest, parseMetricTest ) { char token[] = "Metric( key = \"distance\" ) { float{ 1 } }\n" "Metric( key = \"up\" ) { float{ 1 } }\n"; bool result( false ); OpenDDLParser theParser; theParser.setBuffer( token, strlen( token ) ); result = theParser.parse(); EXPECT_TRUE( result ); DDLNode *myNode = theParser.getRoot(); ASSERT_FALSE(nullptr == myNode); Context *ctx = theParser.getContext(); ASSERT_FALSE(nullptr == ctx); DDLNode::DllNodeList myList = myNode->getChildNodeList(); ASSERT_EQ( 2U, myList.size() ); DDLNode *child = myList[ 0 ]; ASSERT_FALSE(nullptr == child); EXPECT_EQ( "Metric", child->getType() ); Property *prop = child->getProperties(); ASSERT_FALSE(nullptr == prop); const char *data1 = ( const char * ) prop->m_value->m_data; int res( ::strncmp( "distance", data1, strlen( "distance" ) ) ); EXPECT_EQ(Value::ValueType::ddl_string, prop->m_value->m_type); EXPECT_EQ( 0, res ); child = myList[ 1 ]; ASSERT_FALSE(nullptr == child); EXPECT_EQ( "Metric", child->getType() ); prop = child->getProperties(); const char *data2 = ( const char * ) prop->m_value->m_data; res = ::strncmp( "up", data2, strlen( "up" ) ); EXPECT_EQ(Value::ValueType::ddl_string, prop->m_value->m_type); EXPECT_EQ( 0, res ); } TEST_F( OpenDDLIntegrationTest, parseEmbeddedStructureTest ) { char token[] = "GeometryNode $node1\n" "{\n" " string\n" " {\n" " \"test\"\n" " }\n" "}"; bool result( false ); OpenDDLParser theParser; theParser.setBuffer( token, strlen( token ) ); result = theParser.parse(); EXPECT_TRUE( result ); DDLNode *root( theParser.getRoot() ); ASSERT_FALSE(nullptr == root); } TEST_F( OpenDDLIntegrationTest, parseEmbeddedStructureWithRefTest ) { char token[] = "GeometryNode $node1\n" "{\n" " Name{ string{ \"Box001\" } }\n" " ObjectRef{ ref{ $geometry1 } }\n" " MaterialRef{ ref{ $material1 } }\n" "}"; bool result( false ); OpenDDLParser theParser; theParser.setBuffer( token, strlen( token ) ); result = theParser.parse(); EXPECT_TRUE( result ); DDLNode *root( theParser.getRoot() ); ASSERT_FALSE(nullptr == root); DDLNode::DllNodeList childs = root->getChildNodeList(); ASSERT_EQ( 1U, childs.size() ); DDLNode::DllNodeList childChilds = childs[ 0 ]->getChildNodeList(); ASSERT_EQ( 3U, childChilds.size() ); DDLNode *currentNode = nullptr; currentNode = childChilds[ 0 ]; EXPECT_EQ( "Name", currentNode->getType() ); currentNode = childChilds[ 1 ]; EXPECT_EQ( "ObjectRef", currentNode->getType() ); currentNode = childChilds[ 2 ]; EXPECT_EQ( "MaterialRef", currentNode->getType() ); } static void dataArrayList2StdVector( DataArrayList *dataArrayList, std::vector<float> &container ) { if (nullptr == dataArrayList) { return; } Value *val( dataArrayList->m_dataList ); if (nullptr == val) { return; } while (nullptr != val) { container.push_back( val->getFloat() ); val = val->m_next; } } TEST_F( OpenDDLIntegrationTest, parseTransformDataTest ) { char token[] = "Transform\n" "{\n" " float[ 16 ]\n" " {\n" " {0x3F800000, 0x00000000, 0x00000000, 0x00000000, // {1, 0, 0, 0\n" " 0x00000000, 0x3F800000, 0x00000000, 0x00000000, // 0, 1, 0, 0\n" " 0x00000000, 0x00000000, 0x3F800000, 0x00000000, // 0, 0, 1, 0\n" " 0xBEF33B00, 0x411804DE, 0x00000000, 0x3F800000} // -0.47506, 9.50119, 0, 1}\n" " }\n" "}\n"; bool result( false ); OpenDDLParser theParser; theParser.setBuffer( token, strlen( token ) ); result = theParser.parse(); EXPECT_TRUE( result ); DDLNode *root( theParser.getRoot() ); EXPECT_TRUE(nullptr != root); const DDLNode::DllNodeList &childs( root->getChildNodeList() ); EXPECT_EQ( 1U, childs.size() ); DDLNode *transform( childs[ 0 ] ); EXPECT_TRUE(nullptr != transform); DataArrayList *transformData( transform->getDataArrayList() ); EXPECT_TRUE(nullptr != transformData); EXPECT_EQ( 16U, transformData->m_numItems ); std::vector<float> container; dataArrayList2StdVector( transformData, container ); EXPECT_FLOAT_EQ( 1.0f, container[ 0 ] ); EXPECT_FLOAT_EQ( 0.0f, container[ 1 ] ); EXPECT_FLOAT_EQ( 0.0f, container[ 2 ] ); EXPECT_FLOAT_EQ( 0.0f, container[ 3 ] ); } TEST_F( OpenDDLIntegrationTest, exportDataTest ) { char token [] = "Metric( key = \"distance\" ) { float{ 1 } }\n" "Metric( key = \"angle\" ) { float{ 1 } }\n" "Metric( key = \"time\" ) { float{ 1 } }\n" "Metric( key = \"up\" ) { string{ \"z\" } }\n" "\n" "GeometryNode $node1\n" "{\n" " Name{ string{ \"Box001\" } }\n" " ObjectRef{ ref{ $geometry1 } }\n" " MaterialRef{ ref{ $material1 } }\n" "\n" "Transform\n" "{\n" " float[ 16 ]\n" " {\n" " { 0x3F800000, 0x00000000, 0x00000000, 0x00000000, // {1, 0, 0, 0\n" " 0x00000000, 0x3F800000, 0x00000000, 0x00000000, // 0, 1, 0, 0\n" " 0x00000000, 0x00000000, 0x3F800000, 0x00000000, // 0, 0, 1, 0\n" " 0xBEF33B00, 0x411804DE, 0x00000000, 0x3F800000 } // -0.47506, 9.50119, 0, 1}\n" " }\n" " }\n" "}\n" "\n" "GeometryNode $node2\n" "{\n" " Name{ string{ \"Box002\" } }\n" " ObjectRef{ ref{ $geometry1 } }\n" " MaterialRef{ ref{ $material1 } }\n" "\n" " Transform\n" " {\n" " float[ 16 ]\n" " {\n" " { 0x3F800000, 0x00000000, 0x00000000, 0x00000000, // {1, 0, 0, 0\n" " 0x00000000, 0x3F800000, 0x00000000, 0x00000000, // 0, 1, 0, 0\n" " 0x00000000, 0x00000000, 0x3F800000, 0x00000000, // 0, 0, 1, 0\n" " 0x43041438, 0x411804DE, 0x00000000, 0x3F800000 } // 132.079, 9.50119, 0, 1}\n" " }\n" " }\n" "}\n" "\n" "GeometryObject $geometry1 // Box001, Box002\n" "{ \n" " Mesh( primitive = \"triangles\" )\n" " {\n" " VertexArray( attrib = \"position\" )\n" " {\n" " float[ 3 ] // 24\n" " { \n" " { 0xC2501375, 0xC24C468A, 0x00000000 },{ 0xC2501375, 0x424C468A, 0x00000000 },{ 0x42501375, 0x424C468A, 0x00000000 },{ 0x42501375, 0xC24C468A, 0x00000000 },{ 0xC2501375, 0xC24C468A, 0x42BA3928 },{ 0x42501375, 0xC24C468A, 0x42BA3928 },{ 0x42501375, 0x424C468A, 0x42BA3928 },{ 0xC2501375, 0x424C468A, 0x42BA3928 }, \n" " { 0xC2501375, 0xC24C468A, 0x00000000 },{ 0x42501375, 0xC24C468A, 0x00000000 },{ 0x42501375, 0xC24C468A, 0x42BA3928 },{ 0xC2501375, 0xC24C468A, 0x42BA3928 },{ 0x42501375, 0xC24C468A, 0x00000000 },{ 0x42501375, 0x424C468A, 0x00000000 },{ 0x42501375, 0x424C468A, 0x42BA3928 },{ 0x42501375, 0xC24C468A, 0x42BA3928 }, \n" " { 0x42501375, 0x424C468A, 0x00000000 },{ 0xC2501375, 0x424C468A, 0x00000000 },{ 0xC2501375, 0x424C468A, 0x42BA3928 },{ 0x42501375, 0x424C468A, 0x42BA3928 },{ 0xC2501375, 0x424C468A, 0x00000000 },{ 0xC2501375, 0xC24C468A, 0x00000000 },{ 0xC2501375, 0xC24C468A, 0x42BA3928 },{ 0xC2501375, 0x424C468A, 0x42BA3928 }\n" " }\n" " }\n" "\n" " VertexArray( attrib = \"normal\" )\n" " {\n" " float[ 3 ] // 24\n" " { \n" " { 0x00000000, 0x00000000, 0xBF800000 },{ 0x00000000, 0x00000000, 0xBF800000 },{ 0x00000000, 0x00000000, 0xBF800000 },{ 0x00000000, 0x00000000, 0xBF800000 },{ 0x00000000, 0x00000000, 0x3F800000 },{ 0x00000000, 0x00000000, 0x3F800000 },{ 0x00000000, 0x00000000, 0x3F800000 },{ 0x00000000, 0x00000000, 0x3F800000 }, \n" " { 0x00000000, 0xBF800000, 0x00000000 },{ 0x00000000, 0xBF800000, 0x00000000 },{ 0x00000000, 0xBF800000, 0x00000000 },{ 0x80000000, 0xBF800000, 0x00000000 },{ 0x3F800000, 0x00000000, 0x00000000 },{ 0x3F800000, 0x00000000, 0x00000000 },{ 0x3F800000, 0x00000000, 0x00000000 },{ 0x3F800000, 0x00000000, 0x00000000 }, \n" " { 0x00000000, 0x3F800000, 0x00000000 },{ 0x00000000, 0x3F800000, 0x00000000 },{ 0x00000000, 0x3F800000, 0x00000000 },{ 0x80000000, 0x3F800000, 0x00000000 },{ 0xBF800000, 0x00000000, 0x00000000 },{ 0xBF800000, 0x00000000, 0x00000000 },{ 0xBF800000, 0x00000000, 0x00000000 },{ 0xBF800000, 0x00000000, 0x00000000 }\n" " }\n" " }\n" "\n" " VertexArray( attrib = \"texcoord\" )\n" " {\n" " float[ 2 ] // 24\n" " { \n" " { 0x3F800000, 0x00000000 },{ 0x3F800000, 0x3F800000 },{ 0x00000000, 0x3F800000 },{ 0x00000000, 0x00000000 },{ 0x00000000, 0x00000000 },{ 0x3F800000, 0x00000000 },{ 0x3F800000, 0x3F800000 },{ 0x00000000, 0x3F800000 }, \n" " { 0x00000000, 0x00000000 },{ 0x3F800000, 0x00000000 },{ 0x3F800000, 0x3F800000 },{ 0x00000000, 0x3F800000 },{ 0x00000000, 0x00000000 },{ 0x3F800000, 0x00000000 },{ 0x3F800000, 0x3F800000 },{ 0x00000000, 0x3F800000 }, \n" " { 0x00000000, 0x00000000 },{ 0x3F800000, 0x00000000 },{ 0x3F800000, 0x3F800000 },{ 0x00000000, 0x3F800000 },{ 0x00000000, 0x00000000 },{ 0x3F800000, 0x00000000 },{ 0x3F800000, 0x3F800000 },{ 0x00000000, 0x3F800000 }\n" " }\n" " }\n" "\n" " IndexArray\n" " {\n" " unsigned_int32[ 3 ] // 12\n" " { \n" " { 0, 1, 2 },{ 2, 3, 0 },{ 4, 5, 6 },{ 6, 7, 4 },{ 8, 9, 10 },{ 10, 11, 8 },{ 12, 13, 14 },{ 14, 15, 12 },{ 16, 17, 18 },{ 18, 19, 16 },{ 20, 21, 22 },{ 22, 23, 20 }\n" " }\n" " }\n" " }\n" "}\n" "\n" "Material $material1\n" "{\n" " Name{ string{ \"03 - Default\" } }\n" "\n" " Color( attrib = \"diffuse\" ) { float[ 3 ]{ { 0.588235, 0.588235, 0.588235 } } }\n" " Texture( attrib = \"diffuse\" )\n" " {\n" " string{ \"texture/Concrete.tga\" }\n" " }\n" "}\n"; bool result( false ); OpenDDLParser theParser; theParser.setBuffer( token, strlen( token ) ); result = theParser.parse(); EXPECT_TRUE( result ); result = theParser.exportContext( theParser.getContext(), "" ); EXPECT_TRUE( result ); } END_ODDLPARSER_NS
43.425087
340
0.569686
lerppana
898a9117b2f5593cd6a8e6350897187ab58b7a28
6,746
cpp
C++
ProjectEuler+/euler-0058.cpp
sarvekash/HackerRank_Solutions
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
[ "Apache-2.0" ]
null
null
null
ProjectEuler+/euler-0058.cpp
sarvekash/HackerRank_Solutions
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
[ "Apache-2.0" ]
null
null
null
ProjectEuler+/euler-0058.cpp
sarvekash/HackerRank_Solutions
8f48e5b1a6e792a85a10d8c328cd1f5341fb16a8
[ "Apache-2.0" ]
1
2021-05-28T11:14:34.000Z
2021-05-28T11:14:34.000Z
// //////////////////////////////////////////////////////// // # Title // Spiral primes // // # URL // https://projecteuler.net/problem=58 // http://euler.stephan-brumme.com/58/ // // # Problem // Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed. // // ''__37__ 36 35 34 33 32 31'' // ''38 17 16 15 14 13 30'' // ''39 18 5 4 3 12 29'' // ''40 19 6 1 2 11 28'' // ''41 20 7 8 9 10 27'' // ''42 21 22 23 24 25 26'' // ''43 44 45 46 47 48 49'' // // It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that // 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of `frac{8}{13} approx 62%`. // // If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. // If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%? // // # Solved by // Stephan Brumme // February 2017 // // # Algorithm // My solution consists almost entirely of "old code": // - the Miller-Rabin primality test from problem 50 ... // - which in turn requires modular arithmetic from problem 48 // // That code can be found in my [toolbox](../toolbox/), too. // // # Hackerrank // My portable ''mulmod'' was a little bit too slow for Hackerrank, therefore I added the "GCC"-Hack: // the GCC-extension ''__int128'' simplifies ''mulmod'' to a one-line function (which is much faster, too). #include <iostream> // return (a*b) % modulo unsigned long long mulmod(unsigned long long a, unsigned long long b, unsigned long long modulo) { #ifdef __GNUC__ // use GCC's optimized 128 bit code return ((unsigned __int128)a * b) % modulo; #endif // (a * b) % modulo = (a % modulo) * (b % modulo) % modulo a %= modulo; b %= modulo; // fast path if (a <= 0xFFFFFFF && b <= 0xFFFFFFF) return (a * b) % modulo; // we might encounter overflows (slow path) // the number of loops depends on b, therefore try to minimize b if (b > a) std::swap(a, b); // bitwise multiplication unsigned long long result = 0; while (a > 0 && b > 0) { // b is odd ? a*b = a + a*(b-1) if (b & 1) { result += a; if (result >= modulo) result -= modulo; // skip b-- because the bit-shift at the end will remove the lowest bit anyway } // b is even ? a*b = (2*a)*(b/2) a <<= 1; if (a >= modulo) a -= modulo; // next bit b >>= 1; } return result; } // return (base^exponent) % modulo unsigned long long powmod(unsigned long long base, unsigned long long exponent, unsigned long long modulo) { unsigned long long result = 1; while (exponent > 0) { // fast exponentation: // odd exponent ? a^b = a*a^(b-1) if (exponent & 1) result = mulmod(result, base, modulo); // even exponent ? a^b = (a*a)^(b/2) base = mulmod(base, base, modulo); exponent >>= 1; } return result; } // Miller-Rabin-test bool isPrime(unsigned long long p) { // IMPORTANT: requires mulmod(a, b, modulo) and powmod(base, exponent, modulo) // some code from https://ronzii.wordpress.com/2012/03/04/miller-rabin-primality-test/ // with optimizations from http://ceur-ws.org/Vol-1326/020-Forisek.pdf // good bases can be found at http://miller-rabin.appspot.com/ // trivial cases const unsigned int bitmaskPrimes2to31 = (1 << 2) | (1 << 3) | (1 << 5) | (1 << 7) | (1 << 11) | (1 << 13) | (1 << 17) | (1 << 19) | (1 << 23) | (1 << 29); // = 0x208A28Ac if (p < 31) return (bitmaskPrimes2to31 & (1 << p)) != 0; if (p % 2 == 0 || p % 3 == 0 || p % 5 == 0 || p % 7 == 0 || // divisible by a small prime p % 11 == 0 || p % 13 == 0 || p % 17 == 0) return false; if (p < 17*19) // we filtered all composite numbers < 17*19, all others below 17*19 must be prime return true; // test p against those numbers ("witnesses") // good bases can be found at http://miller-rabin.appspot.com/ const unsigned int STOP = 0; const unsigned int TestAgainst1[] = { 377687, STOP }; const unsigned int TestAgainst2[] = { 31, 73, STOP }; const unsigned int TestAgainst3[] = { 2, 7, 61, STOP }; // first three sequences are good up to 2^32 const unsigned int TestAgainst4[] = { 2, 13, 23, 1662803, STOP }; const unsigned int TestAgainst7[] = { 2, 325, 9375, 28178, 450775, 9780504, 1795265022, STOP }; // good up to 2^64 const unsigned int* testAgainst = TestAgainst7; // use less tests if feasible if (p < 5329) testAgainst = TestAgainst1; else if (p < 9080191) testAgainst = TestAgainst2; else if (p < 4759123141ULL) testAgainst = TestAgainst3; else if (p < 1122004669633ULL) testAgainst = TestAgainst4; // find p - 1 = d * 2^j auto d = p - 1; d >>= 1; unsigned int shift = 0; while ((d & 1) == 0) { shift++; d >>= 1; } // test p against all bases do { auto x = powmod(*testAgainst++, d, p); // is test^d % p == 1 or -1 ? if (x == 1 || x == p - 1) continue; // now either prime or a strong pseudo-prime // check test^(d*2^r) for 0 <= r < shift bool maybePrime = false; for (unsigned int r = 0; r < shift; r++) { // x = x^2 % p // (initial x was test^d) x = powmod(x, 2, p); // x % p == 1 => not prime if (x == 1) return false; // x % p == -1 => prime or an even stronger pseudo-prime if (x == p - 1) { // next iteration maybePrime = true; break; } } // not prime if (!maybePrime) return false; } while (*testAgainst != STOP); // prime return true; } int main() { unsigned int percentage = 10; std::cin >> percentage; // the lower right diagonal contains only squares unsigned long long numPrimes = 0; unsigned long long sideLength = 1; unsigned long long diagonals = 1; do { sideLength += 2; diagonals += 4; unsigned long long lowerRight = sideLength * sideLength; unsigned long long lowerLeft = lowerRight - (sideLength - 1); unsigned long long upperLeft = lowerLeft - (sideLength - 1); unsigned long long upperRight = upperLeft - (sideLength - 1); // no need to test lowerRight since it's a square and never prime if (isPrime(lowerLeft) != 0) numPrimes++; if (isPrime(upperLeft) != 0) numPrimes++; if (isPrime(upperRight) != 0) numPrimes++; } while (numPrimes * 100 / diagonals >= percentage); std::cout << sideLength << std::endl; return 0; }
29.203463
151
0.589386
sarvekash
898b35ac17755bdec68108bcf95660ead020c425
499
cpp
C++
ch1/Babylonian_sqr/algorithm.cpp
omar659/Algorithms-Sequential-Parallel-Distributed
3543631139a20625f413cea2ba1f013f3a40d123
[ "MIT" ]
2
2020-02-19T09:27:20.000Z
2020-02-19T09:28:21.000Z
ch1/Babylonian_sqr/algorithm.cpp
omar-3/Algorithms-Sequential-Parallel-Distributed
3543631139a20625f413cea2ba1f013f3a40d123
[ "MIT" ]
null
null
null
ch1/Babylonian_sqr/algorithm.cpp
omar-3/Algorithms-Sequential-Parallel-Distributed
3543631139a20625f413cea2ba1f013f3a40d123
[ "MIT" ]
null
null
null
/* sqrt(a) * sqrt(a) = a so sqrt(a) is the side of square with area a and we keep two numbers as the side of a polygon with area a and make them get closer together by averaging <3 */ #include <iostream> using namespace std; typedef long double number; //you need to use double so the while condition would work number square(number a, double error=0.0001) { number x = a; while (abs(x - a/x) > error) { x = (x+(a/x))/2; } return x; }
24.95
107
0.607214
omar659
89909eaa0da1334b197f4a98dac4e37d652b9dbe
6,066
cpp
C++
nohotspot-skiplist/skiplist.cpp
jyizheng/hydralist
910dad17eab4815057e3ea3e46b02f6ce45d7e46
[ "Apache-2.0" ]
17
2020-11-25T17:45:21.000Z
2021-12-24T06:18:33.000Z
nohotspot-skiplist/skiplist.cpp
jyizheng/hydralist
910dad17eab4815057e3ea3e46b02f6ce45d7e46
[ "Apache-2.0" ]
null
null
null
nohotspot-skiplist/skiplist.cpp
jyizheng/hydralist
910dad17eab4815057e3ea3e46b02f6ce45d7e46
[ "Apache-2.0" ]
6
2020-11-20T17:21:46.000Z
2022-01-21T04:35:24.000Z
/* * skiplist.c: definitions of the skip list data stucture * * Author: Ian Dick, 2013 * */ /* Module overview This module provides the basic structures used to create the skip list data structure, as described in: Crain, T., Gramoli, V., Raynal, M. (2013) "No Hot-Spot Non-Blocking Skip List", to appear in The 33rd IEEE International Conference on Distributed Computing Systems (ICDCS). One approach to designing a skip list data structure is to have one kind of node, and to assign each node in the list a level. A node with level l has l backwards pointers and l forward pointers, one for each level of the skip list. Skip lists designed this way have index level nodes that are implicit, are are handled by multiple pointers per node. The approach taken here is to explicitly create the index nodes and have these as separate structures to regular nodes. The reason for this is that the background maintenance method used here is much easier to implement this way. */ #include <stdio.h> #include <stdlib.h> #include "common.h" #include "skiplist.h" #include "background.h" #include "garbagecoll.h" #include "ptst.h" static int gc_id[NUM_LEVELS]; /* - Public skiplist interface - */ /** * node_new - create a new bottom-level node * @key: the key for the new node * @val: the val for the new node * @prev: the prev node pointer for the new node * @next: the next node pointer for the new node * @level: the level for the new node * @ptst: the per-thread state * * Note: All nodes are originally created with * marker set to 0 (i.e. they are unmarked). */ node_t* node_new(sl_key_t key, val_t val, node_t *prev, node_t *next, unsigned int level, ptst_t *ptst) { node_t *node; node = (node_t *)gc_alloc(ptst, gc_id[NODE_LEVEL]); node->key = key; node->val = val; node->prev = prev; node->next = next; node->level = level; node->marker = 0; assert (node->next != node); return node; } /** * inode_new - create a new index node * @right: the right inode pointer for the new inode * @down: the down inode pointer for the new inode * @node: the node pointer for the new inode * @ptst: per-thread state */ inode_t* inode_new(inode_t *right, inode_t *down, node_t *node, ptst_t *ptst) { inode_t *inode; inode = (inode_t *)gc_alloc(ptst, gc_id[INODE_LEVEL]); inode->right = right; inode->down = down; inode->node = node; return inode; } /** * node_delete - delete a bottom-level node * @node: the node to delete */ void node_delete(node_t *node, ptst_t *ptst) { gc_free(ptst, (void*)node, gc_id[NODE_LEVEL]); } /** * inode_delete - delete an index node * @inode: the index node to delete */ void inode_delete(inode_t *inode, ptst_t *ptst) { gc_free(ptst, (void*)inode, gc_id[INODE_LEVEL]); } /** * set_new - create a new set implemented as a skip list * @bg_start: if 1 start the bg thread, otherwise don't * * Returns a newly created skip list set. * Note: A background thread to update the index levels of the * skip list is created and kick-started as part of this routine. */ set_t* set_new(int start) { set_t *set; set = (set_t *)malloc(sizeof(set_t)); if (!set) { perror("Failed to malloc a set\n"); exit(1); } set->head = (node_t *)malloc(sizeof(node_t)); set->head->key = 0; set->head->val = NULL; set->head->prev = NULL; set->head->next = NULL; set->head->level = 1; set->head->marker = 0; set->top = (inode_t *)malloc(sizeof(inode_t)); set->top->right = NULL; set->top->down = NULL; set->top->node = set->head; set->raises = 0; bg_init(set); if (start) bg_start(0); return set; } /** * set_delete - delete the set * @set: the set to delete */ void set_delete(set_t *set) { inode_t *top; inode_t *icurr; inode_t *inext; node_t *curr; node_t *next; /* stop the background thread */ bg_stop(); /* warning - we are not deallocating the memory for the skip list */ } /** * set_print - print the set * @set: the skip list set to print * @flag: if non-zero include logically deleted nodes in the count */ void set_print(set_t *set, int flag) { node_t *node = set->head; inode_t *ihead = set->top; inode_t *itemp = set->top; /* print the index items */ while (NULL != ihead) { while (NULL != itemp) { //printf("%lu ", itemp->node->key); itemp = itemp->right; } printf("\n"); ihead = ihead->down; itemp = ihead; } /* while (NULL != node) { if (flag && (NULL != node->val && node->val != node)) printf("%lu ", node->key); else if (!flag) printf("%lu ", node->key); node = node->next; } */ printf("\n"); } /** * set_size - print the size of the set * @set: the set to print the size of * @flag: if non-zero include logically deleted nodes in the count * * Return the size of the set. */ int set_size(set_t *set, int flag) { struct sl_node *node = set->head; int size = 0; node = node->next; while (NULL != node) { if (flag && (NULL != node->val && node != node->val)) ++size; else if (!flag) ++size; node = node->next; } return size; } /** * set_subsystem_init - initialise the set subsystem */ void set_subsystem_init(void) { gc_id[NODE_LEVEL] = gc_add_allocator(sizeof(node_t)); gc_id[INODE_LEVEL] = gc_add_allocator(sizeof(inode_t)); }
25.487395
77
0.5788
jyizheng
8993ddc93dcddec9532c3760f4c4a6294eb18841
2,032
cpp
C++
Blake2/Blake2/MacDescription.cpp
Steppenwolfe65/Blake2
9444e194323f98bb797816bc774d202276d17243
[ "Intel", "MIT" ]
1
2016-11-09T05:34:58.000Z
2016-11-09T05:34:58.000Z
Blake2/Blake2/MacDescription.cpp
Steppenwolfe65/Blake2
9444e194323f98bb797816bc774d202276d17243
[ "Intel", "MIT" ]
null
null
null
Blake2/Blake2/MacDescription.cpp
Steppenwolfe65/Blake2
9444e194323f98bb797816bc774d202276d17243
[ "Intel", "MIT" ]
null
null
null
#include "MacDescription.h" #include "StreamWriter.h" NAMESPACE_PROCESSING MacDescription MacDescription::HMACSHA256() { return MacDescription(64, Digests::SHA256); } MacDescription MacDescription::HMACSHA512() { return MacDescription(128, Digests::SHA512); } MacDescription MacDescription::CMACAES256() { return MacDescription(32, BlockCiphers::Rijndael, IVSizes::V128); } int MacDescription::GetHeaderSize() { return MACHDR_SIZE; } void MacDescription::Reset() { m_macType = 0; m_keySize = 0; m_ivSize = 0; m_hmacEngine = 0; m_engineType = 0; m_blockSize = 0; m_roundCount = 0; m_kdfEngine = 0; } std::vector<byte> MacDescription::ToBytes() { IO::StreamWriter writer(GetHeaderSize()); writer.Write(static_cast<byte>(m_macType)); writer.Write(static_cast<short>(m_keySize)); writer.Write(static_cast<byte>(m_ivSize)); writer.Write(static_cast<byte>(m_hmacEngine)); writer.Write(static_cast<byte>(m_engineType)); writer.Write(static_cast<byte>(m_blockSize)); writer.Write(static_cast<byte>(m_roundCount)); writer.Write(static_cast<byte>(m_kdfEngine)); return writer.GetBytes(); } IO::MemoryStream* MacDescription::ToStream() { IO::StreamWriter writer(GetHeaderSize()); writer.Write(static_cast<byte>(m_macType)); writer.Write(static_cast<short>(m_keySize)); writer.Write(static_cast<byte>(m_ivSize)); writer.Write(static_cast<byte>(m_hmacEngine)); writer.Write(static_cast<byte>(m_engineType)); writer.Write(static_cast<byte>(m_blockSize)); writer.Write(static_cast<byte>(m_roundCount)); writer.Write(static_cast<byte>(m_kdfEngine)); return writer.GetStream(); } int MacDescription::GetHashCode() { int hash = 31 * m_macType; hash += 31 * m_keySize; hash += 31 * m_ivSize; hash += 31 * m_hmacEngine; hash += 31 * m_engineType; hash += 31 * m_blockSize; hash += 31 * m_roundCount; hash += 31 * m_kdfEngine; return hash; } bool MacDescription::Equals(MacDescription &Obj) { if (this->GetHashCode() != Obj.GetHashCode()) return false; return true; } NAMESPACE_PROCESSINGEND
22.086957
66
0.745079
Steppenwolfe65
8997b298451bb1e58de3c8a7830040160a7c6ace
2,028
cpp
C++
Src/Plugin/Wonderland/WonderlandPlugin.cpp
prophecy/Pillar
a60b07857e66312ee94d69678b1ca8c97b1a19eb
[ "MIT" ]
2
2017-07-19T03:23:27.000Z
2018-01-16T04:26:53.000Z
Src/Plugin/Wonderland/WonderlandPlugin.cpp
prophecy/Pillar
a60b07857e66312ee94d69678b1ca8c97b1a19eb
[ "MIT" ]
null
null
null
Src/Plugin/Wonderland/WonderlandPlugin.cpp
prophecy/Pillar
a60b07857e66312ee94d69678b1ca8c97b1a19eb
[ "MIT" ]
null
null
null
/* * This source file is part of Wonderland, the C++ Cross-platform middleware for game * * For the latest information, see https://github.com/prophecy/Wonderland * * The MIT License (MIT) * Copyright (c) 2015 Adawat Chanchua * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include "WonderlandPlugin.h" #include "IScene.h" #include "SceneManager.h" #include "Utility/Log/Log.h" #include "Florist.h" void WonderlandPlugin::Create(WonderPtr<IApplication> application) { // Create log Log::GetPtr()->Create("Wonderland.log"); LogDebug("Create WonderlandPlugin"); // Application this->application = application; // Scene manager application->sceneManager = CreateElement<SceneManager>().To<ISceneManager>(); // Create application application->Create(); application->sceneManager->GetCurrentScene()->Create(); } void WonderlandPlugin::Update() { application->sceneManager->OnChangeScene(); application->sceneManager->GetCurrentScene()->taskManager->UpdateTasks(); }
34.965517
85
0.751972
prophecy
89a3b1a7c81e269e6830dee582b3d8210e6fa052
315
cxx
C++
example/wake_ptr.cxx
usagi/usagi
2d57d21eeb92eadfdf4154a3e470aebfc3e388e5
[ "MIT" ]
2
2016-11-20T04:59:17.000Z
2017-02-13T01:44:37.000Z
example/wake_ptr.cxx
usagi/usagi
2d57d21eeb92eadfdf4154a3e470aebfc3e388e5
[ "MIT" ]
3
2015-09-28T12:00:02.000Z
2015-09-28T12:03:21.000Z
example/wake_ptr.cxx
usagi/usagi
2d57d21eeb92eadfdf4154a3e470aebfc3e388e5
[ "MIT" ]
3
2017-07-02T06:09:47.000Z
2018-07-09T01:00:57.000Z
#include <usagi/memory/wake_ptr.hxx> #include <vector> #include <iostream> auto main() -> int { using t = std::vector<int>; auto b = std::make_shared< t >(); using namespace usagi::memory; wake_ptr< t > a = b; a->emplace_back( 123 ); a->emplace_back( 456 ); std::cout << a->front() << (*a)[1]; }
18.529412
37
0.6
usagi
89aa380bf9a9743deae08388709215a54b70e8cb
12,846
cpp
C++
MACHINATH/MACHINATH/sound.cpp
susajin/MACHINATH
1e75097f86218f143411885240bbcf211a6e9c99
[ "MIT" ]
null
null
null
MACHINATH/MACHINATH/sound.cpp
susajin/MACHINATH
1e75097f86218f143411885240bbcf211a6e9c99
[ "MIT" ]
null
null
null
MACHINATH/MACHINATH/sound.cpp
susajin/MACHINATH
1e75097f86218f143411885240bbcf211a6e9c99
[ "MIT" ]
null
null
null
//============================================================================= // // �T�E���h���� [sound.cpp] // //============================================================================= #include <XAudio2.h> #include <mmsystem.h> #include "sound.h" #include "common.h" #pragma comment (lib, "xaudio2.lib") #pragma comment (lib, "winmm.lib") //***************************************************************************** // sound parameters //***************************************************************************** struct SOUNDPARAM { const char *pFilename; // path to sound file int nCntLoop; // -1 == LOOP EDNLESSLY, 0 == DONT LOOP, >= 1 == LOOP }; //***************************************************************************** // methods //***************************************************************************** HRESULT CheckChunk(HANDLE hFile, DWORD format, DWORD *pChunkSize, DWORD *pChunkDataPosition); HRESULT ReadChunkData(HANDLE hFile, void *pBuffer, DWORD dwBuffersize, DWORD dwBufferoffset); void UpdateFadeSound(); //***************************************************************************** // globals //***************************************************************************** IXAudio2 *g_pXAudio2 = NULL; // XAudio2 interface IXAudio2MasteringVoice *g_pMasteringVoice = NULL; // master voice IXAudio2SourceVoice *g_apSourceVoice[SOUND_LABEL_MAX] = {}; // source voice BYTE *g_apDataAudio[SOUND_LABEL_MAX] = {}; DWORD g_aSizeAudio[SOUND_LABEL_MAX] = {}; float g_DeltaTime; float g_targetTime, g_targetVolume; bool g_FadeFlag; float g_curVolume; SOUND_LABEL g_curFadeSound; // sound files to load SOUNDPARAM g_aParam[SOUND_LABEL_MAX] = { {"asset/sound/BGM/title.wav", -1}, {"asset/sound/BGM/game.wav", -1}, {"asset/sound/SE/pickup.wav", 0}, {"asset/sound/SE/get_ready.wav", 0}, {"asset/sound/SE/one.wav", 0}, {"asset/sound/SE/two.wav", 0}, {"asset/sound/SE/three.wav", 0}, {"asset/sound/SE/go.wav", 0}, {"asset/sound/SE/title_pushbutton2.wav", 0}, {"asset/sound/SE/title_noise.wav", 0}, {"asset/sound/SE/slowmo_start.wav", 0}, {"asset/sound/SE/slowmo_end.wav", 0}, {"asset/sound/SE/QTE_fail.wav", 0}, {"asset/sound/SE/QTE_success.wav", 0}, {"asset/sound/SE/QTE_standby.wav", 0}, {"asset/sound/SE/explosion.wav", 0}, {"asset/sound/SE/gate_open.wav", 0}, }; //============================================================================= // init sound //============================================================================= HRESULT InitSound(HWND hWnd) { g_DeltaTime = 0; g_FadeFlag = false; HRESULT hr; // enable multithread for sound playback CoInitializeEx(NULL, COINIT_MULTITHREADED); // initialize xaudio2 hr = XAudio2Create(&g_pXAudio2, 0); if(FAILED(hr)) { MessageBox(hWnd, "Failed to initialize XAudio2!", "Error!", MB_ICONWARNING); CoUninitialize(); return E_FAIL; } // initialize master voice hr = g_pXAudio2->CreateMasteringVoice(&g_pMasteringVoice); if(FAILED(hr)) { MessageBox(hWnd, "Failed to initialize Mastering Voice!", "Error!", MB_ICONWARNING); if(g_pXAudio2) { g_pXAudio2->Release(); g_pXAudio2 = NULL; } CoUninitialize(); return E_FAIL; } // load sound files for(int nCntSound = 0; nCntSound < SOUND_LABEL_MAX; nCntSound++) { HANDLE hFile; DWORD dwChunkSize = 0; DWORD dwChunkPosition = 0; DWORD dwFiletype; WAVEFORMATEXTENSIBLE wfx; XAUDIO2_BUFFER buffer; memset(&wfx, 0, sizeof(WAVEFORMATEXTENSIBLE)); memset(&buffer, 0, sizeof(XAUDIO2_BUFFER)); // load sound files from given path hFile = CreateFile(g_aParam[nCntSound].pFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if(hFile == INVALID_HANDLE_VALUE) { MessageBox(hWnd, "Invalid Handle Value!", "Error!", MB_ICONWARNING); return HRESULT_FROM_WIN32(GetLastError()); } if(SetFilePointer(hFile, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER) { MessageBox(hWnd, "Invalid Set File Pointer!", "Error!", MB_ICONWARNING); return HRESULT_FROM_WIN32(GetLastError()); } hr = CheckChunk(hFile, 'FFIR', &dwChunkSize, &dwChunkPosition); if(FAILED(hr)) { MessageBox(hWnd, "Failed at checking chunk!", "Error!", MB_ICONWARNING); return S_FALSE; } hr = ReadChunkData(hFile, &dwFiletype, sizeof(DWORD), dwChunkPosition); if(FAILED(hr)) { MessageBox(hWnd, "Failed to read chunk data!", "Error!", MB_ICONWARNING); return S_FALSE; } if(dwFiletype != 'EVAW') { MessageBox(hWnd, "Invalid file type!", "Error!", MB_ICONWARNING); return S_FALSE; } // �t�H�[�}�b�g�`�F�b�N hr = CheckChunk(hFile, ' tmf', &dwChunkSize, &dwChunkPosition); if(FAILED(hr)) { MessageBox(hWnd, "�t�H�[�}�b�g�`�F�b�N�Ɏ��s�I(1)", "�x���I", MB_ICONWARNING); return S_FALSE; } hr = ReadChunkData(hFile, &wfx, dwChunkSize, dwChunkPosition); if(FAILED(hr)) { MessageBox(hWnd, "�t�H�[�}�b�g�`�F�b�N�Ɏ��s�I(2)", "�x���I", MB_ICONWARNING); return S_FALSE; } // �I�[�f�B�I�f�[�^�ǂݍ��� hr = CheckChunk(hFile, 'atad', &g_aSizeAudio[nCntSound], &dwChunkPosition); if(FAILED(hr)) { MessageBox(hWnd, "�I�[�f�B�I�f�[�^�ǂݍ��݂Ɏ��s�I(1)", "�x���I", MB_ICONWARNING); return S_FALSE; } g_apDataAudio[nCntSound] = (BYTE*)malloc(g_aSizeAudio[nCntSound]); hr = ReadChunkData(hFile, g_apDataAudio[nCntSound], g_aSizeAudio[nCntSound], dwChunkPosition); if(FAILED(hr)) { MessageBox(hWnd, "�I�[�f�B�I�f�[�^�ǂݍ��݂Ɏ��s�I(2)", "�x���I", MB_ICONWARNING); return S_FALSE; } // create source voice hr = g_pXAudio2->CreateSourceVoice(&g_apSourceVoice[nCntSound], &(wfx.Format)); if(FAILED(hr)) { MessageBox(hWnd, "Failed at creating source voice!", "Error!", MB_ICONWARNING); return S_FALSE; } memset(&buffer, 0, sizeof(XAUDIO2_BUFFER)); buffer.AudioBytes = g_aSizeAudio[nCntSound]; buffer.pAudioData = g_apDataAudio[nCntSound]; buffer.Flags = XAUDIO2_END_OF_STREAM; buffer.LoopCount = g_aParam[nCntSound].nCntLoop; g_apSourceVoice[nCntSound]->SubmitSourceBuffer(&buffer); } return S_OK; } //============================================================================= // uninit sound //============================================================================= void UninitSound(void) { // �ꎞ��~ for(int nCntSound = 0; nCntSound < SOUND_LABEL_MAX; nCntSound++) { if(g_apSourceVoice[nCntSound]) { // �ꎞ��~ g_apSourceVoice[nCntSound]->Stop(0); // �\�[�X�{�C�X�̔j�� g_apSourceVoice[nCntSound]->DestroyVoice(); g_apSourceVoice[nCntSound] = NULL; // �I�[�f�B�I�f�[�^�̊J�� free(g_apDataAudio[nCntSound]); g_apDataAudio[nCntSound] = NULL; } } // �}�X�^�[�{�C�X�̔j�� g_pMasteringVoice->DestroyVoice(); g_pMasteringVoice = NULL; if(g_pXAudio2) { // XAudio2�I�u�W�F�N�g�̊J�� g_pXAudio2->Release(); g_pXAudio2 = NULL; } // COM���C�u�����̏I������ CoUninitialize(); } //============================================================================= // Update Sound //============================================================================= void UpdateSound(void) { if (g_FadeFlag) UpdateFadeSound(); } //============================================================================= // Play Sound //============================================================================= HRESULT PlaySound(SOUND_LABEL label, float volume) { XAUDIO2_VOICE_STATE xa2state; XAUDIO2_BUFFER buffer; // init buffer memset(&buffer, 0, sizeof(XAUDIO2_BUFFER)); buffer.AudioBytes = g_aSizeAudio[label]; buffer.pAudioData = g_apDataAudio[label]; buffer.Flags = XAUDIO2_END_OF_STREAM; buffer.LoopCount = g_aParam[label].nCntLoop; g_apSourceVoice[label]->GetState(&xa2state); if(xa2state.BuffersQueued != 0) { g_apSourceVoice[label]->Stop(0); g_apSourceVoice[label]->FlushSourceBuffers(); } // submit source buffer g_apSourceVoice[label]->SubmitSourceBuffer(&buffer); // play sound g_apSourceVoice[label]->Start(0); // set volume SetVolume(label, volume); return S_OK; } //============================================================================= // Stop Sound //============================================================================= void StopSound(SOUND_LABEL label) { XAUDIO2_VOICE_STATE xa2state; // ��Ԏ擾 g_apSourceVoice[label]->GetState(&xa2state); if(xa2state.BuffersQueued != 0) {// �Đ��� // �ꎞ��~ g_apSourceVoice[label]->Stop(0); // �I�[�f�B�I�o�b�t�@�̍폜 g_apSourceVoice[label]->FlushSourceBuffers(); } } //============================================================================= // Stop all sound //============================================================================= void StopSound(void) { // �ꎞ��~ for(int nCntSound = 0; nCntSound < SOUND_LABEL_MAX; nCntSound++) { if(g_apSourceVoice[nCntSound]) { // �ꎞ��~ g_apSourceVoice[nCntSound]->Stop(0); } } } //============================================================================= // check chunk //============================================================================= HRESULT CheckChunk(HANDLE hFile, DWORD format, DWORD *pChunkSize, DWORD *pChunkDataPosition) { HRESULT hr = S_OK; DWORD dwRead; DWORD dwChunkType; DWORD dwChunkDataSize; DWORD dwRIFFDataSize = 0; DWORD dwFileType; DWORD dwBytesRead = 0; DWORD dwOffset = 0; if(SetFilePointer(hFile, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {// �t�@�C���|�C���^��擪�Ɉړ� return HRESULT_FROM_WIN32(GetLastError()); } while(hr == S_OK) { if(ReadFile(hFile, &dwChunkType, sizeof(DWORD), &dwRead, NULL) == 0) {// �`�����N�̓ǂݍ��� hr = HRESULT_FROM_WIN32(GetLastError()); } if(ReadFile(hFile, &dwChunkDataSize, sizeof(DWORD), &dwRead, NULL) == 0) {// �`�����N�f�[�^�̓ǂݍ��� hr = HRESULT_FROM_WIN32(GetLastError()); } switch(dwChunkType) { case 'FFIR': dwRIFFDataSize = dwChunkDataSize; dwChunkDataSize = 4; if(ReadFile(hFile, &dwFileType, sizeof(DWORD), &dwRead, NULL) == 0) {// �t�@�C���^�C�v�̓ǂݍ��� hr = HRESULT_FROM_WIN32(GetLastError()); } break; default: if(SetFilePointer(hFile, dwChunkDataSize, NULL, FILE_CURRENT) == INVALID_SET_FILE_POINTER) {// �t�@�C���|�C���^��`�����N�f�[�^���ړ� return HRESULT_FROM_WIN32(GetLastError()); } } dwOffset += sizeof(DWORD) * 2; if(dwChunkType == format) { *pChunkSize = dwChunkDataSize; *pChunkDataPosition = dwOffset; return S_OK; } dwOffset += dwChunkDataSize; if(dwBytesRead >= dwRIFFDataSize) { return S_FALSE; } } return S_OK; } //============================================================================= // read cunk data //============================================================================= HRESULT ReadChunkData(HANDLE hFile, void *pBuffer, DWORD dwBuffersize, DWORD dwBufferoffset) { DWORD dwRead; if(SetFilePointer(hFile, dwBufferoffset, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER) {// �t�@�C���|�C���^��w��ʒu�܂ňړ� return HRESULT_FROM_WIN32(GetLastError()); } if(ReadFile(hFile, pBuffer, dwBuffersize, &dwRead, NULL) == 0) {// �f�[�^�̓ǂݍ��� return HRESULT_FROM_WIN32(GetLastError()); } return S_OK; } HRESULT SetVolume(SOUND_LABEL LABEL,float volume,UINT32 OperationSet) { return g_apSourceVoice[LABEL]->SetVolume(volume * AUDIO_MASTER, OperationSet); } float GetVolume(SOUND_LABEL label) { float vol; g_apSourceVoice[label]->GetVolume(&vol); return vol; } void UpdateFadeSound() { if (g_DeltaTime < g_targetTime) { SetVolume(g_curFadeSound, g_targetVolume * (g_DeltaTime/ g_targetTime) + g_curVolume * ((g_targetTime - g_DeltaTime )/ g_targetTime)); g_DeltaTime += (1.0f / 60.0f); } else { SetVolume(g_curFadeSound, g_targetVolume); if (g_targetVolume == 0) { StopSound(g_curFadeSound); } g_DeltaTime = 0; g_FadeFlag = false; } } void StartFade(SOUND_LABEL label, float targetVolume, float targetTime) { // return if a sound is currently fading if (g_FadeFlag) return; g_curFadeSound = label; g_apSourceVoice[label]->GetVolume(&g_curVolume); g_targetVolume = targetVolume; g_targetTime = targetTime; g_FadeFlag = true; } void SetPlaybackSpeed(SOUND_LABEL label, float speed) { // return if given speed is the same as currently set float value; g_apSourceVoice[label]->GetFrequencyRatio(&value); if (value == speed) return; // set playback speed and pitch g_apSourceVoice[label]->SetFrequencyRatio(speed, 0); }
27.74514
114
0.553324
susajin
89af011de156c8e203dc82c575ccc2e901652609
1,993
hpp
C++
src/tests/sequential/cusum.hpp
ropufu/aftermath
ab9364c41672a188879d84ebebb5a23f2d6641ec
[ "MIT" ]
null
null
null
src/tests/sequential/cusum.hpp
ropufu/aftermath
ab9364c41672a188879d84ebebb5a23f2d6641ec
[ "MIT" ]
null
null
null
src/tests/sequential/cusum.hpp
ropufu/aftermath
ab9364c41672a188879d84ebebb5a23f2d6641ec
[ "MIT" ]
null
null
null
#ifndef ROPUFU_AFTERMATH_TESTS_SEQUENTIAL_CUSUM_HPP_INCLUDED #define ROPUFU_AFTERMATH_TESTS_SEQUENTIAL_CUSUM_HPP_INCLUDED #include <doctest/doctest.h> #include "../core.hpp" #include "../../ropufu/random/binomial_sampler.hpp" #include "../../ropufu/random/normal_sampler_512.hpp" #include "../../ropufu/random/uniform_int_sampler.hpp" #include "../../ropufu/sequential/cusum.hpp" #include <cstddef> // std::size_t #include <cstdint> // std::int64_t #include <random> // std::mt19937_64 #include <string> // std::string #include <vector> // std::vector #ifdef ROPUFU_TMP_TEST_TYPES #undef ROPUFU_TMP_TEST_TYPES #endif #define ROPUFU_TMP_TEST_TYPES \ ropufu::aftermath::random::binomial_sampler<std::mt19937_64, std::int64_t>, \ ropufu::aftermath::random::normal_sampler_512<std::mt19937_64, double>, \ ropufu::aftermath::random::uniform_int_sampler<std::mt19937_64, std::int64_t> \ #ifndef ROPUFU_NO_JSON TEST_CASE_TEMPLATE("testing cusum json", sampler_type, ROPUFU_TMP_TEST_TYPES) { using value_type = typename sampler_type::value_type; using cusum_type = ropufu::aftermath::sequential::cusum<value_type>; cusum_type cusum{}; std::string xxx {}; std::string yyy {}; ropufu::tests::does_json_round_trip(cusum, xxx, yyy); CHECK_EQ(xxx, yyy); } // TEST_CASE_TEMPLATE(...) #endif TEST_CASE_TEMPLATE("testing cusum accumulation", sampler_type, ROPUFU_TMP_TEST_TYPES) { using value_type = typename sampler_type::value_type; using cusum_type = ropufu::aftermath::sequential::cusum<value_type>; cusum_type cusum{}; std::vector<value_type> process = {2, 3, -7, 1, 2, 3, 4, 5, 5, -5}; value_type r = 0; value_type s = 0; for (value_type x : process) { r = s; s = cusum.observe(x); } // for (...) CHECK_EQ(r, 20); CHECK_EQ(s, 15); } // TEST_CASE_TEMPLATE(...) #endif // ROPUFU_AFTERMATH_TESTS_SEQUENTIAL_CUSUM_HPP_INCLUDED
31.634921
85
0.690416
ropufu
89b2197cab272b06bd62ceea4dbd7ab38ed77dc4
1,774
cc
C++
archetype/TestWrappedOutput.cc
gitosaurus/archetype
849cd50e653adab6e5ca6f23d5350217a8a4d025
[ "MIT" ]
6
2015-05-04T17:18:54.000Z
2021-01-24T16:23:56.000Z
archetype/TestWrappedOutput.cc
gitosaurus/archetype
849cd50e653adab6e5ca6f23d5350217a8a4d025
[ "MIT" ]
null
null
null
archetype/TestWrappedOutput.cc
gitosaurus/archetype
849cd50e653adab6e5ca6f23d5350217a8a4d025
[ "MIT" ]
null
null
null
// // TestWrappedOutput.cpp // archetype // // Created by Derek Jones on 9/21/14. // Copyright (c) 2014 Derek Jones. All rights reserved. // #include <iostream> #include <string> #include <sstream> #include <deque> #include <iterator> #include "TestWrappedOutput.hh" #include "TestRegistry.hh" #include "StringOutput.hh" #include "WrappedOutput.hh" using namespace std; namespace archetype { ARCHETYPE_TEST_REGISTER(TestWrappedOutput); void TestWrappedOutput::testBasicWrap_() { UserOutput user_soutput{new StringOutput}; StringOutput& strout(*dynamic_cast<StringOutput*>(user_soutput.get())); UserOutput user_output{new WrappedOutput{user_soutput}}; WrappedOutput& wrout(*dynamic_cast<WrappedOutput*>(user_output.get())); wrout.setMaxColumns(10); string utterance = "Now is the time for all good men to come to the aid of their country."; user_output->put(utterance); user_output->endLine(); string result = strout.getOutput(); out() << result; istringstream istr(result); string line; deque<string> lines; while (getline(istr, line)) { ARCHETYPE_TEST(line.size() <= 10); lines.push_back(line); } ARCHETYPE_TEST(lines.size() > 1); // Paste it back together and make sure it matches the original ostringstream back_out; copy(lines.begin(), lines.end(), ostream_iterator<string>(back_out, " ")); string back_out_s = back_out.str(); back_out_s.resize(back_out_s.size() - 1); ARCHETYPE_TEST_EQUAL(back_out_s, utterance); out() << "TestWrappedOutput finished." << endl; } void TestWrappedOutput::runTests_() { testBasicWrap_(); } }
31.122807
99
0.654453
gitosaurus
89b5081b750a5e5ac1fcd4fe39900575790b25e8
404
cpp
C++
pow_sha1/src/_main.cpp
mzk84/phi
69c0535eff9f301daaa67e80aa01f39d7ace2b4b
[ "Unlicense" ]
null
null
null
pow_sha1/src/_main.cpp
mzk84/phi
69c0535eff9f301daaa67e80aa01f39d7ace2b4b
[ "Unlicense" ]
null
null
null
pow_sha1/src/_main.cpp
mzk84/phi
69c0535eff9f301daaa67e80aa01f39d7ace2b4b
[ "Unlicense" ]
null
null
null
#include "_includes.h" #include "mzk84_commons.h" #include "PoW_SHA1.h" int main() { std::cout << "\n************************************************************\n"; std::cout << "Proof of Work SHA1 Test\n\n"; size_t prefix_len = 64; size_t difficulty = 6; for (auto i = 0; i < 5; i++) { std::string prefix = mzk84::get_random_string(prefix_len); PoW_SHA1_Runner(prefix, difficulty, 1); } }
23.764706
81
0.554455
mzk84
89b63e39c6bf70d33d9364c1447d494aaa788823
971
hpp
C++
src/LoadInformations.hpp
jkalter11/freeshop
c7b1858ed713732b8ff9afa116f05a1ed9a4d4c3
[ "MIT" ]
1
2021-05-11T10:40:14.000Z
2021-05-11T10:40:14.000Z
src/LoadInformations.hpp
jkalter11/freeshop
c7b1858ed713732b8ff9afa116f05a1ed9a4d4c3
[ "MIT" ]
null
null
null
src/LoadInformations.hpp
jkalter11/freeshop
c7b1858ed713732b8ff9afa116f05a1ed9a4d4c3
[ "MIT" ]
2
2021-06-05T15:51:05.000Z
2022-02-03T20:44:33.000Z
#ifndef FREESHOP_LOADINFORMATIONS_HPP #define FREESHOP_LOADINFORMATIONS_HPP #include <cpp3ds/Graphics/Drawable.hpp> #include <cpp3ds/Graphics/Text.hpp> #include <cpp3ds/Window/Event.hpp> #include "TweenObjects.hpp" #include <TweenEngine/Tween.h> #include <TweenEngine/TweenManager.h> namespace FreeShop { class LoadInformations : public cpp3ds::Drawable, public util3ds::TweenTransformable<cpp3ds::Transformable> { public: void update(float delta); LoadInformations(); ~LoadInformations(); static LoadInformations& getInstance(); void updateLoadingPercentage(int newPercentage); void setStatus(const std::string& message); void reset(); protected: virtual void draw(cpp3ds::RenderTarget& target, cpp3ds::RenderStates states) const; private: cpp3ds::Text m_textLoadingPercentage; util3ds::TweenText m_textStatus; int m_loadingPercentage; TweenEngine::TweenManager m_tweenManager; }; } // namespace FreeShop #endif // FREESHOP_LOADINFORMATIONS_HPP
23.119048
109
0.797116
jkalter11
89b846212984ab98ac5310f8acd9ec1139074a7c
1,978
cpp
C++
src/tt.cpp
am1w1zz/CppLearn
16db21cb5cc9ca14e488f4f40923b756de18e354
[ "MIT" ]
null
null
null
src/tt.cpp
am1w1zz/CppLearn
16db21cb5cc9ca14e488f4f40923b756de18e354
[ "MIT" ]
null
null
null
src/tt.cpp
am1w1zz/CppLearn
16db21cb5cc9ca14e488f4f40923b756de18e354
[ "MIT" ]
null
null
null
#include<iostream> #include <vector> #include "tt.h" struct aa { void f(int x ,int y) { std::cout<<"void"<<std::endl; return ; } void f(int x,int y )const { std::cout<<"int"<<std::endl; return ; } ~aa() { std::cout<<"aa"<<std::endl; } }; struct bb : aa { ~bb(){ std::cout<<"bb"<<std::endl; } }; struct cc { int v; cc(int v) :v(v) { } }; void func(); union obj{ union obj* obj; char _M_client_data[1]; }; struct node { node* next; int val; }; int main() { // const aa a; // a.f(1,2); // bb a; // std::cout<<sizeof(aa); // f(1,2); // f(1,2); // cc a(1); // cc b(2); // cc& c = a; // std::cout<<c.v<<std::endl; // c = b; // std::cout<<c.v<<std::endl; // std::cout<<a.v<<std::endl; // std::cout<<b.v<<std::endl; // func(); //1 // extern int num; // printf("%d",num); //2 // return 0; // MyTemplate<int> MyIntTemplate; // auto i = MyIntTemplate.GetMemebr(); // obj a; // obj b; // a.obj = &b; // b._M_client_data[0] = 'a'; // std::cout<<sizeof(a)<<std::endl; // std::cout<<sizeof(b)<<std::endl; // } int a[] = {0x01020304,2019}; int* b = a; char* c = (char*)&a[0]; // printf("b+1:%d\n",*(b+1)); // printf("c+1:%d\n",*(c)); // return 0; std::vector<node*> list_node {new node(),new node(),new node(), new node()}; node* n1 = new node(); list_node[0]->next = n1; for(auto& i : list_node){ std::cout<<i<<std::endl; } // std::cout<<list_node[0]->next<<std::endl; std::cout<<std::endl; list_node[0] = list_node[0]->next; std::cout<<std::endl; // std::cout<<list_node[0]<<std::endl; for(auto& i : list_node){ std::cout<<i<<std::endl; } aa* a1 = new aa(); bb* b1 = new bb(); a1 = b1; } // int num = 3; // void func(){ // printf("%d\n",num); // }
18.314815
80
0.455005
am1w1zz
89bdb539249e2db4bad0da72bebba8cbc08e72fc
2,550
hpp
C++
src/solvers/temporal/point_algebra/QualitativeTimePoint.hpp
tomcreutz/planning-templ
55e35ede362444df9a7def6046f6df06851fe318
[ "BSD-3-Clause" ]
1
2022-03-31T12:15:15.000Z
2022-03-31T12:15:15.000Z
src/solvers/temporal/point_algebra/QualitativeTimePoint.hpp
tomcreutz/planning-templ
55e35ede362444df9a7def6046f6df06851fe318
[ "BSD-3-Clause" ]
null
null
null
src/solvers/temporal/point_algebra/QualitativeTimePoint.hpp
tomcreutz/planning-templ
55e35ede362444df9a7def6046f6df06851fe318
[ "BSD-3-Clause" ]
1
2021-12-29T10:38:07.000Z
2021-12-29T10:38:07.000Z
#ifndef TEMPL_SOLVERS_TEMPORAL_POINT_ALGEBRA_QUALITATIVE_TIME_POINT_HPP #define TEMPL_SOLVERS_TEMPORAL_POINT_ALGEBRA_QUALITATIVE_TIME_POINT_HPP #include <graph_analysis/VertexRegistration.hpp> #include "TimePoint.hpp" namespace templ { namespace solvers { namespace temporal { namespace point_algebra { /** * \class QualitativeTimePoint * \details A QualitativeTimePoint represent a labelled timepoint, * which allows to formulate qualitative timepoint relationships * * A QualitativeTimePoint can have one or more aliases and identical * aliases identify equal timepoints, which will allow for later * constraint checking * */ class QualitativeTimePoint : public TimePoint { std::vector<TimePoint::Label> mAliases; static const graph_analysis::VertexRegistration< QualitativeTimePoint > __attribute__((used)) msRegistration; public: typedef shared_ptr<QualitativeTimePoint> Ptr; /** * Default constructor * \param label (main) label for this Timepoint */ QualitativeTimePoint(const TimePoint::Label& label = ""); /** * Create instance of QualitativeTimePoint */ static QualitativeTimePoint::Ptr getInstance(const TimePoint::Label& label); /** * Add an alias for this timepoint * \param alias Alias */ void addAlias(const TimePoint::Label& alias); /** * Check if the given label is an alias (or the actual label) of this * QualitativeTimePoint * \return True if label is an alias, false otherwise o*/ bool isAlias(const TimePoint::Label& label) const; /** * Check equality of two QualitativeTimePoint instances * \return True if they are equal, false otherwise */ virtual bool operator==(const QualitativeTimePoint& other) const; /** * Check if two QualitativeTimePoint instances are distinct * \return True if they are distinct, false otherwise */ bool operator!=(const QualitativeTimePoint& other) const { return ! (*this == other); } /** * Get class name */ virtual std::string getClassName() const { return "QualitativeTimePoint"; } /** * Stringify object */ virtual std::string toString(uint32_t indent) const { return std::string(indent,' ') + mLabel; } private: virtual Vertex* getClone() const { return new QualitativeTimePoint(*this); } }; } // end namespace point_algebra } // end namespace temporal } // end namespace solvers } // end namespace templ #endif // TEMPL_SOLVERS_TEMPORAL_POINT_ALGEBRA_QUALITATIVE_TIME_POINT_HPP
29.651163
113
0.717255
tomcreutz
89c1670532dfc7e5456bbf05a770a97ea580a086
16,394
cc
C++
network/slirp/bootp.cc
rahimazizarab/sand-dyn75
f5462445ce53b9b769e295928cc1e9203bce78b1
[ "BSD-2-Clause" ]
null
null
null
network/slirp/bootp.cc
rahimazizarab/sand-dyn75
f5462445ce53b9b769e295928cc1e9203bce78b1
[ "BSD-2-Clause" ]
null
null
null
network/slirp/bootp.cc
rahimazizarab/sand-dyn75
f5462445ce53b9b769e295928cc1e9203bce78b1
[ "BSD-2-Clause" ]
null
null
null
///////////////////////////////////////////////////////////////////////// // $Id: bootp.cc 12269 2014-04-02 17:38:09Z vruppert $ ///////////////////////////////////////////////////////////////////////// /* * BOOTP/DHCP server (ported from Qemu) * Bochs additions: parameter list and some other options * * Copyright (c) 2004 Fabrice Bellard * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "slirp.h" #if BX_NETWORKING && BX_NETMOD_SLIRP /* XXX: only DHCP is supported */ #define LEASE_TIME (24 * 3600) typedef struct { int msg_type; bx_bool found_srv_id; struct in_addr req_addr; uint8_t *params; uint8_t params_len; char *hostname; uint32_t lease_time; } dhcp_options_t; static const uint8_t rfc1533_cookie[] = { RFC1533_COOKIE }; #ifdef DEBUG #define DPRINTF(fmt, ...) \ do if (slirp_debug & DBG_CALL) { fprintf(dfd, fmt, ## __VA_ARGS__); fflush(dfd); } while (0) #else #define DPRINTF(fmt, ...) do{}while(0) #endif static BOOTPClient *get_new_addr(Slirp *slirp, struct in_addr *paddr, const uint8_t *macaddr) { BOOTPClient *bc; int i; for(i = 0; i < NB_BOOTP_CLIENTS; i++) { bc = &slirp->bootp_clients[i]; if (!bc->allocated || !memcmp(macaddr, bc->macaddr, 6)) goto found; } return NULL; found: bc = &slirp->bootp_clients[i]; bc->allocated = 1; paddr->s_addr = slirp->vdhcp_startaddr.s_addr + htonl(i); return bc; } static BOOTPClient *request_addr(Slirp *slirp, const struct in_addr *paddr, const uint8_t *macaddr) { uint32_t req_addr = ntohl(paddr->s_addr); uint32_t dhcp_addr = ntohl(slirp->vdhcp_startaddr.s_addr); BOOTPClient *bc; if (req_addr >= dhcp_addr && req_addr < (dhcp_addr + NB_BOOTP_CLIENTS)) { bc = &slirp->bootp_clients[req_addr - dhcp_addr]; if (!bc->allocated || !memcmp(macaddr, bc->macaddr, 6)) { bc->allocated = 1; return bc; } } return NULL; } static BOOTPClient *find_addr(Slirp *slirp, struct in_addr *paddr, const uint8_t *macaddr) { BOOTPClient *bc; int i; for(i = 0; i < NB_BOOTP_CLIENTS; i++) { if (!memcmp(macaddr, slirp->bootp_clients[i].macaddr, 6)) goto found; } return NULL; found: bc = &slirp->bootp_clients[i]; bc->allocated = 1; paddr->s_addr = slirp->vdhcp_startaddr.s_addr + htonl(i); return bc; } static void dhcp_decode(Slirp *slirp, const struct bootp_t *bp, dhcp_options_t *opts) { const uint8_t *p, *p_end; uint16_t defsize, maxsize; int len, tag; char msg[80]; memset(opts, 0, sizeof(dhcp_options_t)); p = bp->bp_vend; p_end = p + DHCP_OPT_LEN; if (memcmp(p, rfc1533_cookie, 4) != 0) return; p += 4; while (p < p_end) { tag = p[0]; if (tag == RFC1533_PAD) { p++; } else if (tag == RFC1533_END) { break; } else { p++; if (p >= p_end) break; len = *p++; DPRINTF("dhcp: tag=%d len=%d\n", tag, len); switch(tag) { case RFC2132_MSG_TYPE: if (len >= 1) opts->msg_type = p[0]; break; case RFC2132_REQ_ADDR: if (len >= 4) { memcpy(&(opts->req_addr.s_addr), p, 4); } break; case RFC2132_SRV_ID: if (len >= 4) { if (!memcmp(p, &slirp->vhost_addr, 4)) { opts->found_srv_id = 1; } } break; case RFC2132_PARAM_LIST: if (len >= 1) { opts->params = (uint8_t*)malloc(len); memcpy(opts->params, p, len); opts->params_len = len; } break; case RFC1533_HOSTNAME: if (len >= 1) { opts->hostname = (char*)malloc(len + 1); memcpy(opts->hostname, p, len); opts->hostname[len] = 0; } break; case RFC2132_LEASE_TIME: if (len == 4) { memcpy(&opts->lease_time, p, len); } break; case RFC2132_MAX_SIZE: if (len == 2) { memcpy(&maxsize, p, len); defsize = sizeof(struct bootp_t) - sizeof(struct ip) - sizeof(struct udphdr); if (ntohs(maxsize) < defsize) { sprintf(msg, "DHCP server: RFB2132_MAX_SIZE=%u not supported yet", ntohs(maxsize)); slirp_warning(slirp, msg); } } break; default: sprintf(msg, "DHCP server: option %d not supported yet", tag); slirp_warning(slirp, msg); break; } p += len; } } if ((opts->msg_type == DHCPREQUEST) && (opts->req_addr.s_addr == htonl(0L)) && bp->bp_ciaddr.s_addr) { memcpy(&(opts->req_addr.s_addr), &bp->bp_ciaddr, 4); } } static void bootp_reply(Slirp *slirp, const struct bootp_t *bp) { BOOTPClient *bc = NULL; struct mbuf *m; struct bootp_t *rbp; struct sockaddr_in saddr, daddr; struct in_addr bcast_addr; int val; uint8_t *q, *pp, plen, dhcp_def_params_len; uint8_t client_ethaddr[ETH_ALEN]; uint8_t dhcp_def_params[8]; bx_bool dhcp_def_params_valid = 0; dhcp_options_t dhcp_opts; size_t spaceleft; char msg[80]; /* extract exact DHCP msg type */ dhcp_decode(slirp, bp, &dhcp_opts); DPRINTF("bootp packet op=%d msgtype=%d", bp->bp_op, dhcp_opts.msg_type); if (dhcp_opts.req_addr.s_addr != htonl(0L)) DPRINTF(" req_addr=%08x\n", ntohl(dhcp_opts.req_addr.s_addr)); else DPRINTF("\n"); if (dhcp_opts.msg_type == 0) dhcp_opts.msg_type = DHCPREQUEST; /* Force reply for old BOOTP clients */ if (dhcp_opts.msg_type != DHCPDISCOVER && dhcp_opts.msg_type != DHCPREQUEST) return; /* Get client's hardware address from bootp request */ memcpy(client_ethaddr, bp->bp_hwaddr, ETH_ALEN); m = m_get(slirp); if (!m) { return; } m->m_data += IF_MAXLINKHDR; rbp = (struct bootp_t *)m->m_data; m->m_data += sizeof(struct udpiphdr); memset(rbp, 0, sizeof(struct bootp_t)); dhcp_def_params_len = 0; if (dhcp_opts.msg_type == DHCPDISCOVER) { if (dhcp_opts.req_addr.s_addr != htonl(0L)) { bc = request_addr(slirp, &dhcp_opts.req_addr, client_ethaddr); if (bc) { daddr.sin_addr = dhcp_opts.req_addr; } } if (!bc) { new_addr: bc = get_new_addr(slirp, &daddr.sin_addr, client_ethaddr); if (!bc) { DPRINTF("no address left\n"); return; } } memcpy(bc->macaddr, client_ethaddr, ETH_ALEN); dhcp_def_params[0] = RFC2132_LEASE_TIME; dhcp_def_params[1] = RFC2132_SRV_ID; dhcp_def_params_len = 2; if (*slirp->client_hostname || (dhcp_opts.hostname != NULL)) { dhcp_def_params[dhcp_def_params_len++] = RFC1533_HOSTNAME; } dhcp_def_params_valid = 1; } else if (dhcp_opts.req_addr.s_addr != htonl(0L)) { bc = request_addr(slirp, &dhcp_opts.req_addr, client_ethaddr); if (bc) { daddr.sin_addr = dhcp_opts.req_addr; memcpy(bc->macaddr, client_ethaddr, ETH_ALEN); dhcp_def_params[0] = RFC2132_LEASE_TIME; dhcp_def_params_len = 1; if (!dhcp_opts.found_srv_id) { dhcp_def_params[dhcp_def_params_len++] = RFC2132_SRV_ID; } dhcp_def_params_valid = 1; } else { /* DHCPNAKs should be sent to broadcast */ daddr.sin_addr.s_addr = 0xffffffff; } } else { bc = find_addr(slirp, &daddr.sin_addr, bp->bp_hwaddr); if (!bc) { /* if never assigned, behaves as if it was already assigned (windows fix because it remembers its address) */ goto new_addr; } } /* Update ARP table for this IP address */ arp_table_add(slirp, daddr.sin_addr.s_addr, client_ethaddr); saddr.sin_addr = slirp->vhost_addr; saddr.sin_port = htons(BOOTP_SERVER); daddr.sin_port = htons(BOOTP_CLIENT); rbp->bp_op = BOOTP_REPLY; rbp->bp_xid = bp->bp_xid; rbp->bp_htype = 1; rbp->bp_hlen = 6; memcpy(rbp->bp_hwaddr, bp->bp_hwaddr, ETH_ALEN); rbp->bp_yiaddr = daddr.sin_addr; /* Client IP address */ rbp->bp_siaddr = saddr.sin_addr; /* Server IP address */ q = rbp->bp_vend; memcpy(q, rfc1533_cookie, 4); q += 4; if (bc) { DPRINTF("%s addr=%08x\n", (dhcp_opts.msg_type == DHCPDISCOVER) ? "offered" : "ack'ed", ntohl(daddr.sin_addr.s_addr)); if (dhcp_opts.msg_type == DHCPDISCOVER) { *q++ = RFC2132_MSG_TYPE; *q++ = 1; *q++ = DHCPOFFER; } else /* DHCPREQUEST */ { *q++ = RFC2132_MSG_TYPE; *q++ = 1; *q++ = DHCPACK; } if (slirp->bootp_filename) snprintf((char *)rbp->bp_file, sizeof(rbp->bp_file), "%s", slirp->bootp_filename); strcpy((char *)rbp->bp_sname, "slirp"); pp = dhcp_opts.params; plen = dhcp_opts.params_len; while (1) { while (plen-- > 0) { spaceleft = sizeof(rbp->bp_vend) - (q - rbp->bp_vend); if (spaceleft < 6) break; switch (*pp++) { case RFC1533_NETMASK: *q++ = RFC1533_NETMASK; *q++ = 4; memcpy(q, &slirp->vnetwork_mask, 4); q += 4; break; case RFC1533_GATEWAY: if (!slirp->restricted) { *q++ = RFC1533_GATEWAY; *q++ = 4; memcpy(q, &saddr.sin_addr, 4); q += 4; } break; case RFC1533_DNS: if (!slirp->restricted) { *q++ = RFC1533_DNS; *q++ = 4; memcpy(q, &slirp->vnameserver_addr, 4); q += 4; } break; case RFC1533_HOSTNAME: val = 0; if (*slirp->client_hostname) { val = strlen(slirp->client_hostname); } else if (dhcp_opts.hostname != NULL) { val = strlen(dhcp_opts.hostname); } if ((val > 0) && (spaceleft >= (size_t)(val + 2))) { *q++ = RFC1533_HOSTNAME; *q++ = val; if (*slirp->client_hostname) { memcpy(q, slirp->client_hostname, val); } else { memcpy(q, dhcp_opts.hostname, val); } q += val; } if (dhcp_opts.hostname != NULL) { free(dhcp_opts.hostname); dhcp_opts.hostname = NULL; } break; case RFC1533_INTBROADCAST: *q++ = RFC1533_INTBROADCAST; *q++ = 4; bcast_addr.s_addr = slirp->vhost_addr.s_addr | ~slirp->vnetwork_mask.s_addr; memcpy(q, &bcast_addr, 4); q += 4; break; case RFC2132_LEASE_TIME: *q++ = RFC2132_LEASE_TIME; *q++ = 4; if ((dhcp_opts.lease_time != 0) && (ntohl(dhcp_opts.lease_time) < LEASE_TIME)) { memcpy(q, &dhcp_opts.lease_time, 4); } else { val = htonl(LEASE_TIME); memcpy(q, &val, 4); } q += 4; dhcp_opts.lease_time = 0; break; case RFC2132_SRV_ID: *q++ = RFC2132_SRV_ID; *q++ = 4; memcpy(q, &saddr.sin_addr, 4); q += 4; break; case RFC2132_RENEWAL_TIME: *q++ = RFC2132_RENEWAL_TIME; *q++ = 4; val = htonl(600); memcpy(q, &val, 4); q += 4; break; case RFC2132_REBIND_TIME: *q++ = RFC2132_REBIND_TIME; *q++ = 4; val = htonl(1800); memcpy(q, &val, 4); q += 4; break; default: sprintf(msg, "DHCP server: requested parameter %u not supported yet", *(pp-1)); slirp_warning(slirp, msg); } } if (!dhcp_def_params_valid) break; pp = dhcp_def_params; plen = dhcp_def_params_len; dhcp_def_params_valid = 0; } if (slirp->vdnssearch) { spaceleft = sizeof(rbp->bp_vend) - (q - rbp->bp_vend); val = slirp->vdnssearch_len; if (val + 1 > (int)spaceleft) { slirp_warning(slirp, "DHCP packet size exceeded, omitting domain-search option."); } else { memcpy(q, slirp->vdnssearch, val); q += val; } } } else { static const char nak_msg[] = "requested address not available"; DPRINTF("nak'ed addr=%08x\n", ntohl(preq_addr.s_addr)); *q++ = RFC2132_MSG_TYPE; *q++ = 1; *q++ = DHCPNAK; *q++ = RFC2132_MESSAGE; *q++ = sizeof(nak_msg) - 1; memcpy(q, nak_msg, sizeof(nak_msg) - 1); q += sizeof(nak_msg) - 1; } *q = RFC1533_END; daddr.sin_addr.s_addr = 0xffffffffu; if (dhcp_opts.params != NULL) free(dhcp_opts.params); m->m_len = sizeof(struct bootp_t) - sizeof(struct ip) - sizeof(struct udphdr); udp_output2(NULL, m, &saddr, &daddr, IPTOS_LOWDELAY); } void bootp_input(struct mbuf *m) { struct bootp_t *bp = mtod(m, struct bootp_t *); if (bp->bp_op == BOOTP_REQUEST) { bootp_reply(m->slirp, bp); } } #endif
34.22547
107
0.485909
rahimazizarab
89c340ae80e58b5779e1aa36976412f7276cfd8d
3,389
cpp
C++
VC2010Samples/MFC/general/dlgcbr32/Dlgcbar.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2010Samples/MFC/general/dlgcbr32/Dlgcbar.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2010Samples/MFC/general/dlgcbr32/Dlgcbar.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.000Z
// Dlgcbar.cpp : Defines the class behaviors for the application. // // This is a part of the Microsoft Foundation Classes C++ library. // Copyright (c) Microsoft Corporation. All rights reserved. // // This source code is only intended as a supplement to the // Microsoft Foundation Classes Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Microsoft Foundation Classes product. #include "stdafx.h" #include "resource.h" #include "dlgcbar.h" #include "aboutdlg.h" #include "wndlist.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CTheApp CTheApp theApp; BEGIN_MESSAGE_MAP(CTheApp, CWinApp) //{{AFX_MSG_MAP(CTheApp) ON_COMMAND(ID_HELP_ABOUT, OnHelpAbout) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTheApp Constructors/Destructors CTheApp::CTheApp() { } CTheApp::~CTheApp() { } ///////////////////////////////////////////////////////////////////////////// // CTheApp::FirstInstance // FirstInstance checks for an existing instance of the application. // If one is found, it is activated. // // This function uses a technique similar to that described in KB // article Q109175 to locate the previous instance of the application. // However, instead of searching for a matching class name, it searches // for a matching caption. This allows us to use the normal dialog // class for our main window. It assumes that the AFX_IDS_APP_TITLE // string resource matches the caption specified in the dialog template. BOOL CTheApp::FirstInstance() { CString strCaption; strCaption.LoadString(AFX_IDS_APP_TITLE); CWnd* pwndFirst = CWnd::FindWindow((LPCTSTR)(DWORD_PTR)WC_DIALOG, strCaption); if (pwndFirst) { // another instance is already running - activate it CWnd* pwndPopup = pwndFirst->GetLastActivePopup(); pwndFirst->SetForegroundWindow(); if (pwndFirst->IsIconic()) pwndFirst->ShowWindow(SW_SHOWNORMAL); if (pwndFirst != pwndPopup) pwndPopup->SetForegroundWindow(); return FALSE; } else { // this is the first instance return TRUE; } } ///////////////////////////////////////////////////////////////////////////// // CTheApp::InitInstance // InitInstance performs per-instance initialization of the DLGCBAR // application. If an instance of the application is already running, // it activates that instance. Otherwise, it creates the modeless // dialog which serves as the application's interface. BOOL CTheApp::InitInstance() { if (!FirstInstance()) return FALSE; // Create main window TRY { CWndListDlg* pMainWnd = new CWndListDlg; m_pMainWnd = pMainWnd; return pMainWnd->Create(); } CATCH_ALL(e) { TRACE0("Failed to create main dialog\n"); return FALSE; } END_CATCH_ALL } ///////////////////////////////////////////////////////////////////////////// // CTheApp::OnHelpAbout // OnHelpAbout displays the application's about box. void CTheApp::OnHelpAbout() { CAboutDlg dlg(m_pMainWnd); dlg.DoModal(); }
27.552846
77
0.643848
alonmm
89cc12b6fd4de91b2c89b339bf96667e19205a32
7,018
cpp
C++
HiveCore/src/Buffer/BufferVolumeData.cpp
digirea/HIVE
8896b0cc858c1ad0683888b925f71c0f0d71bf9d
[ "MIT" ]
null
null
null
HiveCore/src/Buffer/BufferVolumeData.cpp
digirea/HIVE
8896b0cc858c1ad0683888b925f71c0f0d71bf9d
[ "MIT" ]
null
null
null
HiveCore/src/Buffer/BufferVolumeData.cpp
digirea/HIVE
8896b0cc858c1ad0683888b925f71c0f0d71bf9d
[ "MIT" ]
null
null
null
/** * @file BufferVolumeData.cpp * BufferVolumeDataクラス */ #include "BufferVolumeData.h" #include "Buffer.h" #include <vector> #include <algorithm> namespace { inline float remap(float x, const float *table, int n) { int idx = x * n; idx = (std::max)((std::min)(n - 1, idx), 0); return table[idx]; } } // namespace /** * BufferVolumeDataクラス */ class BufferVolumeData::Impl { private: int m_dim[3]; int m_comp; bool m_isNonUniform; RefPtr<FloatBuffer> m_buffer; RefPtr<FloatBuffer> m_spacingX; RefPtr<FloatBuffer> m_spacingY; RefPtr<FloatBuffer> m_spacingZ; public: /// コンストラクタ Impl() { Clear(); } /// デストラクタ ~Impl() { Clear(); } /// コンストラクタ Impl(BufferVolumeData* inst) { this->m_dim[0] = inst->Width(); this->m_dim[1] = inst->Height(); this->m_dim[2] = inst->Depth(); this->m_comp = inst->Component(); this->m_buffer = inst->Buffer(); this->m_isNonUniform = inst->NonUniform(); this->m_spacingX = inst->SpacingX(); this->m_spacingY = inst->SpacingY(); this->m_spacingZ = inst->SpacingZ(); } /** * BufferVolumeDataの作成 * @param w Widthサイズ * @param h Heightサイズ * @param d Depthサイズ * @param component component数 * @param nonUniform flag for non-uniform volume */ void Create(int w, int h, int d, int component, bool nonUniform) { this->m_dim[0] = w; this->m_dim[1] = h; this->m_dim[2] = d; this->m_comp = component; FloatBuffer* buf = new FloatBuffer(); FloatBuffer* spacingX = new FloatBuffer(); FloatBuffer* spacingY = new FloatBuffer(); FloatBuffer* spacingZ = new FloatBuffer(); buf->Create(w * h * d * component); this->m_buffer = buf; spacingX->Create(w+1); spacingY->Create(h+1); spacingZ->Create(d+1); this->m_spacingX = spacingX; this->m_spacingY = spacingY; this->m_spacingZ = spacingZ; this->m_isNonUniform = nonUniform; } /// メンバクリア void Clear() { m_dim[0] = m_dim[1] = m_dim[2] = 0; m_comp = 0; m_buffer = new FloatBuffer(); m_isNonUniform = false; } /// デバッグ用 void print() { } /** * Width値取得 * @return Width値 */ int Width() { return m_dim[0]; } /** * Height値取得 * @return Height値 */ int Height() { return m_dim[1]; } /** * Depth値取得 * @return Depth値 */ int Depth() { return m_dim[2]; } /** * Component数取得 * @return Component数 */ int Component() { return m_comp; } /** * ボリュームバッファ取得 * @return FloatBufferボリュームバッファへの参照 */ FloatBuffer *Buffer() { return m_buffer; } const float* Pointer() { return m_buffer->GetBuffer(); } /** * NonUniformフラグ取得 * @return NonUniformフラグ値 */ bool NonUniform() const { return m_isNonUniform; } /// xスペースバッファを返す FloatBuffer* SpacingX() { return m_spacingX; } /// yスペースバッファを返す FloatBuffer* SpacingY() { return m_spacingY; } /// zスペースバッファを返す FloatBuffer* SpacingZ() { return m_spacingZ; } /** * サンプリング * @param ret サンプルされたボリュームバッファ値 * @param x X位置 * @param y Y位置 * @param z Z位置 */ void Sample(float* ret, float x, float y, float z) { float xx = x; float yy = y; float zz = z; if (m_isNonUniform) { // remap coordinate. if (SpacingX()->GetNum() > 0) { xx = remap(xx, static_cast<const float*>(SpacingX()->GetBuffer()), SpacingX()->GetNum()); } if (SpacingX()->GetNum() > 0) { yy = remap(yy, static_cast<const float*>(SpacingY()->GetBuffer()), SpacingY()->GetNum()); } if (SpacingX()->GetNum() > 0) { zz = remap(zz, static_cast<const float*>(SpacingZ()->GetBuffer()), SpacingZ()->GetNum()); } } size_t ix = (std::min)((std::max)((size_t)(xx * Width()), (size_t)(Width()-1)), (size_t)0); size_t iy = (std::min)((std::max)((size_t)(yy * Height()), (size_t)(Height()-1)), (size_t)0); size_t iz = (std::min)((std::max)((size_t)(zz * Depth()), (size_t)(Depth()-1)), (size_t)0); size_t idx = Component() * (iz * Width() * Height() + iy * Width() + ix); const float* buf = static_cast<const float*>(m_buffer->GetBuffer()); for (size_t c = 0; c < Component(); c++) { ret[c] = buf[idx + c]; } } }; /// constructor BufferVolumeData::BufferVolumeData() : BufferData(TYPE_VOLUME) { m_imp = new BufferVolumeData::Impl(); } /// constructor BufferVolumeData::BufferVolumeData(BufferVolumeData* inst) : BufferData(TYPE_VOLUME) { m_imp = new BufferVolumeData::Impl(inst); } /// destructor BufferVolumeData::~BufferVolumeData() { delete m_imp; } BufferVolumeData* BufferVolumeData::CreateInstance() { return new BufferVolumeData(); } /** * BufferVolumeDataの作成 * @param w Widthサイズ * @param h Heightサイズ * @param d Depthサイズ * @param component component数 * @param nonUniform non-uniform flag */ void BufferVolumeData::Create(int w, int h, int d, int component, bool nonUniform) { m_imp->Create(w, h, d, component, nonUniform); } /// メンバクリア void BufferVolumeData::Clear() { m_imp->Clear(); } /// デバッグ用 void BufferVolumeData::print() { m_imp->print(); } /** * Width値取得 * @return Width値 */ int BufferVolumeData::Width() const { return m_imp->Width(); } /** * Height値取得 * @return Height値 */ int BufferVolumeData::Height() const { return m_imp->Height(); } /** * Depth値取得 * @return Depth値 */ int BufferVolumeData::Depth() const { return m_imp->Depth(); } /** * Component数取得 * @return Component数 */ int BufferVolumeData::Component() const { return m_imp->Component(); } /** * ボリュームバッファ取得 * @return FloatBufferボリュームバッファへの参照 */ FloatBuffer *BufferVolumeData::Buffer() const { return m_imp->Buffer(); } /** * ボリュームバッファ取得 * @return FloatBufferボリュームバッファへの参照 */ const float* BufferVolumeData::Pointer() const { return m_imp->Pointer(); } /** * NonUniformフラグ取得 * @return NonUniformフラグ値 */ bool BufferVolumeData::NonUniform() const { return m_imp->NonUniform(); } /// xスペースバッファを返す FloatBuffer* BufferVolumeData::SpacingX() { return m_imp->SpacingX(); } /// yスペースバッファを返す FloatBuffer* BufferVolumeData::SpacingY() { return m_imp->SpacingY(); } /// zスペースバッファを返す FloatBuffer* BufferVolumeData::SpacingZ() { return m_imp->SpacingZ(); } /** * サンプリング * @param ret サンプルされたボリュームバッファ値 * @param x X位置 * @param y Y位置 * @param z Z位置 */ void BufferVolumeData::Sample(float* ret, float x, float y, float z) { m_imp->Sample(ret, x, y, z); }
20.051429
105
0.568681
digirea
89d1b96a977fae6664c2cb09355c1dd481fa1b41
336
hpp
C++
inode.hpp
macdice/ds9fs
d6676d7996a2f3b5722b7d37f3aa58233a397aa5
[ "BSD-2-Clause" ]
3
2021-05-18T18:45:47.000Z
2021-05-24T14:31:21.000Z
inode.hpp
macdice/dsfs
d6676d7996a2f3b5722b7d37f3aa58233a397aa5
[ "BSD-2-Clause" ]
null
null
null
inode.hpp
macdice/dsfs
d6676d7996a2f3b5722b7d37f3aa58233a397aa5
[ "BSD-2-Clause" ]
null
null
null
#ifndef INODE_HPP #define INODE_HPP #include <cstddef> #include <sys/types.h> struct inode { virtual ~inode() {} virtual void write(int fd, const char *data, std::size_t size, off_t offset) = 0; virtual void truncate(int fd, std::size_t size) = 0; virtual void synchronize(int fd) = 0; virtual void lose_power() = 0; }; #endif
19.764706
82
0.699405
macdice
89d4a4127f21642f4525fc464e4f8db5a0456a86
6,216
cpp
C++
11_CPP/02_CPP02/ex03/main.cpp
tderwedu/42cursus
2f56b87ce87227175e7a297d850aa16031acb0a8
[ "Unlicense" ]
null
null
null
11_CPP/02_CPP02/ex03/main.cpp
tderwedu/42cursus
2f56b87ce87227175e7a297d850aa16031acb0a8
[ "Unlicense" ]
null
null
null
11_CPP/02_CPP02/ex03/main.cpp
tderwedu/42cursus
2f56b87ce87227175e7a297d850aa16031acb0a8
[ "Unlicense" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tderwedu <tderwedu@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/30 14:24:51 by tderwedu #+# #+# */ /* Updated: 2021/10/14 15:46:35 by tderwedu ### ########.fr */ /* */ /* ************************************************************************** */ #include <iostream> #include <string> #include "Fixed.hpp" #include "Point.hpp" # define BOLD "\e[1;37m" # define CLEAR "\e[0m" << std::endl bool bsp(Point const a, Point const b, Point const c, Point const point); int main(void) { Point a = Point(-1.0f, 0.0f); Point b = Point( 0.0f, 1.0f); Point c = Point( 1.0f, 0.0f); std::cout << BOLD << "Triangle Vertices:" << CLEAR; std::cout << "a : " << a << std::endl; std::cout << "b : " << b << std::endl; std::cout << "c : " << c << std::endl << std::endl; std::cout << BOLD << "Triangle Midpoints:" << CLEAR; std::cout << "ab : (-0.5, 0.5)" << std::endl; std::cout << "bc : ( 0.5, 0.5)" << std::endl; std::cout << "ca : ( 0.0, 0.0)" << std::endl << std::endl; std::cout << BOLD << "\t [ Permutations ]" << CLEAR; std::cout << " Point INSIDE: (0.0, 0.5)" << std::endl; std::cout << "a, b, c : " << bsp(a, b, c, Point(0.0f, 0.05f)) << std::endl; std::cout << "b, c, a : " << bsp(b, c, a, Point(0.0f, 0.05f)) << std::endl; std::cout << "c, a, b : " << bsp(c, a, b, Point(0.0f, 0.05f)) << std::endl; std::cout << "a, c, b : " << bsp(a, c, b, Point(0.0f, 0.05f)) << std::endl; std::cout << "c, b, a : " << bsp(c, b, a, Point(0.0f, 0.05f)) << std::endl; std::cout << "b, a, c : " << bsp(b, a, c, Point(0.0f, 0.05f)) << std::endl; std::cout << " Point OUTSIDE: (0.0, 2.0)" << std::endl; std::cout << "a, b, c : " << bsp(a, b, c, Point(0.0f, 2.0f)) << std::endl; std::cout << "b, c, a : " << bsp(b, c, a, Point(0.0f, 2.0f)) << std::endl; std::cout << "c, a, b : " << bsp(c, a, b, Point(0.0f, 2.0f)) << std::endl; std::cout << "a, c, b : " << bsp(a, c, b, Point(0.0f, 2.0f)) << std::endl; std::cout << "c, b, a : " << bsp(c, b, a, Point(0.0f, 2.0f)) << std::endl; std::cout << "b, a, c : " << bsp(b, a, c, Point(0.0f, 2.0f)) << std::endl; std::cout << BOLD << "\t [ Point on Edge ]" << CLEAR; std::cout << " Point on Edge ab" << std::endl; std::cout << "a, b, c : " << bsp(a, b, c, Point(-0.5f, 0.5f)) << std::endl; std::cout << "b, c, a : " << bsp(b, c, a, Point(-0.5f, 0.5f)) << std::endl; std::cout << "c, a, b : " << bsp(c, a, b, Point(-0.5f, 0.5f)) << std::endl; std::cout << " Point on Edge bc" << std::endl; std::cout << "a, c, b : " << bsp(a, c, b, Point(0.5f, 0.5f)) << std::endl; std::cout << "c, b, a : " << bsp(c, b, a, Point(0.5f, 0.5f)) << std::endl; std::cout << "b, a, c : " << bsp(b, a, c, Point(0.5f, 0.5f)) << std::endl; std::cout << " Point on Edge ca" << std::endl; std::cout << "b, c, a : " << bsp(b, c, a, Point(0.0f, 0.0f)) << std::endl; std::cout << "c, a, b : " << bsp(c, a, b, Point(0.0f, 0.0f)) << std::endl; std::cout << "a, c, b : " << bsp(a, c, b, Point(0.0f, 0.0f)) << std::endl; std::cout << BOLD << "\t [ Point on Vertex ]" << CLEAR; std::cout << " Point == a" << std::endl; std::cout << "a, b, c : " << bsp(a, b, c, a) << std::endl; std::cout << "b, c, a : " << bsp(b, c, a, a) << std::endl; std::cout << "c, a, b : " << bsp(c, a, b, a) << std::endl; std::cout << " Point == b" << std::endl; std::cout << "a, c, b : " << bsp(a, c, b, b) << std::endl; std::cout << "c, b, a : " << bsp(c, b, a, b) << std::endl; std::cout << "b, a, c : " << bsp(b, a, c, b) << std::endl; std::cout << " Point == c" << std::endl; std::cout << "b, c, a : " << bsp(b, c, a, c) << std::endl; std::cout << "c, a, b : " << bsp(c, a, b, c) << std::endl; std::cout << "a, c, b : " << bsp(a, c, b, c) << std::endl; std::cout << BOLD << "\t [ Point INSIDE but close to Edge ]" << CLEAR; std::cout << " Point close to Edge ab" << std::endl; std::cout << "a, b, c : " << bsp(a, b, c, Point(-0.49f, 0.49f)) << std::endl; std::cout << "b, c, a : " << bsp(b, c, a, Point(-0.49f, 0.49f)) << std::endl; std::cout << "c, a, b : " << bsp(c, a, b, Point(-0.49f, 0.49f)) << std::endl; std::cout << " Point close to Edge bc" << std::endl; std::cout << "a, c, b : " << bsp(a, c, b, Point(0.49f, 0.49f)) << std::endl; std::cout << "c, b, a : " << bsp(c, b, a, Point(0.49f, 0.49f)) << std::endl; std::cout << "b, a, c : " << bsp(b, a, c, Point(0.49f, 0.49f)) << std::endl; std::cout << " Point close to Edge ca" << std::endl; std::cout << "b, c, a : " << bsp(b, c, a, Point(0.0f, 0.01f)) << std::endl; std::cout << "c, a, b : " << bsp(c, a, b, Point(0.0f, 0.01f)) << std::endl; std::cout << "a, c, b : " << bsp(a, c, b, Point(0.0f, 0.01f)) << std::endl; std::cout << BOLD << "\t [ Point OUTSIDE but close to Edge ]" << CLEAR; std::cout << " Point close to Edge ab" << std::endl; std::cout << "a, b, c : " << bsp(a, b, c, Point(-0.51f, 0.51f)) << std::endl; std::cout << "b, c, a : " << bsp(b, c, a, Point(-0.51f, 0.51f)) << std::endl; std::cout << "c, a, b : " << bsp(c, a, b, Point(-0.51f, 0.51f)) << std::endl; std::cout << " Point close to Edge bc" << std::endl; std::cout << "a, c, b : " << bsp(a, c, b, Point(0.51f, 0.51f)) << std::endl; std::cout << "c, b, a : " << bsp(c, b, a, Point(0.51f, 0.51f)) << std::endl; std::cout << "b, a, c : " << bsp(b, a, c, Point(0.51f, 0.51f)) << std::endl; std::cout << " Point close to Edge ca" << std::endl; std::cout << "b, c, a : " << bsp(b, c, a, Point(0.0f, -0.01f)) << std::endl; std::cout << "c, a, b : " << bsp(c, a, b, Point(0.0f, -0.01f)) << std::endl; std::cout << "a, c, b : " << bsp(a, c, b, Point(0.0f, -0.01f)) << std::endl; }
56.509091
80
0.42471
tderwedu
89d8899149f99a2917ad76d922e6428c5e7a10cd
5,161
cpp
C++
Akel/src/Renderer/Buffers/vk_buffer.cpp
NurissGames/Akel
9580f7eb1d4a0dbe20459bd83a5e681a040c29de
[ "MIT" ]
3
2021-12-01T17:59:30.000Z
2022-01-22T20:29:08.000Z
Akel/src/Renderer/Buffers/vk_buffer.cpp
NurissGames/Akel
9580f7eb1d4a0dbe20459bd83a5e681a040c29de
[ "MIT" ]
null
null
null
Akel/src/Renderer/Buffers/vk_buffer.cpp
NurissGames/Akel
9580f7eb1d4a0dbe20459bd83a5e681a040c29de
[ "MIT" ]
1
2021-12-01T17:59:32.000Z
2021-12-01T17:59:32.000Z
// This file is a part of Akel // Authors : @kbz_8 // Created : 10/04/2022 // Updated : 08/05/2022 #include "vk_buffer.h" namespace Ak { void Buffer::create(Buffer::kind type, VkDeviceSize size, VkBufferUsageFlags usage, const void* data) { if(type == Buffer::kind::constant) { if(data == nullptr) { Core::log::report(ERROR, "Vulkan : trying to create constant buffer without data (constant buffers cannot be modified after creation)"); return; } _usage = usage | VK_BUFFER_USAGE_TRANSFER_SRC_BIT; _flags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; } else { _usage = usage; _flags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; } _mem_chunck.size = size; createBuffer(_usage, _flags); if(type == Buffer::kind::constant) { void* mapped = nullptr; mapMem(mapped); std::memcpy(mapped, data, _mem_chunck.size); unmapMem(); pushToGPU(); } } void Buffer::destroy() noexcept { Ak_assert(_buffer != VK_NULL_HANDLE, "trying to destroy an uninit video buffer"); vkDestroyBuffer(Render_Core::get().getDevice().get(), _buffer, nullptr); Render_Core::get().freeChunk(_mem_chunck); } void Buffer::createBuffer(VkBufferUsageFlags usage, VkMemoryPropertyFlags properties) { VkBufferCreateInfo bufferInfo{}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = _mem_chunck.size; bufferInfo.usage = usage; bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; auto device = Render_Core::get().getDevice().get(); if(vkCreateBuffer(device, &bufferInfo, nullptr, &_buffer) != VK_SUCCESS) Core::log::report(FATAL_ERROR, "Vulkan : failed to create buffer"); VkMemoryRequirements memRequirements; vkGetBufferMemoryRequirements(device, _buffer, &memRequirements); VkMemoryAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memRequirements.size; allocInfo.memoryTypeIndex = findMemoryType(memRequirements.memoryTypeBits); _mem_chunck = Render_Core::get().allocChunk(memRequirements, properties); vkBindBufferMemory(device, _buffer, _mem_chunck.memory, _mem_chunck.offset); } void Buffer::pushToGPU() noexcept { Buffer newBuffer; newBuffer._mem_chunck.size = this->_mem_chunck.size; newBuffer._usage = (this->_usage & VK_BUFFER_USAGE_TRANSFER_SRC_BIT) | VK_BUFFER_USAGE_TRANSFER_DST_BIT; newBuffer._flags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; newBuffer.createBuffer(newBuffer._usage, newBuffer._flags); auto cmdpool = Render_Core::get().getCmdPool().get(); auto device = Render_Core::get().getDevice().get(); VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = cmdpool; allocInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer); VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkBeginCommandBuffer(commandBuffer, &beginInfo); VkBufferCopy copyRegion{}; copyRegion.size = this->_mem_chunck.size; vkCmdCopyBuffer(commandBuffer, _buffer, newBuffer._buffer, 1, &copyRegion); vkEndCommandBuffer(commandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; auto graphicsQueue = Render_Core::get().getQueue().getGraphic(); vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE); vkQueueWaitIdle(graphicsQueue); vkFreeCommandBuffers(device, cmdpool, 1, &commandBuffer); this->swap(newBuffer); newBuffer.destroy(); } void Buffer::swap(Buffer& buffer) { VkBuffer temp_b = _buffer; _buffer = buffer._buffer; buffer._buffer = temp_b; GPU_Mem_Chunk temp_c = _mem_chunck; _mem_chunck = buffer._mem_chunck; buffer._mem_chunck = temp_c; VkBufferUsageFlags temp_u = _usage; _usage = buffer._usage; buffer._usage = temp_u; VkMemoryPropertyFlags temp_f = _flags; _flags = buffer._flags; buffer._flags = temp_f; } void Buffer::flush(VkDeviceSize size, VkDeviceSize offset) { VkMappedMemoryRange mappedRange{}; mappedRange.memory = _mem_chunck.memory; mappedRange.offset = offset; mappedRange.size = size; vkFlushMappedMemoryRanges(Render_Core::get().getDevice().get(), 1, &mappedRange); } uint32_t Buffer::findMemoryType(uint32_t typeFilter) { VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(Render_Core::get().getDevice().getPhysicalDevice(), &memProperties); for(uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { if((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & _flags) == _flags) return i; } Core::log::report(FATAL_ERROR, "Vulkan : failed to find suitable memory type"); return 0; // Not necessary due to the FATAL_ERROR parameter for logs but that removes a warning } }
30.720238
140
0.757605
NurissGames
89e1274278a0bff99a3783c7779dbe8b65955b92
339
cpp
C++
src/Interface/Handling/JsonAPIResourceBuilder.cpp
korenandr/poco_restful_webservice
864b02fb0cd500c9c74fb2f6931c44ecd6f4d019
[ "Apache-2.0" ]
1
2021-07-01T18:45:35.000Z
2021-07-01T18:45:35.000Z
src/Interface/Handling/JsonAPIResourceBuilder.cpp
korenandr/poco_restful_webservice
864b02fb0cd500c9c74fb2f6931c44ecd6f4d019
[ "Apache-2.0" ]
null
null
null
src/Interface/Handling/JsonAPIResourceBuilder.cpp
korenandr/poco_restful_webservice
864b02fb0cd500c9c74fb2f6931c44ecd6f4d019
[ "Apache-2.0" ]
null
null
null
#include "Interface/Handling/JsonAPIResourceBuilder.h" namespace Interface::Handling { JsonAPIResourceBuilder::JsonAPIResourceBuilder() : JsonAPIAbstractRootResourceBuilder("") { } JsonAPIResourceBuilder::JsonAPIResourceBuilder(const std::string & url) : JsonAPIAbstractRootResourceBuilder(url) { } }
21.1875
75
0.734513
korenandr
89e394cf4d0768c3326a5aa7ca1bf8345abddfc5
1,494
cpp
C++
src/client/sdl/drawables/drawable_text_entry_button.cpp
Santoi/quantum-chess
a2f5a0f322c6aa51488c52c8ebacbe0ad75ca9f9
[ "MIT" ]
9
2021-12-22T02:10:34.000Z
2021-12-30T17:14:25.000Z
src/client/sdl/drawables/drawable_text_entry_button.cpp
Santoi/quantum-chess
a2f5a0f322c6aa51488c52c8ebacbe0ad75ca9f9
[ "MIT" ]
null
null
null
src/client/sdl/drawables/drawable_text_entry_button.cpp
Santoi/quantum-chess
a2f5a0f322c6aa51488c52c8ebacbe0ad75ca9f9
[ "MIT" ]
null
null
null
#include "drawable_text_entry_button.h" #include <utility> #include <string> DrawableTextEntryButton::DrawableTextEntryButton( TextSpriteRepository &text_repository, ButtonSpriteRepository &button_repository, std::string default_text) : text_repository(text_repository), button_repository(button_repository), button_name(std::move(default_text)), text_box(button_repository, text_repository, "text", ""), text(text_repository, ""), is_pressed(false), x(0), y(0), width(0), height(0) {} void DrawableTextEntryButton::setAreaAndPosition(int x_, int y_, int width_, int height_) { x = x_; y = y_; width = width_; height = height_; } bool DrawableTextEntryButton::isPixelOnTextEntry( const PixelCoordinate &pixel) { is_pressed = (pixel.x() > x && pixel.x() < x + width && pixel.y() > y && pixel.y() < y + height); return is_pressed; } void DrawableTextEntryButton::render(const std::string &current_text) { is_pressed ? text_box.enablePressedStatus() : text_box.disablePressedStatus(); text_box.setAreaAndPosition(x, y, width, height); text_box.render(); if (current_text.empty()) { text.setColor('d'); text.setText(button_name); } else { text.setColor('w'); text.setText(current_text); } int text_x = x + width / 2 - text.getDrawableWidth() / 2; int text_y = y + height / 2 - text.getDrawableHeight() / 2; text.render(text_x, text_y); }
31.125
80
0.668675
Santoi
89e7a7d2a32ad560b594975537a29bb715877bda
5,001
cpp
C++
srcdll/cdc.cpp
HPC-Factor/232usb
aaf0e43e20e7e7ea9d5f8b0a2c0ba37bcf0d1567
[ "BSD-3-Clause" ]
null
null
null
srcdll/cdc.cpp
HPC-Factor/232usb
aaf0e43e20e7e7ea9d5f8b0a2c0ba37bcf0d1567
[ "BSD-3-Clause" ]
null
null
null
srcdll/cdc.cpp
HPC-Factor/232usb
aaf0e43e20e7e7ea9d5f8b0a2c0ba37bcf0d1567
[ "BSD-3-Clause" ]
null
null
null
// 232usb Copyright (c) 03-04 Zoroyoshi, Japan // See source.txt for detail #include <windows.h> #include "usbdi.h" #include "common.h" #include "file.h" #include "device.h" #include "cdc.h" int cdc_extension:: classissue() { if(classut) return -1; //issued int pkt= classendp->Descriptor.wMaxPacketSize&0x7ff; classut= uf->lpIssueInterruptTransfer(classpipe, notifyevent, serialevent , USB_IN_TRANSFER|USB_SHORT_TRANSFER_OK, pkt, classbuf, 0); //zmesg(ZM_USB,L" classissue=x%x\n", classut); if(classut==0) { //?error zmesg(ZM_ERROR,L" classissue err=%d\n", GetLastError()); return 0; }; return 1; }; int cdc_extension:: classwait() { if(classut==0) return 0; //nothing queued DWORD rc= ~0; DWORD len= 0; int rt= uf->lpIsTransferComplete(classut); if(uf->lpGetTransferStatus(classut, &len, &rc)) { if(rt==0) return 0; //waiting uf->lpCloseTransfer(classut); }; zmesg(ZM_USB,L" classwait=x%x len=%d\n", classut, len); classut= 0; if(rc!=0) { //?error zmesg(ZM_ERROR,L" classwait=x%x rc=%d\n", classut, rc); }; if(len==10&&classbuf[0]==0xa1&&classbuf[1]==0x20) { //SERIAL_STATE notify DWORD state= classbuf[8]|classbuf[9]<<8; DWORD err; err= 0; if(state&0x10) err|= CE_FRAME; if(state&0x20) err|= CE_RXPARITY; if(state&0x40) err|= CE_OVERRUN; if(state&4) err|= CE_BREAK; DWORD in; in= state>>3&MS_CTS_ON|state<<4&MS_DSR_ON|state<<3&MS_RING_ON|state<<7&MS_RLSD_ON|state>>2&1; if(!(usbmode&MODE_2303)) in|= MS_CTS_ON; linestatein(in, err); } else { //other ignored }; return 1; }; int cdc_extension:: dispatchdo() { int rt; rt= device_extension::dispatchdo(); classwait(); classissue(); if(rt==0&&classut==0) return 0; return 1; }; BOOL cdc_extension:: init() { zmesg(ZM_DRIVER,L"cdc::init\n"); if(classendp==0||recvendp==0||sendendp==0) return FALSE; if(device_extension::init()==0) return FALSE; lineout= 0; classut= 0; classpipe= uf->lpOpenPipe(uh, &classendp->Descriptor); USB_TRANSFER ut; ut= uf->lpClearFeature(uh, 0, 0 , USB_SEND_TO_ENDPOINT, USB_FEATURE_ENDPOINT_STALL, classendp->Descriptor.bEndpointAddress); if(ut) uf->lpCloseTransfer(ut); USB_DEVICE_REQUEST req; WORD abs; req.bmRequestType= USB_REQUEST_HOST_TO_DEVICE|USB_REQUEST_CLASS|USB_REQUEST_FOR_INTERFACE; req.bRequest= 0x2; //SET_COMM_FEATURE req.wValue= 1; req.wIndex= classif; req.wLength= sizeof(abs); abs= 2; //enable multiplexing ut= uf->lpIssueVendorTransfer(uh, 0, 0 , USB_SEND_TO_INTERFACE|USB_OUT_TRANSFER , &req, (BYTE*)&abs, 0); if(ut) uf->lpCloseTransfer(ut); return TRUE; }; BOOL cdc_extension:: deinit() { uf->lpClosePipe(classpipe); classpipe= 0; device_extension::deinit(); return TRUE; }; USB_TRANSFER cdc_extension:: issuebreak(int code) { USB_TRANSFER ut; USB_DEVICE_REQUEST req; int duration= 0; if(code) duration=0xffff; req.bmRequestType= USB_REQUEST_HOST_TO_DEVICE|USB_REQUEST_CLASS|USB_REQUEST_FOR_INTERFACE; req.bRequest= 0x23; //SEND_BREAK; req.wValue= duration; req.wIndex= classif; req.wLength= 0; ut= uf->lpIssueVendorTransfer(uh, 0, 0 , USB_SEND_TO_INTERFACE|USB_OUT_TRANSFER , &req, 0, 0); zmesg(ZM_USB,L" BREAK(x%x) ut=x%x\n", duration, ut); if(ut) uf->lpCloseTransfer(ut); return(0); //dummy }; USB_TRANSFER cdc_extension:: issuelinestate(int nandcode, int orcode, HANDLE event) { USB_TRANSFER ut; USB_DEVICE_REQUEST req; HANDLE ev= event; if(event==0) { ev= CreateEvent(0, 0, 0, 0); EnterCriticalSection(&flowcs); }; lineout= lineout&~nandcode|orcode; req.bmRequestType= USB_REQUEST_HOST_TO_DEVICE|USB_REQUEST_CLASS|USB_REQUEST_FOR_INTERFACE; req.bRequest= 0x22; //SET_CONTROL_LINE_STATE req.wValue= (WORD)lineout; req.wIndex= classif; req.wLength= 0; ut= uf->lpIssueVendorTransfer(uh, notifyevent, ev , USB_SEND_TO_INTERFACE|USB_OUT_TRANSFER , &req, 0, 0); if(event==0) { LeaveCriticalSection(&flowcs); if(ut) { WaitForSingleObject(ev, INFINITE); uf->lpCloseTransfer(ut); ut= 0; }; CloseHandle(ev); }; zmesg(ZM_USB,L" LINE_STATE(x%x) ut=x%x\n", lineout, ut); return(ut); }; BOOL cdc_extension:: applydcb() { device_extension::applydcb(); if(usbmode&MODE_NOBAUD) return TRUE; USB_TRANSFER ut; USB_DEVICE_REQUEST req; BYTE buf[7]; req.bmRequestType= USB_REQUEST_HOST_TO_DEVICE|USB_REQUEST_CLASS|USB_REQUEST_FOR_INTERFACE; req.bRequest= 0x20; //SET_LINE_CODING req.wValue= 0; req.wIndex= classif; req.wLength= 7; *(DWORD*)buf= dcb.BaudRate; buf[4]= dcb.StopBits; buf[5]= dcb.Parity; buf[6]= dcb.ByteSize; ut= uf->lpIssueVendorTransfer(uh, 0, 0 , USB_SEND_TO_INTERFACE|USB_OUT_TRANSFER , &req, buf, 0); zmesg(ZM_USB,L" APPLYDCB ut=x%x\n", ut); if(ut) uf->lpCloseTransfer(ut); return TRUE; };
27.327869
98
0.667666
HPC-Factor
89e8aa346df247c24ff451f5559150e4d972bc32
8,291
hpp
C++
rgcmidcpp/src/binutils.hpp
mdsitton/rhythmChartFormat
1e53aaff34603bee258582293d11d29e0bf53bde
[ "BSD-2-Clause" ]
8
2017-09-20T20:24:29.000Z
2019-08-10T22:55:13.000Z
rgcmidcpp/src/binutils.hpp
mdsitton/rhythmChartFormat
1e53aaff34603bee258582293d11d29e0bf53bde
[ "BSD-2-Clause" ]
null
null
null
rgcmidcpp/src/binutils.hpp
mdsitton/rhythmChartFormat
1e53aaff34603bee258582293d11d29e0bf53bde
[ "BSD-2-Clause" ]
1
2018-08-28T19:28:20.000Z
2018-08-28T19:28:20.000Z
// Copyright (c) 2015-2017 Matthew Sitton <matthewsitton@gmail.com> // See LICENSE in the RhythmGameChart root for license information. #pragma once #include <cstdint> #include <istream> #include <ostream> #include <vector> #include <stdexcept> #include <algorithm> #include <string> #include <string_view> // This is an older version of the code used in openrhythm with backported // bugfixes because it's a bit simpler to extend/understand. Way slower than // my code in openrhythm. // Read and write strings // The data format here is <vlv length> <string data> std::string read_string(std::istream &stream); void write_string(std::ostream &stream, std::string_view str); // Templates to read from a file different length values template<typename T, bool swapEndian = true> T read_type(std::istream &file) { T output; constexpr auto size = sizeof(T); int offset; char readContainer[size]; file.read(&readContainer[0], size); char* outPtr = reinterpret_cast<char*>(&output); for (size_t i = 0; i < size; i++) { if (swapEndian) { offset = (size-1) - i; // endianness lol ? } else { offset = i; } *(outPtr+offset) = readContainer[i]; } return output; } template<typename T, bool swapEndian = true> T read_type(std::istream &file, size_t size) { T output = 0; if (sizeof(output) < size) { throw std::runtime_error("Size greater than container type"); } else { int offset; char readContainer[size]; file.read(&readContainer[0], size); char *outPtr = reinterpret_cast<char*>(&output); for (size_t i = 0; i < size; i++) { if (swapEndian) { offset = (size-1) - i; // endianness lol ? } else { offset = i; } *(outPtr+offset) = readContainer[i]; } } return output; } template<typename T, bool swapEndian = true> void read_type(std::istream &file, T *output, size_t length) { auto size = sizeof(T); int offset; for (size_t j = 0; j < length; j++) { char *outPtr = reinterpret_cast<char*>(output); char readContainer[size]; file.read(&readContainer[0], size); for (size_t i = 0; i < size; i++) { if (swapEndian) { offset = ((size-1) - i) + (size * j); // endianness lol ? } else { offset = i + (size * j); } *(outPtr+offset) = readContainer[i]; } } } // We implement peek with read_type above to reduce code duplication. template<typename T, bool swapEndian = true> T peek_type(std::istream &file) { // We need to emulate a peek because we need several bytes of data. std::streampos startingPos = file.tellg(); T output = read_type<T, swapEndian>(file); file.seekg(startingPos); return output; } template<typename T, bool swapEndian = true> T peek_type(std::istream &file, size_t size) { // We need to emulate a peek because we need several bytes of data. std::streampos startingPos = file.tellg(); T output = read_type<T, swapEndian>(file, size); file.seekg(startingPos); return output; } template<typename T, bool swapEndian = true> void peek_type(std::istream &file, T *output, size_t length) { // We need to emulate a peek because we need several bytes of data. std::streampos startingPos = file.tellg(); read_type<T, swapEndian>(file, output, length); file.seekg(startingPos); } // write `source` to `file` in big endian template<typename T, bool swapEndian = true> void write_type(std::ostream &file, T source) { auto size = sizeof(T); int offset; T output; char* sourcePtr = reinterpret_cast<char*>(&source); char* outPtr = reinterpret_cast<char*>(&output); for (size_t i = 0; i < size; i++) { if (swapEndian) { offset = (size-1) - i; // endianness lol ? } else { offset = i; } *(outPtr+i) = *(sourcePtr+offset); } file.write(outPtr, size); } // write only `size` bytes from `source` to `file` in big endian template<typename T, bool swapEndian = true> void write_type(std::ostream &file, T source, size_t size) { if (size > sizeof(T)) { throw std::runtime_error("Size greater than container type"); } else { int offset; T output; char* sourcePtr = reinterpret_cast<char*>(&source); char* outPtr = reinterpret_cast<char*>(&output); for (size_t i = 0; i < size; i++) { if (swapEndian) { offset = (size-1) - i; // endianness lol ? } else { offset = i; } *(outPtr+i) = *(sourcePtr+offset); } file.write(outPtr, size); } } // Write `length` number of `T` from `source` in big endian // Primarally used for writing strings. template<typename T, bool swapEndian = true> void write_type(std::ostream &file, const T *source, size_t length) { auto size = sizeof(T); int offset; T output; char* sourcePtr = const_cast<char*>(source); char* outPtr = reinterpret_cast<char*>(&output); for (size_t j = 0; j < length; j++) { for (size_t i = 0; i < size; i++) { if (swapEndian) { offset = ((size-1) - i) + (size * j); // endianness lol ? } else { offset = i + (size * j); } *(outPtr+i) = *(sourcePtr+offset); } file.write(outPtr, size); } } // Convert string to bytes for creation of things like BOM's template<typename T, bool swapEndian = false> T str_to_bin(std::string_view str) { T output = 0; int offset = 0; size_t size = sizeof(T); if (size < str.length()) { throw std::runtime_error("Size greater than container type"); } for (size_t i = 0; i < str.length(); i++) { if (swapEndian) { offset = static_cast<int>((size-1) - i); // endianness lol ? } else { offset = i; } output |= str[offset] << ((size-1-i)*8); } return output; } // Read and write to VariableLengthValues // This is an earlier varient of my varlen reading code I wrote for openrhythm w/ bugfixes. // It is slower but supports reading and writing, and i'm lazy so here we go. template<typename T> T from_vlv(std::vector<uint8_t>& varLen) { T value = 0; // Check that the size of the varlen fits into the max number of bytes we have available if (varLen.size() > ((sizeof(T)*8)/7)) { throw std::runtime_error("Variable Length Value to long for type!"); return 0; } // get the last element of the vector and verify that it doesnt // have the contiuation bit set. if (((* --varLen.end()) & 0x80) != 0) { throw std::runtime_error("Invalid Variable Length Value!"); } for(auto &byte : varLen) { value = (value << 7) | (byte & 0x7F); } return value; } template<typename T> std::vector<uint8_t> to_vlv(T value) { uint8_t scratch; int byteCount = 0; std::vector<uint8_t> output; do { scratch = value & 0x7F; if (byteCount != 0 ) { scratch |= 0x80; } output.push_back(scratch); value >>= 7; byteCount++; } while(value != 0 && byteCount < ((sizeof(T)*8)/7)); std::reverse(output.begin(), output.end()); return output; } template<typename T> T read_vlv(std::istream &stream) { std::vector<uint8_t> varLen; uint8_t c; do { c = read_type<uint8_t>(stream); varLen.push_back(c); } while(c & 0x80 && varLen.size() < ((sizeof(T)*8)/7)); return from_vlv<T>(varLen); } template<typename T> void write_vlv(std::ostream &stream, T value) { std::vector<uint8_t> varLen = to_vlv<T>(value); stream.write(reinterpret_cast<char*>(&varLen[0]), sizeof(uint8_t)*varLen.size()); }
24.457227
92
0.569051
mdsitton
89e9eb41496407e950fa2e4dfa325f03fbd589ab
1,064
hpp
C++
test/mock/src/runtime/block_builder_api_mock.hpp
GeniusVentures/SuperGenius
ae43304f4a2475498ef56c971296175acb88d0ee
[ "MIT" ]
1
2021-07-10T21:25:03.000Z
2021-07-10T21:25:03.000Z
test/mock/src/runtime/block_builder_api_mock.hpp
GeniusVentures/SuperGenius
ae43304f4a2475498ef56c971296175acb88d0ee
[ "MIT" ]
null
null
null
test/mock/src/runtime/block_builder_api_mock.hpp
GeniusVentures/SuperGenius
ae43304f4a2475498ef56c971296175acb88d0ee
[ "MIT" ]
null
null
null
#ifndef SUPERGENIUS_TEST_MOCK_SRC_RUNTIME_BLOCK_BUILDER_API_MOCK_HPP #define SUPERGENIUS_TEST_MOCK_SRC_RUNTIME_BLOCK_BUILDER_API_MOCK_HPP #include <gmock/gmock.h> #include "runtime/block_builder.hpp" namespace sgns::runtime { class BlockBuilderApiMock : public BlockBuilder { public: MOCK_METHOD1(apply_extrinsic, outcome::result<primitives::ApplyResult>( const primitives::Extrinsic &)); MOCK_METHOD0(finalise_block, outcome::result<primitives::BlockHeader>()); MOCK_METHOD1(inherent_extrinsics, outcome::result<std::vector<primitives::Extrinsic>>( const primitives::InherentData &)); MOCK_METHOD2(check_inherents, outcome::result<primitives::CheckInherentsResult>( const primitives::Block &, const primitives::InherentData &)); MOCK_METHOD0(random_seed, outcome::result<base::Hash256>()); }; } // namespace sgns::runtime #endif // SUPERGENIUS_TEST_MOCK_SRC_RUNTIME_BLOCK_BUILDER_API_MOCK_HPP
36.689655
77
0.696429
GeniusVentures
8852a42eff8e4b8e8846aa31b40a7b2a69c52a73
1,299
cpp
C++
ex00/srcs/megaphone.cpp
JonathanDUFOUR/cpp_modul_00
d7ebbf1a42b0af46309ed835644e2d2f8897ad06
[ "MIT" ]
null
null
null
ex00/srcs/megaphone.cpp
JonathanDUFOUR/cpp_modul_00
d7ebbf1a42b0af46309ed835644e2d2f8897ad06
[ "MIT" ]
null
null
null
ex00/srcs/megaphone.cpp
JonathanDUFOUR/cpp_modul_00
d7ebbf1a42b0af46309ed835644e2d2f8897ad06
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* megaphone.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jodufour <jodufour@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/11/11 18:48:52 by jodufour #+# #+# */ /* Updated: 2022/03/01 18:32:30 by jodufour ### ########.fr */ /* */ /* ************************************************************************** */ #include <cstdlib> #include <iostream> typedef unsigned int uint; int main(int const ac, char const **av) { uint idx0; uint idx1; if (ac > 1) for (idx0 = 1 ; av[idx0] ; ++idx0) for (idx1 = 0 ; av[idx0][idx1] ; ++idx1) std::cout << static_cast<char>(std::toupper(av[idx0][idx1])); else std::cout << "* LOUD AND UNBEARABLE FEEDBACK NOISE *"; std::cout << std::endl; return EXIT_SUCCESS; }
40.59375
80
0.277136
JonathanDUFOUR
885a29976d90fc532e7db7e3dd64f5ba1ce0a8e1
958
cpp
C++
codechef/MAY COOK 15/REARRSTR.cpp
DevGithub007/My_Codes
e506050b97abc058fa8b1e24b3b936cc2315c664
[ "MIT" ]
null
null
null
codechef/MAY COOK 15/REARRSTR.cpp
DevGithub007/My_Codes
e506050b97abc058fa8b1e24b3b936cc2315c664
[ "MIT" ]
null
null
null
codechef/MAY COOK 15/REARRSTR.cpp
DevGithub007/My_Codes
e506050b97abc058fa8b1e24b3b936cc2315c664
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const int N = 1234567; char s[N], res[N]; pair <int, int> e[42]; int main() { int tt; scanf("%d", &tt); while (tt--) { scanf("%s", s); int n = strlen(s); int cnt[42]; for (int j = 0; j < 26; j++) { cnt[j] = 0; } for (int i = 0; i < n; i++) { cnt[s[i] - 'a']++; } for (int j = 0; j < 26; j++) { e[j] = make_pair(cnt[j], j); } sort(e, e + 26); reverse(e, e + 26); int pos = 0; for (int j = 0; j < 26; j++) { char c = e[j].second + 'a'; for (int u = 0; u < e[j].first; u++) { res[pos] = c; pos += 2; if (pos >= n) { pos = 1; } } } bool ok = true; for (int i = 0; i < n - 1; i++) { if (res[i] == res[i + 1]) { ok = false; } } res[n] = 0; if (ok) { puts(res); } else { printf("%d\n", -1); } } return 0; }
17.740741
44
0.368476
DevGithub007
8860acc08b23db785b649ae1f4d3e9bf23e03462
1,612
cpp
C++
test/math/vector/hypersphere_to_cartesian.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
test/math/vector/hypersphere_to_cartesian.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
test/math/vector/hypersphere_to_cartesian.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <fcppt/math/vector/componentwise_equal.hpp> #include <fcppt/math/vector/hypersphere_to_cartesian.hpp> #include <fcppt/math/vector/static.hpp> #include <fcppt/config/external_begin.hpp> #include <catch2/catch.hpp> #include <cmath> #include <limits> #include <fcppt/config/external_end.hpp> TEST_CASE( "math::vector::hypersphere_to_cartesian", "[math],[vector]" ) { typedef float real; real const epsilon{ std::numeric_limits< real >::epsilon() }; typedef fcppt::math::vector::static_< real, 1 > fvector1; typedef fcppt::math::vector::static_< real, 2 > fvector2; typedef fcppt::math::vector::static_< real, 3 > fvector3; real const phi1{ fcppt::literal< real >( 1.5 ) }, phi2{ fcppt::literal< real >( 0.5 ) }; CHECK( fcppt::math::vector::componentwise_equal( fcppt::math::vector::hypersphere_to_cartesian( fvector1{ phi1 } ), fvector2{ std::cos( phi1 ), std::sin( phi1 ) }, epsilon ) ); CHECK( fcppt::math::vector::componentwise_equal( fcppt::math::vector::hypersphere_to_cartesian( fvector2{ phi1, phi2 } ), fvector3( std::cos( phi1 ), std::sin( phi1 ) * std::cos( phi2 ), std::sin( phi1 ) * std::sin( phi2 ) ), epsilon ) ); }
13.777778
61
0.597395
pmiddend
8865092e6cbea3b4d4128f0e80fc9c5da9a14a20
6,309
cpp
C++
examples/tutorial/dynatype.cpp
Hower91/Apache-C-Standard-Library-4.2.x
4d9011d60dbb38b3ff80dcfe54dccd3a4647d9d3
[ "Apache-2.0" ]
null
null
null
examples/tutorial/dynatype.cpp
Hower91/Apache-C-Standard-Library-4.2.x
4d9011d60dbb38b3ff80dcfe54dccd3a4647d9d3
[ "Apache-2.0" ]
null
null
null
examples/tutorial/dynatype.cpp
Hower91/Apache-C-Standard-Library-4.2.x
4d9011d60dbb38b3ff80dcfe54dccd3a4647d9d3
[ "Apache-2.0" ]
null
null
null
/************************************************************************** * * dynatype.cpp - Example program of map. See Class Reference Section * * $Id: //stdlib/dev/examples/stdlib/tutorial/dynatype.cpp#11 $ * *************************************************************************** * * Copyright (c) 1994-2005 Quovadx, Inc., acting through its Rogue Wave * Software division. 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 <iostream> #include <map> #include <typeinfo> #include <examples.h> // ordinary class whose objects are dynamically typed at runtime class dynatype { // member template class that encapsulates a per-specialization copy // of an associative container (map) used to bind a specific instance // of dynatype to its value template <class T> struct map { typedef std::map<const dynatype*, T> map_type; static map_type& get () { static map_type m; return m; } }; // helper: removes this instance of dynatype from map template <class T> void remove () { map<T>::get ().erase (this); } // helper: copies one instance of dynatype to another template <class T> void copy (const dynatype &rhs) { *this = static_cast<T>(rhs); } // pointers to the helpers (do not depend on a template parameter) void (dynatype::*p_remove)(); void (dynatype::*p_copy)(const dynatype&); public: dynatype (); // construct a dynatype object from a value of any type template <class T> dynatype (const T&); // copy one dynatype object to another dynatype (const dynatype &rhs) : p_remove (rhs.p_remove), p_copy (rhs.p_copy) { (this->*p_copy)(rhs); } // assign one dynatype object to another dynatype& operator= (const dynatype &rhs); // remove `this' from the map destroy the object ~dynatype () { (this->*p_remove)(); } // retrieve a reference to the concrete type from an instance of // dynatype throws std::bad_cast if the types don't match exactly template <class T> operator T& () { if (map<T>::get ().end () == map<T>::get ().find (this)) throw std::bad_cast (); return map<T>::get () [this]; } // retrieve a value of the concrete type from an instance of // dynatype throws std::bad_cast if the types don't match exactly template <class T> operator T () const { return static_cast<T&> (*const_cast<dynatype*>(this)); } // assign a value of any type to an instance of dynatype template <class T> dynatype& operator= (const T &t); }; // 14.7.3, p6 - explicit specializations must be defined before first use template <> inline void dynatype::remove<dynatype::map<void> >() { /* no-op */ } template <> inline void dynatype::copy<dynatype::map<void> >(const dynatype&) { /* no-op */ } template <> inline dynatype& dynatype::operator= (const dynatype::map<void>&) { // no-op return *this; } // initialize with pointers to no-ops inline dynatype::dynatype () : p_remove (&dynatype::remove<map<void> >), p_copy (&dynatype::copy<map<void> >) { } // construct a dynatype object from a value of any type template <class T> inline dynatype::dynatype (const T &t) : p_remove (&dynatype::remove<T>), p_copy (&dynatype::copy<T>) { *this = t; } // assign one dynatype object to another inline dynatype& dynatype::operator= (const dynatype &rhs) { if (this != &rhs) { // remove `this' from the associated map (this->*p_remove)(); // copy pointers to helpers from the right-hand-side p_remove = rhs.p_remove; p_copy = rhs.p_copy; // copy value of unknown type from rhs to `*this' (this->*p_copy)(rhs); } return *this; } // assign a value of any type to an instance of dynatype template <class T> inline dynatype& dynatype::operator= (const T &t) { // remove `this' from the map of the corresponding type (this->*p_remove)(); // insert `t' into the map specialized on `T' map<T>::get () [this] = t; // assign pointers to the helpers p_remove = &dynatype::remove<T>; p_copy = &dynatype::copy<T>; return *this; } int main () { try { std::cout << "dynatype v1 = 1\n"; // create an instance of dynatype an initialized it with an int dynatype v1 = 1; std::cout << "int (v1) = " << int (v1) << std::endl; // assign a double to an instance of dynatype v1 = 3.14; std::cout << "double (v1 = 3.14) = " << double (v1) << std::endl; // copy construct an instance of dynatype dynatype v2 = v1; std::cout << "double (v2 = v1) = " << double (v2) << std::endl; // assign a const char* literal to an instance of dynatype const char* const literal = "abc"; v2 = literal; std::cout << "(const char*)(v2 = \"abc\") = " << (const char*)v2 << std::endl; // assign one instance of dynatype to another v1 = v2; std::cout << "(const char*)(v1 = v2) = " << (const char*)v1 << std::endl; // create uninitialized (untyped) instances of dynatype dynatype v3, v4; // assign one uninitialized instance to another v3 = v4; // attempt to extract any value from an unitialized dynatype fails std::cout << "char (v3) = " << char (v1) << std::endl; } catch (...) { std::cerr << "exception\n"; } }
27.430435
76
0.574735
Hower91