text
stringlengths
5
1.04M
/******************************************************************************* * Copyright 2020-2021 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #pragma once #include "oneapi/dal/algo/knn/train_types.hpp" #include "oneapi/dal/backend/dispatcher_dpc.hpp" namespace oneapi::dal::knn::backend { template <typename Float, typename Method, typename Task> struct train_kernel_gpu { train_result<Task> operator()(const dal::backend::context_gpu& ctx, const detail::descriptor_base<Task>& params, const train_input<Task>& input) const; }; } // namespace oneapi::dal::knn::backend
#include <bits/stdc++.h> int main() { bool flag_finish = false; int N_MAX = 3; int N, M; std::cin >> N >> M; std::vector<int> s(M); std::vector<int> c(M); std::vector<int> sc(N_MAX+1, -1); for (int i = 0; i < M; i++) { std::cin >> s[i] >> c[i]; // 2桁以上で先頭が0のときは終了 if (N >= 2 && s[i] == 1 && c[i] == 0) flag_finish = true; // 重複があった場合は終了 if (sc[s[i]] == -1) sc[s[i]] = c[i]; else if (sc[s[i]] != c[i]) flag_finish = true; } if (flag_finish == true) std::cout << -1 << std::endl; else { // 初期化 std::vector<int> v(N, 0); // 桁ごとに入れ替え for (int i = 0; i < M; i++) v[s[i]-1] = c[i]; // 先頭が不定のときは1にする if (v[0] == 0) v[0] = 1; // 値に変換 std::string ans = ""; for (int i = 0; i < N; i++) ans += std::to_string(v[i]); std::cout << std::stoi(ans) << std::endl; } return 0; }
// Copyright (c) 2014-2017 The Machinecoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "crypto/aes.h" #include "crypto/ripemd160.h" #include "crypto/sha1.h" #include "crypto/sha256.h" #include "crypto/sha512.h" #include "crypto/hmac_sha256.h" #include "crypto/hmac_sha512.h" #include "utilstrencodings.h" #include "test/test_machinecoin.h" #include "test/test_random.h" #include <vector> #include <boost/assign/list_of.hpp> #include <boost/test/unit_test.hpp> #include <openssl/aes.h> #include <openssl/evp.h> BOOST_FIXTURE_TEST_SUITE(crypto_tests, BasicTestingSetup) template<typename Hasher, typename In, typename Out> void TestVector(const Hasher &h, const In &in, const Out &out) { Out hash; BOOST_CHECK(out.size() == h.OUTPUT_SIZE); hash.resize(out.size()); { // Test that writing the whole input string at once works. Hasher(h).Write((unsigned char*)&in[0], in.size()).Finalize(&hash[0]); BOOST_CHECK(hash == out); } for (int i=0; i<32; i++) { // Test that writing the string broken up in random pieces works. Hasher hasher(h); size_t pos = 0; while (pos < in.size()) { size_t len = insecure_rand() % ((in.size() - pos + 1) / 2 + 1); hasher.Write((unsigned char*)&in[pos], len); pos += len; if (pos > 0 && pos + 2 * out.size() > in.size() && pos < in.size()) { // Test that writing the rest at once to a copy of a hasher works. Hasher(hasher).Write((unsigned char*)&in[pos], in.size() - pos).Finalize(&hash[0]); BOOST_CHECK(hash == out); } } hasher.Finalize(&hash[0]); BOOST_CHECK(hash == out); } } void TestSHA1(const std::string &in, const std::string &hexout) { TestVector(CSHA1(), in, ParseHex(hexout));} void TestSHA256(const std::string &in, const std::string &hexout) { TestVector(CSHA256(), in, ParseHex(hexout));} void TestSHA512(const std::string &in, const std::string &hexout) { TestVector(CSHA512(), in, ParseHex(hexout));} void TestRIPEMD160(const std::string &in, const std::string &hexout) { TestVector(CRIPEMD160(), in, ParseHex(hexout));} void TestHMACSHA256(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { std::vector<unsigned char> key = ParseHex(hexkey); TestVector(CHMAC_SHA256(&key[0], key.size()), ParseHex(hexin), ParseHex(hexout)); } void TestHMACSHA512(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { std::vector<unsigned char> key = ParseHex(hexkey); TestVector(CHMAC_SHA512(&key[0], key.size()), ParseHex(hexin), ParseHex(hexout)); } void TestAES128(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { std::vector<unsigned char> key = ParseHex(hexkey); std::vector<unsigned char> in = ParseHex(hexin); std::vector<unsigned char> correctout = ParseHex(hexout); std::vector<unsigned char> buf, buf2; assert(key.size() == 16); assert(in.size() == 16); assert(correctout.size() == 16); AES128Encrypt enc(&key[0]); buf.resize(correctout.size()); buf2.resize(correctout.size()); enc.Encrypt(&buf[0], &in[0]); BOOST_CHECK_EQUAL(HexStr(buf), HexStr(correctout)); AES128Decrypt dec(&key[0]); dec.Decrypt(&buf2[0], &buf[0]); BOOST_CHECK_EQUAL(HexStr(buf2), HexStr(in)); } void TestAES256(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { std::vector<unsigned char> key = ParseHex(hexkey); std::vector<unsigned char> in = ParseHex(hexin); std::vector<unsigned char> correctout = ParseHex(hexout); std::vector<unsigned char> buf; assert(key.size() == 32); assert(in.size() == 16); assert(correctout.size() == 16); AES256Encrypt enc(&key[0]); buf.resize(correctout.size()); enc.Encrypt(&buf[0], &in[0]); BOOST_CHECK(buf == correctout); AES256Decrypt dec(&key[0]); dec.Decrypt(&buf[0], &buf[0]); BOOST_CHECK(buf == in); } void TestAES128CBC(const std::string &hexkey, const std::string &hexiv, bool pad, const std::string &hexin, const std::string &hexout) { std::vector<unsigned char> key = ParseHex(hexkey); std::vector<unsigned char> iv = ParseHex(hexiv); std::vector<unsigned char> in = ParseHex(hexin); std::vector<unsigned char> correctout = ParseHex(hexout); std::vector<unsigned char> realout(in.size() + AES_BLOCKSIZE); // Encrypt the plaintext and verify that it equals the cipher AES128CBCEncrypt enc(&key[0], &iv[0], pad); int size = enc.Encrypt(&in[0], in.size(), &realout[0]); realout.resize(size); BOOST_CHECK(realout.size() == correctout.size()); BOOST_CHECK_MESSAGE(realout == correctout, HexStr(realout) + std::string(" != ") + hexout); // Decrypt the cipher and verify that it equals the plaintext std::vector<unsigned char> decrypted(correctout.size()); AES128CBCDecrypt dec(&key[0], &iv[0], pad); size = dec.Decrypt(&correctout[0], correctout.size(), &decrypted[0]); decrypted.resize(size); BOOST_CHECK(decrypted.size() == in.size()); BOOST_CHECK_MESSAGE(decrypted == in, HexStr(decrypted) + std::string(" != ") + hexin); // Encrypt and re-decrypt substrings of the plaintext and verify that they equal each-other for(std::vector<unsigned char>::iterator i(in.begin()); i != in.end(); ++i) { std::vector<unsigned char> sub(i, in.end()); std::vector<unsigned char> subout(sub.size() + AES_BLOCKSIZE); int _size = enc.Encrypt(&sub[0], sub.size(), &subout[0]); if (_size != 0) { subout.resize(_size); std::vector<unsigned char> subdecrypted(subout.size()); _size = dec.Decrypt(&subout[0], subout.size(), &subdecrypted[0]); subdecrypted.resize(_size); BOOST_CHECK(decrypted.size() == in.size()); BOOST_CHECK_MESSAGE(subdecrypted == sub, HexStr(subdecrypted) + std::string(" != ") + HexStr(sub)); } } } void TestAES256CBC(const std::string &hexkey, const std::string &hexiv, bool pad, const std::string &hexin, const std::string &hexout) { std::vector<unsigned char> key = ParseHex(hexkey); std::vector<unsigned char> iv = ParseHex(hexiv); std::vector<unsigned char> in = ParseHex(hexin); std::vector<unsigned char> correctout = ParseHex(hexout); std::vector<unsigned char> realout(in.size() + AES_BLOCKSIZE); // Encrypt the plaintext and verify that it equals the cipher AES256CBCEncrypt enc(&key[0], &iv[0], pad); int size = enc.Encrypt(&in[0], in.size(), &realout[0]); realout.resize(size); BOOST_CHECK(realout.size() == correctout.size()); BOOST_CHECK_MESSAGE(realout == correctout, HexStr(realout) + std::string(" != ") + hexout); // Decrypt the cipher and verify that it equals the plaintext std::vector<unsigned char> decrypted(correctout.size()); AES256CBCDecrypt dec(&key[0], &iv[0], pad); size = dec.Decrypt(&correctout[0], correctout.size(), &decrypted[0]); decrypted.resize(size); BOOST_CHECK(decrypted.size() == in.size()); BOOST_CHECK_MESSAGE(decrypted == in, HexStr(decrypted) + std::string(" != ") + hexin); // Encrypt and re-decrypt substrings of the plaintext and verify that they equal each-other for(std::vector<unsigned char>::iterator i(in.begin()); i != in.end(); ++i) { std::vector<unsigned char> sub(i, in.end()); std::vector<unsigned char> subout(sub.size() + AES_BLOCKSIZE); int _size = enc.Encrypt(&sub[0], sub.size(), &subout[0]); if (_size != 0) { subout.resize(_size); std::vector<unsigned char> subdecrypted(subout.size()); _size = dec.Decrypt(&subout[0], subout.size(), &subdecrypted[0]); subdecrypted.resize(_size); BOOST_CHECK(decrypted.size() == in.size()); BOOST_CHECK_MESSAGE(subdecrypted == sub, HexStr(subdecrypted) + std::string(" != ") + HexStr(sub)); } } } std::string LongTestString(void) { std::string ret; for (int i=0; i<200000; i++) { ret += (unsigned char)(i); ret += (unsigned char)(i >> 4); ret += (unsigned char)(i >> 8); ret += (unsigned char)(i >> 12); ret += (unsigned char)(i >> 16); } return ret; } const std::string test1 = LongTestString(); BOOST_AUTO_TEST_CASE(ripemd160_testvectors) { TestRIPEMD160("", "9c1185a5c5e9fc54612808977ee8f548b2258d31"); TestRIPEMD160("abc", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc"); TestRIPEMD160("message digest", "5d0689ef49d2fae572b881b123a85ffa21595f36"); TestRIPEMD160("secure hash algorithm", "20397528223b6a5f4cbc2808aba0464e645544f9"); TestRIPEMD160("RIPEMD160 is considered to be safe", "a7d78608c7af8a8e728778e81576870734122b66"); TestRIPEMD160("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "12a053384a9c0c88e405a06c27dcf49ada62eb2b"); TestRIPEMD160("For this sample, this 63-byte string will be used as input data", "de90dbfee14b63fb5abf27c2ad4a82aaa5f27a11"); TestRIPEMD160("This is exactly 64 bytes long, not counting the terminating byte", "eda31d51d3a623b81e19eb02e24ff65d27d67b37"); TestRIPEMD160(std::string(1000000, 'a'), "52783243c1697bdbe16d37f97f68f08325dc1528"); TestRIPEMD160(test1, "464243587bd146ea835cdf57bdae582f25ec45f1"); } BOOST_AUTO_TEST_CASE(sha1_testvectors) { TestSHA1("", "da39a3ee5e6b4b0d3255bfef95601890afd80709"); TestSHA1("abc", "a9993e364706816aba3e25717850c26c9cd0d89d"); TestSHA1("message digest", "c12252ceda8be8994d5fa0290a47231c1d16aae3"); TestSHA1("secure hash algorithm", "d4d6d2f0ebe317513bbd8d967d89bac5819c2f60"); TestSHA1("SHA1 is considered to be safe", "f2b6650569ad3a8720348dd6ea6c497dee3a842a"); TestSHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "84983e441c3bd26ebaae4aa1f95129e5e54670f1"); TestSHA1("For this sample, this 63-byte string will be used as input data", "4f0ea5cd0585a23d028abdc1a6684e5a8094dc49"); TestSHA1("This is exactly 64 bytes long, not counting the terminating byte", "fb679f23e7d1ce053313e66e127ab1b444397057"); TestSHA1(std::string(1000000, 'a'), "34aa973cd4c4daa4f61eeb2bdbad27316534016f"); TestSHA1(test1, "b7755760681cbfd971451668f32af5774f4656b5"); } BOOST_AUTO_TEST_CASE(sha256_testvectors) { TestSHA256("", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); TestSHA256("abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); TestSHA256("message digest", "f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650"); TestSHA256("secure hash algorithm", "f30ceb2bb2829e79e4ca9753d35a8ecc00262d164cc077080295381cbd643f0d"); TestSHA256("SHA256 is considered to be safe", "6819d915c73f4d1e77e4e1b52d1fa0f9cf9beaead3939f15874bd988e2a23630"); TestSHA256("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"); TestSHA256("For this sample, this 63-byte string will be used as input data", "f08a78cbbaee082b052ae0708f32fa1e50c5c421aa772ba5dbb406a2ea6be342"); TestSHA256("This is exactly 64 bytes long, not counting the terminating byte", "ab64eff7e88e2e46165e29f2bce41826bd4c7b3552f6b382a9e7d3af47c245f8"); TestSHA256("As Machinecoin relies on 80 byte header hashes, we want to have an example for that.", "7406e8de7d6e4fffc573daef05aefb8806e7790f55eab5576f31349743cca743"); TestSHA256(std::string(1000000, 'a'), "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"); TestSHA256(test1, "a316d55510b49662420f49d145d42fb83f31ef8dc016aa4e32df049991a91e26"); } BOOST_AUTO_TEST_CASE(sha512_testvectors) { TestSHA512("", "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce" "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"); TestSHA512("abc", "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a" "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"); TestSHA512("message digest", "107dbf389d9e9f71a3a95f6c055b9251bc5268c2be16d6c13492ea45b0199f33" "09e16455ab1e96118e8a905d5597b72038ddb372a89826046de66687bb420e7c"); TestSHA512("secure hash algorithm", "7746d91f3de30c68cec0dd693120a7e8b04d8073cb699bdce1a3f64127bca7a3" "d5db502e814bb63c063a7a5043b2df87c61133395f4ad1edca7fcf4b30c3236e"); TestSHA512("SHA512 is considered to be safe", "099e6468d889e1c79092a89ae925a9499b5408e01b66cb5b0a3bd0dfa51a9964" "6b4a3901caab1318189f74cd8cf2e941829012f2449df52067d3dd5b978456c2"); TestSHA512("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c335" "96fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445"); TestSHA512("For this sample, this 63-byte string will be used as input data", "b3de4afbc516d2478fe9b518d063bda6c8dd65fc38402dd81d1eb7364e72fb6e" "6663cf6d2771c8f5a6da09601712fb3d2a36c6ffea3e28b0818b05b0a8660766"); TestSHA512("This is exactly 64 bytes long, not counting the terminating byte", "70aefeaa0e7ac4f8fe17532d7185a289bee3b428d950c14fa8b713ca09814a38" "7d245870e007a80ad97c369d193e41701aa07f3221d15f0e65a1ff970cedf030"); TestSHA512("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno" "ijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018" "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909"); TestSHA512(std::string(1000000, 'a'), "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb" "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b"); TestSHA512(test1, "40cac46c147e6131c5193dd5f34e9d8bb4951395f27b08c558c65ff4ba2de594" "37de8c3ef5459d76a52cedc02dc499a3c9ed9dedbfb3281afd9653b8a112fafc"); } BOOST_AUTO_TEST_CASE(hmac_sha256_testvectors) { // test cases 1, 2, 3, 4, 6 and 7 of RFC 4231 TestHMACSHA256("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", "4869205468657265", "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"); TestHMACSHA256("4a656665", "7768617420646f2079612077616e7420666f72206e6f7468696e673f", "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"); TestHMACSHA256("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" "dddddddddddddddddddddddddddddddddddd", "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe"); TestHMACSHA256("0102030405060708090a0b0c0d0e0f10111213141516171819", "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b"); TestHMACSHA256("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaa", "54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a" "65204b6579202d2048617368204b6579204669727374", "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"); TestHMACSHA256("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaa", "5468697320697320612074657374207573696e672061206c6172676572207468" "616e20626c6f636b2d73697a65206b657920616e642061206c61726765722074" "68616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565" "647320746f20626520686173686564206265666f7265206265696e6720757365" "642062792074686520484d414320616c676f726974686d2e", "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2"); } BOOST_AUTO_TEST_CASE(hmac_sha512_testvectors) { // test cases 1, 2, 3, 4, 6 and 7 of RFC 4231 TestHMACSHA512("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", "4869205468657265", "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde" "daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854"); TestHMACSHA512("4a656665", "7768617420646f2079612077616e7420666f72206e6f7468696e673f", "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554" "9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737"); TestHMACSHA512("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" "dddddddddddddddddddddddddddddddddddd", "fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33b2279d39" "bf3e848279a722c806b485a47e67c807b946a337bee8942674278859e13292fb"); TestHMACSHA512("0102030405060708090a0b0c0d0e0f10111213141516171819", "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", "b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3db" "a91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd"); TestHMACSHA512("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaa", "54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a" "65204b6579202d2048617368204b6579204669727374", "80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f352" "6b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598"); TestHMACSHA512("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaa", "5468697320697320612074657374207573696e672061206c6172676572207468" "616e20626c6f636b2d73697a65206b657920616e642061206c61726765722074" "68616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565" "647320746f20626520686173686564206265666f7265206265696e6720757365" "642062792074686520484d414320616c676f726974686d2e", "e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944" "b6022cac3c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58"); } BOOST_AUTO_TEST_CASE(aes_testvectors) { // AES test vectors from FIPS 197. TestAES128("000102030405060708090a0b0c0d0e0f", "00112233445566778899aabbccddeeff", "69c4e0d86a7b0430d8cdb78070b4c55a"); TestAES256("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", "00112233445566778899aabbccddeeff", "8ea2b7ca516745bfeafc49904b496089"); // AES-ECB test vectors from NIST sp800-38a. TestAES128("2b7e151628aed2a6abf7158809cf4f3c", "6bc1bee22e409f96e93d7e117393172a", "3ad77bb40d7a3660a89ecaf32466ef97"); TestAES128("2b7e151628aed2a6abf7158809cf4f3c", "ae2d8a571e03ac9c9eb76fac45af8e51", "f5d3d58503b9699de785895a96fdbaaf"); TestAES128("2b7e151628aed2a6abf7158809cf4f3c", "30c81c46a35ce411e5fbc1191a0a52ef", "43b1cd7f598ece23881b00e3ed030688"); TestAES128("2b7e151628aed2a6abf7158809cf4f3c", "f69f2445df4f9b17ad2b417be66c3710", "7b0c785e27e8ad3f8223207104725dd4"); TestAES256("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", "6bc1bee22e409f96e93d7e117393172a", "f3eed1bdb5d2a03c064b5a7e3db181f8"); TestAES256("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", "ae2d8a571e03ac9c9eb76fac45af8e51", "591ccb10d410ed26dc5ba74a31362870"); TestAES256("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", "30c81c46a35ce411e5fbc1191a0a52ef", "b6ed21b99ca6f4f9f153e7b1beafed1d"); TestAES256("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", "f69f2445df4f9b17ad2b417be66c3710", "23304b7a39f9f3ff067d8d8f9e24ecc7"); } BOOST_AUTO_TEST_CASE(aes_cbc_testvectors) { // NIST AES CBC 128-bit encryption test-vectors TestAES128CBC("2b7e151628aed2a6abf7158809cf4f3c", "000102030405060708090A0B0C0D0E0F", false, \ "6bc1bee22e409f96e93d7e117393172a", "7649abac8119b246cee98e9b12e9197d"); TestAES128CBC("2b7e151628aed2a6abf7158809cf4f3c", "7649ABAC8119B246CEE98E9B12E9197D", false, \ "ae2d8a571e03ac9c9eb76fac45af8e51", "5086cb9b507219ee95db113a917678b2"); TestAES128CBC("2b7e151628aed2a6abf7158809cf4f3c", "5086cb9b507219ee95db113a917678b2", false, \ "30c81c46a35ce411e5fbc1191a0a52ef", "73bed6b8e3c1743b7116e69e22229516"); TestAES128CBC("2b7e151628aed2a6abf7158809cf4f3c", "73bed6b8e3c1743b7116e69e22229516", false, \ "f69f2445df4f9b17ad2b417be66c3710", "3ff1caa1681fac09120eca307586e1a7"); // The same vectors with padding enabled TestAES128CBC("2b7e151628aed2a6abf7158809cf4f3c", "000102030405060708090A0B0C0D0E0F", true, \ "6bc1bee22e409f96e93d7e117393172a", "7649abac8119b246cee98e9b12e9197d8964e0b149c10b7b682e6e39aaeb731c"); TestAES128CBC("2b7e151628aed2a6abf7158809cf4f3c", "7649ABAC8119B246CEE98E9B12E9197D", true, \ "ae2d8a571e03ac9c9eb76fac45af8e51", "5086cb9b507219ee95db113a917678b255e21d7100b988ffec32feeafaf23538"); TestAES128CBC("2b7e151628aed2a6abf7158809cf4f3c", "5086cb9b507219ee95db113a917678b2", true, \ "30c81c46a35ce411e5fbc1191a0a52ef", "73bed6b8e3c1743b7116e69e22229516f6eccda327bf8e5ec43718b0039adceb"); TestAES128CBC("2b7e151628aed2a6abf7158809cf4f3c", "73bed6b8e3c1743b7116e69e22229516", true, \ "f69f2445df4f9b17ad2b417be66c3710", "3ff1caa1681fac09120eca307586e1a78cb82807230e1321d3fae00d18cc2012"); // NIST AES CBC 256-bit encryption test-vectors TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \ "000102030405060708090A0B0C0D0E0F", false, "6bc1bee22e409f96e93d7e117393172a", \ "f58c4c04d6e5f1ba779eabfb5f7bfbd6"); TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \ "F58C4C04D6E5F1BA779EABFB5F7BFBD6", false, "ae2d8a571e03ac9c9eb76fac45af8e51", \ "9cfc4e967edb808d679f777bc6702c7d"); TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \ "9CFC4E967EDB808D679F777BC6702C7D", false, "30c81c46a35ce411e5fbc1191a0a52ef", "39f23369a9d9bacfa530e26304231461"); TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \ "39F23369A9D9BACFA530E26304231461", false, "f69f2445df4f9b17ad2b417be66c3710", \ "b2eb05e2c39be9fcda6c19078c6a9d1b"); // The same vectors with padding enabled TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \ "000102030405060708090A0B0C0D0E0F", true, "6bc1bee22e409f96e93d7e117393172a", \ "f58c4c04d6e5f1ba779eabfb5f7bfbd6485a5c81519cf378fa36d42b8547edc0"); TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \ "F58C4C04D6E5F1BA779EABFB5F7BFBD6", true, "ae2d8a571e03ac9c9eb76fac45af8e51", \ "9cfc4e967edb808d679f777bc6702c7d3a3aa5e0213db1a9901f9036cf5102d2"); TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \ "9CFC4E967EDB808D679F777BC6702C7D", true, "30c81c46a35ce411e5fbc1191a0a52ef", "39f23369a9d9bacfa530e263042314612f8da707643c90a6f732b3de1d3f5cee"); TestAES256CBC("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4", \ "39F23369A9D9BACFA530E26304231461", true, "f69f2445df4f9b17ad2b417be66c3710", \ "b2eb05e2c39be9fcda6c19078c6a9d1b3f461796d6b0d6b2e0c2a72b4d80e644"); } BOOST_AUTO_TEST_SUITE_END()
/** * \file dnn/src/cuda/convolution/forward/algos.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. */ #include "src/cuda/convolution/forward/algos.h" #include "src/common/algo_base.h" #include "src/common/algo_chooser.h" #include "src/cuda/conv_bias/algo.h" #include "src/cuda/conv_bias/opr_impl.h" using namespace megdnn; using namespace cuda; namespace { std::pair<TensorLayoutArray, ConvBiasForward::Param> sub_opr_config( const TensorLayout& src, const TensorLayout& filter, const TensorLayout& dst, const ConvolutionForwardImpl* opr) { auto conv_param = opr->param(); DType bias_type; if (src.dtype.enumv() == DTypeEnum::QuantizedS8) { bias_type = dtype::QuantizedS32( src.dtype.param<dtype::QuantizedS8>().scale * filter.dtype.param<dtype::QuantizedS8>().scale); } else if (src.dtype.enumv() == DTypeEnum::Quantized8Asymm) { bias_type = dtype::QuantizedS32( src.dtype.param<dtype::Quantized8Asymm>().scale * filter.dtype.param<dtype::Quantized8Asymm>().scale); } else if ( src.dtype.enumv() == DTypeEnum::Uint8 || src.dtype.enumv() == DTypeEnum::Int8) { bias_type = dtype::Int32{}; } else if (src.dtype.enumv() == DTypeEnum::Quantized4Asymm) { bias_type = dtype::QuantizedS32( src.dtype.param<dtype::Quantized4Asymm>().scale * filter.dtype.param<dtype::Quantized4Asymm>().scale); } else if (src.dtype.enumv() == DTypeEnum::QuantizedS1) { bias_type = dtype::QuantizedS32( src.dtype.param<dtype::QuantizedS1>().scale * filter.dtype.param<dtype::QuantizedS1>().scale); } else { megdnn_assert(src.dtype.category() == DTypeCategory::FLOAT); bias_type = src.dtype; } std::pair<TensorLayoutArray, ConvBiasForward::Param> ret; ret.second = { param::ConvBias::NonlineMode::IDENTITY, conv_param.mode, conv_param.sparse, conv_param.format, conv_param.pad_h, conv_param.pad_w, conv_param.stride_h, conv_param.stride_w, conv_param.dilate_h, conv_param.dilate_w, conv_param.compute_mode}; ret.first.push_back(TensorLayout({}, bias_type)); ret.first.push_back(TensorLayout({}, dst.dtype)); return ret; } std::pair<TensorLayoutArray, std::unique_ptr<ConvBiasForward>> prepare_sub_opr( const ConvolutionForwardImpl::AlgoBase::SizeArgs& args) { auto conv_bias_opr = args.opr->handle()->create_operator<ConvBiasForward>(); set_execution_policy<ConvolutionForward, ConvBiasForward*>( args.opr, conv_bias_opr.get()); auto&& config = sub_opr_config( *args.layout_src, *args.layout_filter, *args.layout_dst, args.opr); conv_bias_opr->param() = config.second; return {config.first, std::move(conv_bias_opr)}; } } // namespace ConvolutionForwardImpl::AlgoPack::AlgoPack() { all_algos.push_back(&algo_default); for (auto&& algo : all_algos) { m_all_algos_map.emplace(algo->info().desc, algo); } } ConvolutionForwardImpl::AlgoPack ConvolutionForwardImpl::sm_algo_pack; MEGDNN_DEF_GET_ALGO_FROM_DESC(ConvolutionForwardImpl) ConvolutionForwardImpl::AlgoBase::SizeArgs::SizeArgs( ConvolutionForwardImpl* o, const TensorLayout& src, const TensorLayout& filter, const TensorLayout& dst) : opr{o}, layout_src{&src}, layout_filter{&filter}, layout_dst{&dst} {} ConvolutionForwardImpl::AlgoBase::ExecArgs::ExecArgs( ConvolutionForwardImpl* opr, _megdnn_tensor_in src, _megdnn_tensor_in filter, _megdnn_tensor_out dst, _megdnn_workspace workspace) : SizeArgs(opr, src.layout, filter.layout, dst.layout), tensor_src{src}, tensor_filter{filter}, tensor_dst{dst}, workspace{workspace} {} std::string ConvolutionForwardImpl::AlgoBase::SizeArgs::to_string() const { return ssprintf( "src=%s, filter=%s, dst=%s", layout_src->to_string().c_str(), layout_filter->to_string().c_str(), layout_dst->to_string().c_str()); } /* ===================== default algo ===================== */ std::vector<Algorithm::SearchItem> ConvolutionForwardImpl::AlgoDefault::get_subopr_list( const TensorLayoutArray& layouts, const OperatorBase* opr) const { auto&& config = sub_opr_config( layouts[0], layouts[1], layouts[2], static_cast<const ConvolutionForwardImpl*>(opr)); TensorLayoutArray conv_bias_layouts = { layouts[0], layouts[1], config.first[0], config.first[1], layouts[2]}; std::string param_str; Algorithm::serialize_write_pod(config.second, param_str); return {{Algorithm::OprType::CONVBIAS_FORWARD, param_str, conv_bias_layouts}}; } bool ConvolutionForwardImpl::AlgoDefault::is_available(const SizeArgs& args) const { auto config = prepare_sub_opr(args); return get_algorithm( static_cast<ConvBiasForwardImpl*>(config.second.get()), *args.layout_src, *args.layout_filter, config.first[0], config.first[1], *args.layout_dst); } size_t ConvolutionForwardImpl::AlgoDefault::get_workspace_in_bytes( const SizeArgs& args) const { auto config = prepare_sub_opr(args); return config.second->get_workspace_in_bytes( *args.layout_src, *args.layout_filter, config.first[0], config.first[1], *args.layout_dst, nullptr); } void ConvolutionForwardImpl::AlgoDefault::exec(const ExecArgs& args) const { auto config = prepare_sub_opr(args); config.second->exec( args.tensor_src, args.tensor_filter, {nullptr, config.first[0]}, {nullptr, config.first[1]}, args.tensor_dst, nullptr, args.workspace); } // vim: syntax=cpp.doxygen
/* -------------------------------------------------------------------------- * * OpenSim Moco: MocoCasOCSolver.cpp * * -------------------------------------------------------------------------- * * Copyright (c) 2018 Stanford University and the Authors * * * * Author(s): Christopher Dembia * * * * 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 "../MocoUtilities.h" #include "CasOCHermiteSimpson.h" #include "CasOCProblem.h" #include "CasOCTranscription.h" #include "CasOCTrapezoidal.h" using OpenSim::Exception; namespace CasOC { std::unique_ptr<Transcription> Solver::createTranscription() const { std::unique_ptr<Transcription> transcription; if (m_transcriptionScheme == "trapezoidal") { transcription = OpenSim::make_unique<Trapezoidal>(*this, m_problem); } else if (m_transcriptionScheme == "hermite-simpson") { transcription = OpenSim::make_unique<HermiteSimpson>(*this, m_problem); } else { OPENSIM_THROW(Exception, "Unknown transcription scheme '{}'.", m_transcriptionScheme); } return transcription; } Iterate Solver::createInitialGuessFromBounds() const { auto transcription = createTranscription(); return transcription->createInitialGuessFromBounds(); } Iterate Solver::createRandomIterateWithinBounds() const { auto transcription = createTranscription(); return transcription->createRandomIterateWithinBounds(); } void Solver::setSparsityDetection(const std::string& setting) { OPENSIM_THROW_IF(setting != "none" && setting != "random" && setting != "initial-guess", Exception); m_sparsity_detection = setting; } void Solver::setSparsityDetectionRandomCount(int count) { OPENSIM_THROW_IF(count <= 0, Exception); m_sparsity_detection_random_count = count; } void Solver::setParallelism(std::string parallelism, int numThreads) { m_parallelism = parallelism; OPENSIM_THROW_IF(numThreads < 1, OpenSim::Exception, "Expected numThreads >= 1 but got {}.", numThreads); m_numThreads = numThreads; } Solution Solver::solve(const Iterate& guess) const { auto transcription = createTranscription(); auto pointsForSparsityDetection = std::make_shared<std::vector<VariablesDM>>(); if (m_sparsity_detection == "initial-guess") { // TODO: This guess has not been interpolated. pointsForSparsityDetection->push_back(guess.variables); } else if (m_sparsity_detection == "random") { // Make sure the exact same sparsity pattern is used every time. auto randGen = OpenSim::make_unique<SimTK::Random::Uniform>(-1, 1); randGen->setSeed(0); for (int i = 0; i < m_sparsity_detection_random_count; ++i) { pointsForSparsityDetection->push_back( transcription->createRandomIterateWithinBounds( randGen.get()) .variables); } } m_problem.initialize(m_finite_difference_scheme, std::const_pointer_cast<const std::vector<VariablesDM>>( pointsForSparsityDetection)); return transcription->solve(guess); } } // namespace CasOC
/** * Copyright (C) 2008-2014 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ /* Collections we use: local.sources - indicates what sources we pull from as a "slave", and the last update of each local.oplog.$main - our op log as "master" local.dbinfo.<dbname> - no longer used??? local.pair.startup - [deprecated] can contain a special value indicating for a pair that we have the master copy. used when replacing other half of the pair which has permanently failed. local.pair.sync - [deprecated] { initialsynccomplete: 1 } */ #define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kReplication #include "mongo/platform/basic.h" #include "mongo/db/repl/master_slave.h" #include <pcrecpp.h> #include <boost/thread/thread.hpp> #include "mongo/db/auth/authorization_manager.h" #include "mongo/db/catalog/database_catalog_entry.h" #include "mongo/db/cloner.h" #include "mongo/db/commands.h" #include "mongo/db/dbdirectclient.h" #include "mongo/db/dbhelpers.h" #include "mongo/db/ops/update.h" #include "mongo/db/query/internal_plans.h" #include "mongo/db/repl/oplog.h" #include "mongo/db/repl/repl_coordinator_global.h" #include "mongo/db/repl/rs.h" // replLocalAuth() #include "mongo/db/server_parameters.h" #include "mongo/db/operation_context_impl.h" #include "mongo/db/storage_options.h" #include "mongo/util/exit.h" #include "mongo/util/log.h" namespace mongo { namespace repl { void pretouchOperation(OperationContext* txn, const BSONObj& op); void pretouchN(vector<BSONObj>&, unsigned a, unsigned b); /* if 1 sync() is running */ volatile int syncing = 0; volatile int relinquishSyncingSome = 0; static time_t lastForcedResync = 0; /* output by the web console */ const char *replInfo = ""; struct ReplInfo { ReplInfo(const char *msg) { replInfo = msg; } ~ReplInfo() { replInfo = "?"; } }; ReplSource::ReplSource(OperationContext* txn) { nClonedThisPass = 0; ensureMe(txn); } ReplSource::ReplSource(OperationContext* txn, BSONObj o) : nClonedThisPass(0) { only = o.getStringField("only"); hostName = o.getStringField("host"); _sourceName = o.getStringField("source"); uassert( 10118 , "'host' field not set in sources collection object", !hostName.empty() ); uassert( 10119 , "only source='main' allowed for now with replication", sourceName() == "main" ); BSONElement e = o.getField("syncedTo"); if ( !e.eoo() ) { uassert( 10120 , "bad sources 'syncedTo' field value", e.type() == Date || e.type() == Timestamp ); OpTime tmp( e.date() ); syncedTo = tmp; } BSONObj dbsObj = o.getObjectField("dbsNextPass"); if ( !dbsObj.isEmpty() ) { BSONObjIterator i(dbsObj); while ( 1 ) { BSONElement e = i.next(); if ( e.eoo() ) break; addDbNextPass.insert( e.fieldName() ); } } dbsObj = o.getObjectField("incompleteCloneDbs"); if ( !dbsObj.isEmpty() ) { BSONObjIterator i(dbsObj); while ( 1 ) { BSONElement e = i.next(); if ( e.eoo() ) break; incompleteCloneDbs.insert( e.fieldName() ); } } ensureMe(txn); } /* Turn our C++ Source object into a BSONObj */ BSONObj ReplSource::jsobj() { BSONObjBuilder b; b.append("host", hostName); b.append("source", sourceName()); if ( !only.empty() ) b.append("only", only); if ( !syncedTo.isNull() ) b.appendTimestamp("syncedTo", syncedTo.asDate()); BSONObjBuilder dbsNextPassBuilder; int n = 0; for ( set<string>::iterator i = addDbNextPass.begin(); i != addDbNextPass.end(); i++ ) { n++; dbsNextPassBuilder.appendBool(*i, 1); } if ( n ) b.append("dbsNextPass", dbsNextPassBuilder.done()); BSONObjBuilder incompleteCloneDbsBuilder; n = 0; for ( set<string>::iterator i = incompleteCloneDbs.begin(); i != incompleteCloneDbs.end(); i++ ) { n++; incompleteCloneDbsBuilder.appendBool(*i, 1); } if ( n ) b.append("incompleteCloneDbs", incompleteCloneDbsBuilder.done()); return b.obj(); } void ReplSource::ensureMe(OperationContext* txn) { string myname = getHostName(); // local.me is an identifier for a server for getLastError w:2+ bool exists = Helpers::getSingleton(txn, "local.me", _me); if (!exists || !_me.hasField("host") || _me["host"].String() != myname) { Lock::DBLock dblk(txn->lockState(), "local", MODE_X); WriteUnitOfWork wunit(txn); // clean out local.me Helpers::emptyCollection(txn, "local.me"); // repopulate BSONObjBuilder b; b.appendOID("_id", 0, true); b.append("host", myname); _me = b.obj(); Helpers::putSingleton(txn, "local.me", _me); wunit.commit(); } _me = _me.getOwned(); } void ReplSource::save(OperationContext* txn) { BSONObjBuilder b; verify( !hostName.empty() ); b.append("host", hostName); // todo: finish allowing multiple source configs. // this line doesn't work right when source is null, if that is allowed as it is now: //b.append("source", _sourceName); BSONObj pattern = b.done(); BSONObj o = jsobj(); LOG( 1 ) << "Saving repl source: " << o << endl; { OpDebug debug; Client::Context ctx(txn, "local.sources"); const NamespaceString requestNs("local.sources"); UpdateRequest request(txn, requestNs); request.setQuery(pattern); request.setUpdates(o); request.setUpsert(); UpdateResult res = update(ctx.db(), request, &debug); verify( ! res.modifiers ); verify( res.numMatched == 1 ); } } static void addSourceToList(OperationContext* txn, ReplSource::SourceVector &v, ReplSource& s, ReplSource::SourceVector &old) { if ( !s.syncedTo.isNull() ) { // Don't reuse old ReplSource if there was a forced resync. for ( ReplSource::SourceVector::iterator i = old.begin(); i != old.end(); ) { if ( s == **i ) { v.push_back(*i); old.erase(i); return; } i++; } } v.push_back( shared_ptr< ReplSource >( new ReplSource( s ) ) ); } /* we reuse our existing objects so that we can keep our existing connection and cursor in effect. */ void ReplSource::loadAll(OperationContext* txn, SourceVector &v) { const char* localSources = "local.sources"; Client::Context ctx(txn, localSources); SourceVector old = v; v.clear(); const ReplSettings& replSettings = getGlobalReplicationCoordinator()->getSettings(); if (!replSettings.source.empty()) { // --source <host> specified. // check that no items are in sources other than that // add if missing int n = 0; auto_ptr<PlanExecutor> exec( InternalPlanner::collectionScan(txn, localSources, ctx.db()->getCollection(txn, localSources))); BSONObj obj; PlanExecutor::ExecState state; while (PlanExecutor::ADVANCED == (state = exec->getNext(&obj, NULL))) { n++; ReplSource tmp(txn, obj); if (tmp.hostName != replSettings.source) { log() << "repl: --source " << replSettings.source << " != " << tmp.hostName << " from local.sources collection" << endl; log() << "repl: for instructions on changing this slave's source, see:" << endl; log() << "http://dochub.mongodb.org/core/masterslave" << endl; log() << "repl: terminating mongod after 30 seconds" << endl; sleepsecs(30); dbexit( EXIT_REPLICATION_ERROR ); } if (tmp.only != replSettings.only) { log() << "--only " << replSettings.only << " != " << tmp.only << " from local.sources collection" << endl; log() << "terminating after 30 seconds" << endl; sleepsecs(30); dbexit( EXIT_REPLICATION_ERROR ); } } uassert(17065, "Internal error reading from local.sources", PlanExecutor::IS_EOF == state); uassert( 10002 , "local.sources collection corrupt?", n<2 ); if ( n == 0 ) { // source missing. add. ReplSource s(txn); s.hostName = replSettings.source; s.only = replSettings.only; s.save(txn); } } else { try { massert(10384 , "--only requires use of --source", replSettings.only.empty()); } catch ( ... ) { dbexit( EXIT_BADOPTIONS ); } } auto_ptr<PlanExecutor> exec( InternalPlanner::collectionScan(txn, localSources, ctx.db()->getCollection(txn, localSources))); BSONObj obj; PlanExecutor::ExecState state; while (PlanExecutor::ADVANCED == (state = exec->getNext(&obj, NULL))) { ReplSource tmp(txn, obj); if ( tmp.syncedTo.isNull() ) { DBDirectClient c(txn); if ( c.exists( "local.oplog.$main" ) ) { BSONObj op = c.findOne( "local.oplog.$main", QUERY( "op" << NE << "n" ).sort( BSON( "$natural" << -1 ) ) ); if ( !op.isEmpty() ) { tmp.syncedTo = op[ "ts" ].date(); } } } addSourceToList(txn, v, tmp, old); } uassert(17066, "Internal error reading from local.sources", PlanExecutor::IS_EOF == state); } bool ReplSource::throttledForceResyncDead( OperationContext* txn, const char *requester ) { if ( time( 0 ) - lastForcedResync > 600 ) { forceResyncDead( txn, requester ); lastForcedResync = time( 0 ); return true; } return false; } void ReplSource::forceResyncDead( OperationContext* txn, const char *requester ) { if ( !replAllDead ) return; SourceVector sources; ReplSource::loadAll(txn, sources); for( SourceVector::iterator i = sources.begin(); i != sources.end(); ++i ) { log() << requester << " forcing resync from " << (*i)->hostName << endl; (*i)->forceResync( txn, requester ); } replAllDead = 0; } bool replHandshake(DBClientConnection *conn, const OID& myRID) { string myname = getHostName(); BSONObjBuilder cmd; cmd.append("handshake", myRID); BSONObj res; bool ok = conn->runCommand( "admin" , cmd.obj() , res ); // ignoring for now on purpose for older versions LOG( ok ? 1 : 0 ) << "replHandshake res not: " << ok << " res: " << res << endl; return true; } bool ReplSource::_connect(OplogReader* reader, const HostAndPort& host, const OID& myRID) { if (reader->conn()) { return true; } if (!reader->connect(host)) { return false; } if (!replHandshake(reader->conn(), myRID)) { return false; } return true; } void ReplSource::forceResync( OperationContext* txn, const char *requester ) { BSONObj info; { // This is always a GlobalWrite lock (so no ns/db used from the context) invariant(txn->lockState()->isW()); Lock::TempRelease tempRelease(txn->lockState()); if (!_connect(&oplogReader, HostAndPort(hostName), getGlobalReplicationCoordinator()->getMyRID())) { msgassertedNoTrace( 14051 , "unable to connect to resync"); } /* todo use getDatabaseNames() method here */ bool ok = oplogReader.conn()->runCommand( "admin", BSON( "listDatabases" << 1 ), info ); massert( 10385 , "Unable to get database list", ok ); } WriteUnitOfWork wunit(txn); BSONObjIterator i( info.getField( "databases" ).embeddedObject() ); while( i.moreWithEOO() ) { BSONElement e = i.next(); if ( e.eoo() ) break; string name = e.embeddedObject().getField( "name" ).valuestr(); if ( !e.embeddedObject().getBoolField( "empty" ) ) { if ( name != "local" ) { if ( only.empty() || only == name ) { resyncDrop( txn, name ); } } } } syncedTo = OpTime(); addDbNextPass.clear(); save(txn); wunit.commit(); } void ReplSource::resyncDrop( OperationContext* txn, const string& db ) { log() << "resync: dropping database " << db; Client::Context ctx(txn, db); dropDatabase(txn, ctx.db()); } /* grab initial copy of a database from the master */ void ReplSource::resync(OperationContext* txn, const std::string& dbName) { const std::string db(dbName); // need local copy of the name, we're dropping the original resyncDrop( txn, db ); { log() << "resync: cloning database " << db << " to get an initial copy" << endl; ReplInfo r("resync: cloning a database"); string errmsg; int errCode = 0; CloneOptions cloneOptions; cloneOptions.fromDB = db; cloneOptions.logForRepl = false; cloneOptions.slaveOk = true; cloneOptions.useReplAuth = true; cloneOptions.snapshot = true; cloneOptions.mayYield = true; cloneOptions.mayBeInterrupted = false; Cloner cloner; bool ok = cloner.go(txn, db, hostName.c_str(), cloneOptions, NULL, errmsg, &errCode); if ( !ok ) { if ( errCode == DatabaseDifferCaseCode ) { resyncDrop( txn, db ); log() << "resync: database " << db << " not valid on the master due to a name conflict, dropping." << endl; return; } else { log() << "resync of " << db << " from " << hostName << " failed " << errmsg << endl; throw SyncException(); } } } log() << "resync: done with initial clone for db: " << db << endl; return; } static DatabaseIgnorer ___databaseIgnorer; void DatabaseIgnorer::doIgnoreUntilAfter( const string &db, const OpTime &futureOplogTime ) { if ( futureOplogTime > _ignores[ db ] ) { _ignores[ db ] = futureOplogTime; } } bool DatabaseIgnorer::ignoreAt( const string &db, const OpTime &currentOplogTime ) { if ( _ignores[ db ].isNull() ) { return false; } if ( _ignores[ db ] >= currentOplogTime ) { return true; } else { // The ignore state has expired, so clear it. _ignores.erase( db ); return false; } } bool ReplSource::handleDuplicateDbName( OperationContext* txn, const BSONObj &op, const char* ns, const char* db ) { // We are already locked at this point if (dbHolder().get(txn, ns) != NULL) { // Database is already present. return true; } BSONElement ts = op.getField( "ts" ); if ( ( ts.type() == Date || ts.type() == Timestamp ) && ___databaseIgnorer.ignoreAt( db, ts.date() ) ) { // Database is ignored due to a previous indication that it is // missing from master after optime "ts". return false; } if (Database::duplicateUncasedName(db).empty()) { // No duplicate database names are present. return true; } OpTime lastTime; bool dbOk = false; { // This is always a GlobalWrite lock (so no ns/db used from the context) invariant(txn->lockState()->isW()); Lock::TempRelease(txn->lockState()); // We always log an operation after executing it (never before), so // a database list will always be valid as of an oplog entry generated // before it was retrieved. BSONObj last = oplogReader.findOne( this->ns().c_str(), Query().sort( BSON( "$natural" << -1 ) ) ); if ( !last.isEmpty() ) { BSONElement ts = last.getField( "ts" ); massert( 14032, "Invalid 'ts' in remote log", ts.type() == Date || ts.type() == Timestamp ); lastTime = OpTime( ts.date() ); } BSONObj info; bool ok = oplogReader.conn()->runCommand( "admin", BSON( "listDatabases" << 1 ), info ); massert( 14033, "Unable to get database list", ok ); BSONObjIterator i( info.getField( "databases" ).embeddedObject() ); while( i.more() ) { BSONElement e = i.next(); const char * name = e.embeddedObject().getField( "name" ).valuestr(); if ( strcasecmp( name, db ) != 0 ) continue; if ( strcmp( name, db ) == 0 ) { // The db exists on master, still need to check that no conflicts exist there. dbOk = true; continue; } // The master has a db name that conflicts with the requested name. dbOk = false; break; } } if ( !dbOk ) { ___databaseIgnorer.doIgnoreUntilAfter( db, lastTime ); incompleteCloneDbs.erase(db); addDbNextPass.erase(db); return false; } // Check for duplicates again, since we released the lock above. set< string > duplicates; Database::duplicateUncasedName(db, &duplicates); // The database is present on the master and no conflicting databases // are present on the master. Drop any local conflicts. for( set< string >::const_iterator i = duplicates.begin(); i != duplicates.end(); ++i ) { ___databaseIgnorer.doIgnoreUntilAfter( *i, lastTime ); incompleteCloneDbs.erase(*i); addDbNextPass.erase(*i); Client::Context ctx(txn, *i); dropDatabase(txn, ctx.db()); } massert(14034, "Duplicate database names present after attempting to delete duplicates", Database::duplicateUncasedName(db).empty()); return true; } void ReplSource::applyOperation(OperationContext* txn, Database* db, const BSONObj& op) { try { bool failedUpdate = applyOperation_inlock( txn, db, op ); if (failedUpdate) { Sync sync(hostName); if (sync.shouldRetry(txn, op)) { uassert(15914, "Failure retrying initial sync update", !applyOperation_inlock(txn, db, op)); } } } catch ( UserException& e ) { log() << "sync: caught user assertion " << e << " while applying op: " << op << endl;; } catch ( DBException& e ) { log() << "sync: caught db exception " << e << " while applying op: " << op << endl;; } } /* local.$oplog.main is of the form: { ts: ..., op: <optype>, ns: ..., o: <obj> , o2: <extraobj>, b: <boolflag> } ... see logOp() comments. @param alreadyLocked caller already put us in write lock if true */ void ReplSource::_sync_pullOpLog_applyOperation(OperationContext* txn, BSONObj& op, bool alreadyLocked) { LOG(6) << "processing op: " << op << endl; if( op.getStringField("op")[0] == 'n' ) return; char clientName[MaxDatabaseNameLen]; const char *ns = op.getStringField("ns"); nsToDatabase(ns, clientName); if ( *ns == '.' ) { log() << "skipping bad op in oplog: " << op.toString() << endl; return; } else if ( *ns == 0 ) { /*if( op.getStringField("op")[0] != 'n' )*/ { log() << "halting replication, bad op in oplog:\n " << op.toString() << endl; replAllDead = "bad object in oplog"; throw SyncException(); } //ns = "local.system.x"; //nsToDatabase(ns, clientName); } if ( !only.empty() && only != clientName ) return; const ReplSettings& replSettings = getGlobalReplicationCoordinator()->getSettings(); if (replSettings.pretouch && !alreadyLocked/*doesn't make sense if in write lock already*/) { if (replSettings.pretouch > 1) { /* note: this is bad - should be put in ReplSource. but this is first test... */ static int countdown; verify( countdown >= 0 ); if( countdown > 0 ) { countdown--; // was pretouched on a prev pass } else { const int m = 4; if( tp.get() == 0 ) { int nthr = min(8, replSettings.pretouch); nthr = max(nthr, 1); tp.reset( new ThreadPool(nthr) ); } vector<BSONObj> v; oplogReader.peek(v, replSettings.pretouch); unsigned a = 0; while( 1 ) { if( a >= v.size() ) break; unsigned b = a + m - 1; // v[a..b] if( b >= v.size() ) b = v.size() - 1; tp->schedule(pretouchN, v, a, b); DEV cout << "pretouch task: " << a << ".." << b << endl; a += m; } // we do one too... pretouchOperation(txn, op); tp->join(); countdown = v.size(); } } else { pretouchOperation(txn, op); } } scoped_ptr<Lock::GlobalWrite> lk(alreadyLocked ? 0 : new Lock::GlobalWrite(txn->lockState())); if ( replAllDead ) { // hmmm why is this check here and not at top of this function? does it get set between top and here? log() << "replAllDead, throwing SyncException: " << replAllDead << endl; throw SyncException(); } if (!handleDuplicateDbName(txn, op, ns, clientName)) { return; } // This code executes on the slaves only, so it doesn't need to be sharding-aware since // mongos will not send requests there. That's why the last argument is false (do not do // version checking). Client::Context ctx(txn, ns, false); ctx.getClient()->curop()->reset(); bool empty = ctx.db()->getDatabaseCatalogEntry()->isEmpty(); bool incompleteClone = incompleteCloneDbs.count( clientName ) != 0; LOG(6) << "ns: " << ns << ", justCreated: " << ctx.justCreated() << ", empty: " << empty << ", incompleteClone: " << incompleteClone << endl; // always apply admin command command // this is a bit hacky -- the semantics of replication/commands aren't well specified if ( strcmp( clientName, "admin" ) == 0 && *op.getStringField( "op" ) == 'c' ) { applyOperation(txn, ctx.db(), op); return; } if ( ctx.justCreated() || empty || incompleteClone ) { // we must add to incomplete list now that setClient has been called incompleteCloneDbs.insert( clientName ); if ( nClonedThisPass ) { /* we only clone one database per pass, even if a lot need done. This helps us avoid overflowing the master's transaction log by doing too much work before going back to read more transactions. (Imagine a scenario of slave startup where we try to clone 100 databases in one pass.) */ addDbNextPass.insert( clientName ); } else { if ( incompleteClone ) { log() << "An earlier initial clone of '" << clientName << "' did not complete, now resyncing." << endl; } save(txn); Client::Context ctx(txn, ns); nClonedThisPass++; resync(txn, ctx.db()->name()); addDbNextPass.erase(clientName); incompleteCloneDbs.erase( clientName ); } save(txn); } else { applyOperation(txn, ctx.db(), op); addDbNextPass.erase( clientName ); } } void ReplSource::syncToTailOfRemoteLog() { string _ns = ns(); BSONObjBuilder b; if ( !only.empty() ) { b.appendRegex("ns", string("^") + pcrecpp::RE::QuoteMeta( only )); } BSONObj last = oplogReader.findOne( _ns.c_str(), Query( b.done() ).sort( BSON( "$natural" << -1 ) ) ); if ( !last.isEmpty() ) { BSONElement ts = last.getField( "ts" ); massert( 10386 , "non Date ts found: " + last.toString(), ts.type() == Date || ts.type() == Timestamp ); syncedTo = OpTime( ts.date() ); } } class ReplApplyBatchSize : public ServerParameter { public: ReplApplyBatchSize() : ServerParameter( ServerParameterSet::getGlobal(), "replApplyBatchSize" ), _value( 1 ) { } int get() const { return _value; } virtual void append(OperationContext* txn, BSONObjBuilder& b, const string& name) { b.append( name, _value ); } virtual Status set( const BSONElement& newValuElement ) { return set( newValuElement.numberInt() ); } virtual Status set( int b ) { if( b < 1 || b > 1024 ) { return Status( ErrorCodes::BadValue, "replApplyBatchSize has to be >= 1 and < 1024" ); } const ReplSettings& replSettings = getGlobalReplicationCoordinator()->getSettings(); if ( replSettings.slavedelay != 0 && b > 1 ) { return Status( ErrorCodes::BadValue, "can't use a batch size > 1 with slavedelay" ); } if ( ! replSettings.slave ) { return Status( ErrorCodes::BadValue, "can't set replApplyBatchSize on a non-slave machine" ); } _value = b; return Status::OK(); } virtual Status setFromString( const string& str ) { return set( atoi( str.c_str() ) ); } int _value; } replApplyBatchSize; /* slave: pull some data from the master's oplog note: not yet in db mutex at this point. @return -1 error 0 ok, don't sleep 1 ok, sleep */ int ReplSource::_sync_pullOpLog(OperationContext* txn, int& nApplied) { int okResultCode = 1; string ns = string("local.oplog.$") + sourceName(); LOG(2) << "repl: sync_pullOpLog " << ns << " syncedTo:" << syncedTo.toStringLong() << '\n'; bool tailing = true; oplogReader.tailCheck(); bool initial = syncedTo.isNull(); if ( !oplogReader.haveCursor() || initial ) { if ( initial ) { // Important to grab last oplog timestamp before listing databases. syncToTailOfRemoteLog(); BSONObj info; bool ok = oplogReader.conn()->runCommand( "admin", BSON( "listDatabases" << 1 ), info ); massert( 10389 , "Unable to get database list", ok ); BSONObjIterator i( info.getField( "databases" ).embeddedObject() ); while( i.moreWithEOO() ) { BSONElement e = i.next(); if ( e.eoo() ) break; string name = e.embeddedObject().getField( "name" ).valuestr(); if ( !e.embeddedObject().getBoolField( "empty" ) ) { if ( name != "local" ) { if ( only.empty() || only == name ) { LOG( 2 ) << "adding to 'addDbNextPass': " << name << endl; addDbNextPass.insert( name ); } } } } // obviously global isn't ideal, but non-repl set is old so // keeping it simple Lock::GlobalWrite lk(txn->lockState()); save(txn); } BSONObjBuilder gte; gte.appendTimestamp("$gte", syncedTo.asDate()); BSONObjBuilder query; query.append("ts", gte.done()); if ( !only.empty() ) { // note we may here skip a LOT of data table scanning, a lot of work for the master. // maybe append "\\." here? query.appendRegex("ns", string("^") + pcrecpp::RE::QuoteMeta( only )); } BSONObj queryObj = query.done(); // e.g. queryObj = { ts: { $gte: syncedTo } } oplogReader.tailingQuery(ns.c_str(), queryObj); tailing = false; } else { LOG(2) << "repl: tailing=true\n"; } if( !oplogReader.haveCursor() ) { log() << "repl: dbclient::query returns null (conn closed?)" << endl; oplogReader.resetConnection(); return -1; } // show any deferred database creates from a previous pass { set<string>::iterator i = addDbNextPass.begin(); if ( i != addDbNextPass.end() ) { BSONObjBuilder b; b.append("ns", *i + '.'); b.append("op", "db"); BSONObj op = b.done(); _sync_pullOpLog_applyOperation(txn, op, false); } } if ( !oplogReader.more() ) { if ( tailing ) { LOG(2) << "repl: tailing & no new activity\n"; okResultCode = 0; // don't sleep } else { log() << "repl: " << ns << " oplog is empty" << endl; } { Lock::GlobalWrite lk(txn->lockState()); save(txn); } return okResultCode; } OpTime nextOpTime; { BSONObj op = oplogReader.next(); BSONElement ts = op.getField("ts"); if ( ts.type() != Date && ts.type() != Timestamp ) { string err = op.getStringField("$err"); if ( !err.empty() ) { // 13051 is "tailable cursor requested on non capped collection" if (op.getIntField("code") == 13051) { log() << "trying to slave off of a non-master" << '\n'; massert( 13344 , "trying to slave off of a non-master", false ); } else { log() << "repl: $err reading remote oplog: " + err << '\n'; massert( 10390 , "got $err reading remote oplog", false ); } } else { log() << "repl: bad object read from remote oplog: " << op.toString() << '\n'; massert( 10391 , "repl: bad object read from remote oplog", false); } } nextOpTime = OpTime( ts.date() ); LOG(2) << "repl: first op time received: " << nextOpTime.toString() << '\n'; if ( initial ) { LOG(1) << "repl: initial run\n"; } if( tailing ) { if( !( syncedTo < nextOpTime ) ) { log() << "repl ASSERTION failed : syncedTo < nextOpTime" << endl; log() << "repl syncTo: " << syncedTo.toStringLong() << endl; log() << "repl nextOpTime: " << nextOpTime.toStringLong() << endl; verify(false); } oplogReader.putBack( op ); // op will be processed in the loop below nextOpTime = OpTime(); // will reread the op below } else if ( nextOpTime != syncedTo ) { // didn't get what we queried for - error log() << "repl: nextOpTime " << nextOpTime.toStringLong() << ' ' << ((nextOpTime < syncedTo) ? "<??" : ">") << " syncedTo " << syncedTo.toStringLong() << '\n' << "repl: time diff: " << (nextOpTime.getSecs() - syncedTo.getSecs()) << "sec\n" << "repl: tailing: " << tailing << '\n' << "repl: data too stale, halting replication" << endl; replInfo = replAllDead = "data too stale halted replication"; verify( syncedTo < nextOpTime ); throw SyncException(); } else { /* t == syncedTo, so the first op was applied previously or it is the first op of initial query and need not be applied. */ } } // apply operations { int n = 0; time_t saveLast = time(0); while ( 1 ) { // we need "&& n" to assure we actually process at least one op to get a sync // point recorded in the first place. const bool moreInitialSyncsPending = !addDbNextPass.empty() && n; if ( moreInitialSyncsPending || !oplogReader.more() ) { Lock::GlobalWrite lk(txn->lockState()); if (tailing) { okResultCode = 0; // don't sleep } syncedTo = nextOpTime; save(txn); // note how far we are synced up to now log() << "repl: applied " << n << " operations" << endl; nApplied = n; log() << "repl: end sync_pullOpLog syncedTo: " << syncedTo.toStringLong() << endl; break; } OCCASIONALLY if( n > 0 && ( n > 100000 || time(0) - saveLast > 60 ) ) { // periodically note our progress, in case we are doing a lot of work and crash Lock::GlobalWrite lk(txn->lockState()); syncedTo = nextOpTime; // can't update local log ts since there are pending operations from our peer save(txn); log() << "repl: checkpoint applied " << n << " operations" << endl; log() << "repl: syncedTo: " << syncedTo.toStringLong() << endl; saveLast = time(0); n = 0; } BSONObj op = oplogReader.next(); int b = replApplyBatchSize.get(); bool justOne = b == 1; scoped_ptr<Lock::GlobalWrite> lk(justOne ? 0 : new Lock::GlobalWrite(txn->lockState())); while( 1 ) { BSONElement ts = op.getField("ts"); if( !( ts.type() == Date || ts.type() == Timestamp ) ) { log() << "sync error: problem querying remote oplog record" << endl; log() << "op: " << op.toString() << endl; log() << "halting replication" << endl; replInfo = replAllDead = "sync error: no ts found querying remote oplog record"; throw SyncException(); } OpTime last = nextOpTime; nextOpTime = OpTime( ts.date() ); if ( !( last < nextOpTime ) ) { log() << "sync error: last applied optime at slave >= nextOpTime from master" << endl; log() << " last: " << last.toStringLong() << endl; log() << " nextOpTime: " << nextOpTime.toStringLong() << endl; log() << " halting replication" << endl; replInfo = replAllDead = "sync error last >= nextOpTime"; uassert( 10123 , "replication error last applied optime at slave >= nextOpTime from master", false); } const ReplSettings& replSettings = getGlobalReplicationCoordinator()->getSettings(); if ( replSettings.slavedelay && ( unsigned( time( 0 ) ) < nextOpTime.getSecs() + replSettings.slavedelay ) ) { verify( justOne ); oplogReader.putBack( op ); _sleepAdviceTime = nextOpTime.getSecs() + replSettings.slavedelay + 1; Lock::GlobalWrite lk(txn->lockState()); if ( n > 0 ) { syncedTo = last; save(txn); } log() << "repl: applied " << n << " operations" << endl; log() << "repl: syncedTo: " << syncedTo.toStringLong() << endl; log() << "waiting until: " << _sleepAdviceTime << " to continue" << endl; return okResultCode; } _sync_pullOpLog_applyOperation(txn, op, !justOne); n++; if( --b == 0 ) break; // if to here, we are doing mulpile applications in a singel write lock acquisition if( !oplogReader.moreInCurrentBatch() ) { // break if no more in batch so we release lock while reading from the master break; } op = oplogReader.next(); } } } return okResultCode; } /* note: not yet in mutex at this point. returns >= 0 if ok. return -1 if you want to reconnect. return value of zero indicates no sleep necessary before next call */ int ReplSource::sync(OperationContext* txn, int& nApplied) { _sleepAdviceTime = 0; ReplInfo r("sync"); if (!serverGlobalParams.quiet) { LogstreamBuilder l = log(); l << "repl: syncing from "; if( sourceName() != "main" ) { l << "source:" << sourceName() << ' '; } l << "host:" << hostName << endl; } nClonedThisPass = 0; // FIXME Handle cases where this db isn't on default port, or default port is spec'd in hostName. if ((string("localhost") == hostName || string("127.0.0.1") == hostName) && serverGlobalParams.port == ServerGlobalParams::DefaultDBPort) { log() << "repl: can't sync from self (localhost). sources configuration may be wrong." << endl; sleepsecs(5); return -1; } if ( !_connect(&oplogReader, HostAndPort(hostName), getGlobalReplicationCoordinator()->getMyRID()) ) { LOG(4) << "repl: can't connect to sync source" << endl; return -1; } return _sync_pullOpLog(txn, nApplied); } /* --------------------------------------------------------------*/ static bool _replMainStarted = false; /* TODO: _ source has autoptr to the cursor _ reuse that cursor when we can */ /* returns: # of seconds to sleep before next pass 0 = no sleep recommended 1 = special sentinel indicating adaptive sleep recommended */ int _replMain(OperationContext* txn, ReplSource::SourceVector& sources, int& nApplied) { { ReplInfo r("replMain load sources"); Lock::GlobalWrite lk(txn->lockState()); ReplSource::loadAll(txn, sources); // only need this param for initial reset _replMainStarted = true; } if ( sources.empty() ) { /* replication is not configured yet (for --slave) in local.sources. Poll for config it every 20 seconds. */ log() << "no source given, add a master to local.sources to start replication" << endl; return 20; } int sleepAdvice = 1; for ( ReplSource::SourceVector::iterator i = sources.begin(); i != sources.end(); i++ ) { ReplSource *s = i->get(); int res = -1; try { res = s->sync(txn, nApplied); bool moreToSync = s->haveMoreDbsToSync(); if( res < 0 ) { sleepAdvice = 3; } else if( moreToSync ) { sleepAdvice = 0; } else if ( s->sleepAdvice() ) { sleepAdvice = s->sleepAdvice(); } else sleepAdvice = res; } catch ( const SyncException& ) { log() << "caught SyncException" << endl; return 10; } catch ( AssertionException& e ) { if ( e.severe() ) { log() << "replMain AssertionException " << e.what() << endl; return 60; } else { log() << "repl: AssertionException " << e.what() << endl; } replInfo = "replMain caught AssertionException"; } catch ( const DBException& e ) { log() << "repl: DBException " << e.what() << endl; replInfo = "replMain caught DBException"; } catch ( const std::exception &e ) { log() << "repl: std::exception " << e.what() << endl; replInfo = "replMain caught std::exception"; } catch ( ... ) { log() << "unexpected exception during replication. replication will halt" << endl; replAllDead = "caught unexpected exception during replication"; } if ( res < 0 ) s->oplogReader.resetConnection(); } return sleepAdvice; } static void replMain(OperationContext* txn) { ReplSource::SourceVector sources; while ( 1 ) { int s = 0; { Lock::GlobalWrite lk(txn->lockState()); if ( replAllDead ) { // throttledForceResyncDead can throw if ( !getGlobalReplicationCoordinator()->getSettings().autoresync || !ReplSource::throttledForceResyncDead( txn, "auto" ) ) { log() << "all sources dead: " << replAllDead << ", sleeping for 5 seconds" << endl; break; } } verify( syncing == 0 ); // i.e., there is only one sync thread running. we will want to change/fix this. syncing++; } try { int nApplied = 0; s = _replMain(txn, sources, nApplied); if( s == 1 ) { if( nApplied == 0 ) s = 2; else if( nApplied > 100 ) { // sleep very little - just enough that we aren't truly hammering master sleepmillis(75); s = 0; } } } catch (...) { log() << "caught exception in _replMain" << endl; s = 4; } { Lock::GlobalWrite lk(txn->lockState()); verify( syncing == 1 ); syncing--; } if( relinquishSyncingSome ) { relinquishSyncingSome = 0; s = 1; // sleep before going back in to syncing=1 } if ( s ) { stringstream ss; ss << "repl: sleep " << s << " sec before next pass"; string msg = ss.str(); if (!serverGlobalParams.quiet) log() << msg << endl; ReplInfo r(msg.c_str()); sleepsecs(s); } } } static void replMasterThread() { sleepsecs(4); Client::initThread("replmaster"); int toSleep = 10; while( 1 ) { sleepsecs( toSleep ); /* write a keep-alive like entry to the log. this will make things like printReplicationStatus() and printSlaveReplicationStatus() stay up-to-date even when things are idle. */ { OperationContextImpl txn; writelocktry lk(txn.lockState(), 1); if ( lk.got() ) { toSleep = 10; replLocalAuth(); try { logKeepalive(&txn); } catch(...) { log() << "caught exception in replMasterThread()" << endl; } } else { LOG(5) << "couldn't logKeepalive" << endl; toSleep = 1; } } } } static void replSlaveThread() { sleepsecs(1); Client::initThread("replslave"); OperationContextImpl txn; { Lock::GlobalWrite lk(txn.lockState()); replLocalAuth(); } while ( 1 ) { try { replMain(&txn); sleepsecs(5); } catch ( AssertionException& ) { ReplInfo r("Assertion in replSlaveThread(): sleeping 5 minutes before retry"); log() << "Assertion in replSlaveThread(): sleeping 5 minutes before retry" << endl; sleepsecs(300); } catch ( DBException& e ) { log() << "exception in replSlaveThread(): " << e.what() << ", sleeping 5 minutes before retry" << endl; sleepsecs(300); } catch ( ... ) { log() << "error in replSlaveThread(): sleeping 5 minutes before retry" << endl; sleepsecs(300); } } } void startMasterSlave() { OperationContextImpl txn; oldRepl(); const ReplSettings& replSettings = getGlobalReplicationCoordinator()->getSettings(); if( !replSettings.slave && !replSettings.master ) return; { Lock::GlobalWrite lk(txn.lockState()); replLocalAuth(); } { ReplSource temp(&txn); // Ensures local.me is populated } if ( replSettings.slave ) { verify( replSettings.slave == SimpleSlave ); LOG(1) << "slave=true" << endl; boost::thread repl_thread(replSlaveThread); } if ( replSettings.master ) { LOG(1) << "master=true" << endl; createOplog(&txn); boost::thread t(replMasterThread); } if (replSettings.fastsync) { while(!_replMainStarted) // don't allow writes until we've set up from log sleepmillis( 50 ); } } int _dummy_z; void pretouchN(vector<BSONObj>& v, unsigned a, unsigned b) { Client *c = currentClient.get(); if( c == 0 ) { Client::initThread("pretouchN"); c = &cc(); } OperationContextImpl txn; // XXX Lock::GlobalRead lk(txn.lockState()); for( unsigned i = a; i <= b; i++ ) { const BSONObj& op = v[i]; const char *which = "o"; const char *opType = op.getStringField("op"); if ( *opType == 'i' ) ; else if( *opType == 'u' ) which = "o2"; else continue; /* todo : other operations */ try { BSONObj o = op.getObjectField(which); BSONElement _id; if( o.getObjectID(_id) ) { const char *ns = op.getStringField("ns"); BSONObjBuilder b; b.append(_id); BSONObj result; Client::Context ctx(&txn, ns); if( Helpers::findById(&txn, ctx.db(), ns, b.done(), result) ) _dummy_z += result.objsize(); // touch } } catch( DBException& e ) { log() << "ignoring assertion in pretouchN() " << a << ' ' << b << ' ' << i << ' ' << e.toString() << endl; } } } void pretouchOperation(OperationContext* txn, const BSONObj& op) { if (txn->lockState()->isWriteLocked()) { return; // no point pretouching if write locked. not sure if this will ever fire, but just in case. } const char *which = "o"; const char *opType = op.getStringField("op"); if ( *opType == 'i' ) ; else if( *opType == 'u' ) which = "o2"; else return; /* todo : other operations */ try { BSONObj o = op.getObjectField(which); BSONElement _id; if( o.getObjectID(_id) ) { const char *ns = op.getStringField("ns"); BSONObjBuilder b; b.append(_id); BSONObj result; AutoGetCollectionForRead ctx(txn, ns ); if (Helpers::findById(txn, ctx.getDb(), ns, b.done(), result)) { _dummy_z += result.objsize(); // touch } } } catch( DBException& ) { log() << "ignoring assertion in pretouchOperation()" << endl; } } } // namespace repl } // namespace mongo
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2018 The Securus developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bitcoinaddressvalidator.h" #include "base58.h" /* Base58 characters are: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" This is: - All numbers except for '0' - All upper-case letters except for 'I' and 'O' - All lower-case letters except for 'l' */ BitcoinAddressEntryValidator::BitcoinAddressEntryValidator(QObject* parent) : QValidator(parent) { } QValidator::State BitcoinAddressEntryValidator::validate(QString& input, int& pos) const { Q_UNUSED(pos); // Empty address is "intermediate" input if (input.isEmpty()) return QValidator::Intermediate; // Correction for (int idx = 0; idx < input.size();) { bool removeChar = false; QChar ch = input.at(idx); // Corrections made are very conservative on purpose, to avoid // users unexpectedly getting away with typos that would normally // be detected, and thus sending to the wrong address. switch (ch.unicode()) { // Qt categorizes these as "Other_Format" not "Separator_Space" case 0x200B: // ZERO WIDTH SPACE case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE removeChar = true; break; default: break; } // Remove whitespace if (ch.isSpace()) removeChar = true; // To next character if (removeChar) input.remove(idx, 1); else ++idx; } // Validation QValidator::State state = QValidator::Acceptable; for (int idx = 0; idx < input.size(); ++idx) { int ch = input.at(idx).unicode(); if (((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) && ch != 'l' && ch != 'I' && ch != '0' && ch != 'O') { // Alphanumeric and not a 'forbidden' character } else { state = QValidator::Invalid; } } return state; } BitcoinAddressCheckValidator::BitcoinAddressCheckValidator(QObject* parent) : QValidator(parent) { } QValidator::State BitcoinAddressCheckValidator::validate(QString& input, int& pos) const { Q_UNUSED(pos); // Validate the passed Bitcoin address CBitcoinAddress addr(input.toStdString()); if (addr.IsValid()) return QValidator::Acceptable; return QValidator::Invalid; }
#include <iostream> #include <ctime> #include <random> #include "ClassicMatrix.h" #include "SparseMatrix.h" #include "SparseMatrixOptimized.h" #include "Generator.h" #include "Helper.h" #define PRINT_MAX_HEIGHT 20 #define PRINT_MAX_WIDTH 20 /** * @brief Reads element matrix from std::cin until the OES * @param matrix Matrix to write in. */ template<class T> void ReadMatrixElements(Matrix::MatrixBase<T>& matrix) { auto matrix_height = matrix.get_height(); auto matrix_width = matrix.get_width(); while (!std::cin.eof()) { // read element row int row = 0; while (true) { std::cout << "Enter row:"; std::cin >> row; if (row < 0 || row >= matrix_height) { std::cout << "\tError: value is out of range. Valid values: [0, " << matrix_height - 1 << "]." << std::endl; } else { break; } } // read element column int col = 0; while (true) { std::cout << "Enter column:"; std::cin >> row; if (col < 0 || col >= matrix_width) { std::cout << "\tError: value is out of range. Valid values: [0, " << matrix_width - 1 << "]." << std::endl; } else { break; } } // read value T value; std::cout << "Enter value: "; std::cin >> value; matrix.set_item(col, row, value); } } /** * @brief Reads all matrix elements. * @param matrix Matrix to write in. */ template<class T> void ReadMatrix(Matrix::MatrixBase<T>& matrix) { auto matrix_height = matrix.get_height(); auto matrix_width = matrix.get_width(); for (int i = 0; i < matrix_height; ++i) { for (int j = 0; j < matrix_width; ++j) { T value; std::cin >> value; matrix.set_item(i, j, value); } } } /** * @brief Reads matrix from std::cin. * @param matrix Matrix to write in */ template<class T> void ReadMatrixDialog(Matrix::MatrixBase<T>& matrix, bool fixed_size = false) { // matrix size int height; int width; if (fixed_size) { height = matrix.get_height(); width = matrix.get_width(); } else { std::cout << "Enter height: "; std::cin >> height; std::cout << "Enter width: "; std::cin >> width; matrix.Resize(height, width); } bool select_mode; std::cout << "Use selection mode? (0, 1): "; std::cin >> select_mode; if (select_mode) { while (true) { int row = 0; while (true) { std::cout << "Enter row (negative to stop): "; std::cin >> row; if (row >= height) { std::cout << "Value is out of range (must be less then " << height << ")." << std::endl; } else { break; } } if (row < 0) { break; } int col = 0; while (true) { std::cout << "Enter column (negative to stop): "; std::cin >> col; if (col >= width) { std::cout << "Value is out of range (must be less then " << width << ")." << std::endl; } else { break; } } if (col < 0) { break; } T value; std::cout << "Enter value: "; std::cin >> value; matrix.set_item(row, col, value); } } else { ReadMatrix(matrix); } } template<class T> void PrintMatrix(std::ostream& out, const Matrix::MatrixBase<T>& classic, const Matrix::MatrixBase<T>& sparse) { int height = classic.get_height(); int width = classic.get_width(); if (height <= PRINT_MAX_HEIGHT && width <= PRINT_MAX_WIDTH && sparse.get_height() <= PRINT_MAX_HEIGHT && sparse.get_width() <= PRINT_MAX_WIDTH) { Helper::ContecateStreamByRows(std::cout, classic, sparse); } else { out << "Classic non-zero items: "; for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { const auto& item = classic.get_item(i, j); if (item) { out << "[" << i << "," << j << "]=" << item << " "; } } } out << std::endl; out << "Sparse non-zero items: "; for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { const auto& item = sparse.get_item(i, j); if (item) { out << "[" << i << "," << j << "]=" << item << " "; } } } out << std::endl; } out << std::endl; } int main(int argc, char* argv[]) { // default values int height = 1000; int width = 1000; double fill_factor = -2; bool user_dialog = false; bool generate = false; // handling arguments if (argc == 2) { if (std::string(argv[1]) == "-ui") { user_dialog = true; generate = false; } else { fill_factor = std::atof(argv[1]); generate = true; } } else if (argc == 3) { fill_factor = std::atoi(argv[1]); height = width = std::atoi(argv[2]); generate = true; } else if (argc == 4) { fill_factor = std::atof(argv[1]); height = std::atoi(argv[2]); width = std::atoi(argv[3]); generate = true; } // classic matrix Matrix::ClassicMatrix<int> a_classic(height, width); Matrix::ClassicMatrix<int> b_classic(height, width); Matrix::ClassicMatrix<int> c_classic(height, width); // sparse matrix // replace 'SparseMatrixOptimized' with 'SparseMatrix' in the following 3 lines to use 'truth' algorithm Matrix::SparseMatrixOptimized<int> a_sparse(height, width); Matrix::SparseMatrixOptimized<int> b_sparse(height, width); Matrix::SparseMatrixOptimized<int> c_sparse(height, width); // generate matrix if (generate) { std::cout << "Generating matrix (fill factor is " << fill_factor << ")..." << std::endl; std::uniform_int_distribution<> item_distribution(1, 10); Generator::FillRandom(item_distribution, a_classic, fill_factor); Generator::FillRandom(item_distribution, b_classic, fill_factor); } else { // read std::cout << "Reading matrix..." << std::endl; // with ui if (user_dialog) { std::cout << "Matrix A:" << std::endl; ReadMatrixDialog(a_classic, false); b_classic.Resize(a_classic.get_height(), a_classic.get_width()); std::cout << "Matrix B:" << std::endl; ReadMatrixDialog(b_classic, true); } else { // from input stream std::cin >> a_classic; std::cin >> b_classic; } height = a_classic.get_height(); width = a_classic.get_width(); if (a_classic.get_height() != b_classic.get_height() || a_classic.get_width() != b_classic.get_width()) { std::cerr << "Invalid matrix size: matrix sizes must be equal." << std::endl; return -1; } } // copy matrix static_cast<Matrix::MatrixBase<int>&>(a_sparse) = a_classic; static_cast<Matrix::MatrixBase<int>&>(b_sparse) = b_classic; // run tests std::cout << "Adding matrix..." << std::endl; time_t classic_time = std::clock(); c_classic = a_classic + b_classic; classic_time = std::clock() - classic_time; time_t sparse_time = std::clock(); c_sparse = a_sparse + b_sparse; sparse_time = std::clock() - sparse_time; // work is done std::cout << "Done!" << std::endl << std::endl; // print matrix std::cout << "Matrix A: " << std::endl; PrintMatrix(std::cout, a_classic, a_sparse); std::cout << "Matrix B: " << std::endl; PrintMatrix(std::cout, b_classic, b_sparse); std::cout << "Matrix C = A + B: " << std::endl; PrintMatrix(std::cout, c_classic, c_sparse); std::cout << "Equality check:" << std::endl; std::cout << " Classic A " << (a_classic == a_sparse ? '=' : '!') << "= sparse A" << std::endl; std::cout << " Classic B " << (b_classic == b_sparse ? '=' : '!') << "= sparse B" << std::endl; std::cout << " Classic C " << (c_classic == c_sparse ? '=' : '!') << "= sparse C" << std::endl; std::cout << std::endl; // test results const size_t a_classic_size = a_classic.get_size(); const size_t b_classic_size = b_classic.get_size(); const size_t c_classic_size = c_classic.get_size(); const size_t a_sparse_size = a_sparse.get_size(); const size_t b_sparse_size = b_sparse.get_size(); const size_t c_sparse_size = c_sparse.get_size(); // print test result std::cout << "Classic matrix (" << a_classic.get_height() << 'x' << a_classic.get_width() << "):" << std::endl; std::cout << " Addition time: " << classic_time << std::endl; std::cout << " Size of A: " << a_classic_size << std::endl; std::cout << " Size of B: " << b_classic_size << std::endl; std::cout << " Size of C: " << c_classic_size << std::endl; std::cout << std::endl; std::cout << "Sparse matrix (" << a_sparse.get_height() << 'x' << a_sparse.get_width() << "):" << std::endl; std::cout << " Addition time: " << sparse_time << " (ratio: " << static_cast<double>(sparse_time) / classic_time << ")" << std::endl; std::cout << " Size of A: " << a_sparse_size << " (ratio: " << static_cast<double>(a_sparse_size) / a_classic_size << ")" << std::endl; std::cout << " Size of B: " << b_sparse_size << " (ratio: " << static_cast<double>(b_sparse_size) / b_classic_size << ")" << std::endl; std::cout << " Size of C: " << c_sparse_size << " (ratio: " << static_cast<double>(c_sparse_size) / c_classic_size << ")" << std::endl; std::cout << std::endl; return 0; }
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/cmq/v20190304/model/TransactionPolicy.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cmq::V20190304::Model; using namespace std; TransactionPolicy::TransactionPolicy() : m_firstQueryIntervalHasBeenSet(false), m_maxQueryCountHasBeenSet(false) { } CoreInternalOutcome TransactionPolicy::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("FirstQueryInterval") && !value["FirstQueryInterval"].IsNull()) { if (!value["FirstQueryInterval"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `TransactionPolicy.FirstQueryInterval` IsUint64=false incorrectly").SetRequestId(requestId)); } m_firstQueryInterval = value["FirstQueryInterval"].GetUint64(); m_firstQueryIntervalHasBeenSet = true; } if (value.HasMember("MaxQueryCount") && !value["MaxQueryCount"].IsNull()) { if (!value["MaxQueryCount"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `TransactionPolicy.MaxQueryCount` IsUint64=false incorrectly").SetRequestId(requestId)); } m_maxQueryCount = value["MaxQueryCount"].GetUint64(); m_maxQueryCountHasBeenSet = true; } return CoreInternalOutcome(true); } void TransactionPolicy::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_firstQueryIntervalHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "FirstQueryInterval"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_firstQueryInterval, allocator); } if (m_maxQueryCountHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "MaxQueryCount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_maxQueryCount, allocator); } } uint64_t TransactionPolicy::GetFirstQueryInterval() const { return m_firstQueryInterval; } void TransactionPolicy::SetFirstQueryInterval(const uint64_t& _firstQueryInterval) { m_firstQueryInterval = _firstQueryInterval; m_firstQueryIntervalHasBeenSet = true; } bool TransactionPolicy::FirstQueryIntervalHasBeenSet() const { return m_firstQueryIntervalHasBeenSet; } uint64_t TransactionPolicy::GetMaxQueryCount() const { return m_maxQueryCount; } void TransactionPolicy::SetMaxQueryCount(const uint64_t& _maxQueryCount) { m_maxQueryCount = _maxQueryCount; m_maxQueryCountHasBeenSet = true; } bool TransactionPolicy::MaxQueryCountHasBeenSet() const { return m_maxQueryCountHasBeenSet; }
/************************************************************************* * * SCSC CONFIDENTIAL * __________________ * * Copyright (c) [2009] - [2012] * SubCarrier System Corp. (SCSC) * All Rights Reserved. * * NOTICE: All information contained herein is, and remains, * the property of SubCarrier System Corp. (SCSC) and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to SubCarrier System Corp. (SCSC) * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from SubCarrier System Corp. (SCSC). * * * This file is subject to the terms and conditions of use defined * in the files 'LICENSE.rft' or 'LICENSE.pdf' which is part of this * source code package. * * LIC: #Battelle_001_01_dbfff42a90727d02153511a33480572b# */ /* * Generated by asn1c-0.9.22 (http://lionet.info/asn1c) [SCSCrev09] * From ASN.1 module "DSRC" * found in "DSRC_R36_Source.ASN" * `asn1c -S/skeletons` */ #include "stdafx.h" #include <asn_internal.h> #include "SteeringWheelAngle.h" int SteeringWheelAngle_constraint(asn_TYPE_descriptor_t *td, const void *sptr, asn_app_constraint_failed_f *ctfailcb, void *app_key) { const OCTET_STRING_t *st = (const OCTET_STRING_t *)sptr; size_t size; if(!sptr) { _ASN_CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name, __FILE__, __LINE__); return -1; } size = st->size; if((size == 1)) { /* Constraint check succeeded */ return 0; } else { _ASN_CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)", td->name, __FILE__, __LINE__); return -1; } } /* * This type is implemented using OCTET_STRING, * so here we adjust the DEF accordingly. */ static void SteeringWheelAngle_1_inherit_TYPE_descriptor(asn_TYPE_descriptor_t *td) { td->free_struct = asn_DEF_OCTET_STRING.free_struct; td->print_struct = asn_DEF_OCTET_STRING.print_struct; td->ber_decoder = asn_DEF_OCTET_STRING.ber_decoder; td->der_encoder = asn_DEF_OCTET_STRING.der_encoder; td->xer_decoder = asn_DEF_OCTET_STRING.xer_decoder; td->xer_encoder = asn_DEF_OCTET_STRING.xer_encoder; td->uper_decoder = asn_DEF_OCTET_STRING.uper_decoder; td->uper_encoder = asn_DEF_OCTET_STRING.uper_encoder; if(!td->per_constraints) td->per_constraints = asn_DEF_OCTET_STRING.per_constraints; td->elements = asn_DEF_OCTET_STRING.elements; td->elements_count = asn_DEF_OCTET_STRING.elements_count; td->specifics = asn_DEF_OCTET_STRING.specifics; } void SteeringWheelAngle_free(asn_TYPE_descriptor_t *td, void *struct_ptr, int contents_only) { SteeringWheelAngle_1_inherit_TYPE_descriptor(td); td->free_struct(td, struct_ptr, contents_only); } int SteeringWheelAngle_print(asn_TYPE_descriptor_t *td, const void *struct_ptr, int ilevel, asn_app_consume_bytes_f *cb, void *app_key) { SteeringWheelAngle_1_inherit_TYPE_descriptor(td); return td->print_struct(td, struct_ptr, ilevel, cb, app_key); } asn_dec_rval_t SteeringWheelAngle_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **structure, const void *bufptr, size_t size, int tag_mode) { SteeringWheelAngle_1_inherit_TYPE_descriptor(td); return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode); } asn_enc_rval_t SteeringWheelAngle_encode_der(asn_TYPE_descriptor_t *td, void *structure, int tag_mode, ber_tlv_tag_t tag, asn_app_consume_bytes_f *cb, void *app_key) { SteeringWheelAngle_1_inherit_TYPE_descriptor(td); return td->der_encoder(td, structure, tag_mode, tag, cb, app_key); } asn_dec_rval_t SteeringWheelAngle_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, void **structure, const char *opt_mname, const void *bufptr, size_t size) { SteeringWheelAngle_1_inherit_TYPE_descriptor(td); return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size); } asn_enc_rval_t SteeringWheelAngle_encode_xer(asn_TYPE_descriptor_t *td, void *structure, int ilevel, enum xer_encoder_flags_e flags, asn_app_consume_bytes_f *cb, void *app_key) { SteeringWheelAngle_1_inherit_TYPE_descriptor(td); return td->xer_encoder(td, structure, ilevel, flags, cb, app_key); } static ber_tlv_tag_t asn_DEF_SteeringWheelAngle_tags_1[] = { (ASN_TAG_CLASS_UNIVERSAL | (4 << 2)) }; asn_TYPE_descriptor_t asn_DEF_SteeringWheelAngle = { "SteeringWheelAngle", "SteeringWheelAngle", SteeringWheelAngle_free, SteeringWheelAngle_print, SteeringWheelAngle_constraint, SteeringWheelAngle_decode_ber, SteeringWheelAngle_encode_der, SteeringWheelAngle_decode_xer, SteeringWheelAngle_encode_xer, 0, 0, /* No PER support, use "-gen-PER" to enable */ 0, /* Use generic outmost tag fetcher */ asn_DEF_SteeringWheelAngle_tags_1, sizeof(asn_DEF_SteeringWheelAngle_tags_1) /sizeof(asn_DEF_SteeringWheelAngle_tags_1[0]), /* 1 */ asn_DEF_SteeringWheelAngle_tags_1, /* Same as above */ sizeof(asn_DEF_SteeringWheelAngle_tags_1) /sizeof(asn_DEF_SteeringWheelAngle_tags_1[0]), /* 1 */ 0, /* No PER visible constraints */ 0, 0, /* No members */ 0 /* No specifics */ }; /* Utility Calls */ /* Utility Calls */ // Set all basic structure pointers to 'safe' null values void SteeringWheelAngle_Init ( SteeringWheelAngle_t* theObj) { if (theObj != NULL) { // Allocate memory needed on heap int bufSize = SteeringWheelAngle_BuffSize; theObj->buf = (uint8_t *) malloc(bufSize); assert(theObj->buf); theObj->size = bufSize; // As per clause 7.115 Data Element: DE_SteeringWheelAngle theObj->buf[0] = 0x7F; // unavailable value theObj->_asn_ctx.ptr = NULL; // not used } } // Not used in this object // Move the structure into the packed bytes of the blob void SteeringWheelAngle_ToBlob ( SteeringWheelAngle_t* theObj, char* theBlob) { if ((theObj != NULL) && (theBlob != NULL)) { } } // Not used in this object // Fill the structure from the packed bytes of the blob void SteeringWheelAngle_FromBlob ( SteeringWheelAngle_t* theObj, char* theBlob) { if ((theObj != NULL) && (theBlob != NULL)) { } }
#include "DQMServices/Core/interface/Standalone.h" #include "DQMServices/Core/interface/DQMStore.h" #include "DQMServices/Core/interface/MonitorElement.h" #include "classlib/utils/DebugAids.h" #include "classlib/utils/Signal.h" #include "TROOT.h" #include <iostream> #include <cstdlib> #include <cerrno> #ifndef _NSIG #define _NSIG NSIG #endif typedef dqm::legacy::DQMStore DQMStore; typedef dqm::legacy::MonitorElement MonitorElement; static const int FATAL_OPTS = (lat::Signal::FATAL_DEFAULT & ~(lat::Signal::FATAL_ON_INT | lat::Signal::FATAL_ON_QUIT | lat::Signal::FATAL_DUMP_CORE)); // ------------------------------------------------------------------- // Always abort on assertion failure. static char onAssertFail(const char *message) { std::cout.flush(); fflush(stdout); std::cerr.flush(); fflush(stderr); std::cerr << message << "ABORTING\n"; return 'a'; } // ------------------------------------------------------------------- // Main program. int main(int argc, char **argv) { // Install base debugging support. lat::DebugAids::failHook(&onAssertFail); lat::Signal::handleFatal(argv[0], IOFD_INVALID, nullptr, nullptr, FATAL_OPTS); // Re-capture signals from ROOT after ROOT has initialised. ROOT::GetROOT(); for (int sig = 1; sig < _NSIG; ++sig) lat::Signal::revert(sig); lat::Signal::handleFatal(argv[0], IOFD_INVALID, nullptr, nullptr, FATAL_OPTS); // Check command line arguments. char *output = (argc > 1 ? argv[1] : nullptr); if (!output) { std::cerr << "Usage: " << argv[0] << " OUTPUT-FILE FILE...\n"; return 1; } // Process each file given as argument. edm::ParameterSet emptyps; std::vector<edm::ParameterSet> emptyset; edm::ServiceToken services(edm::ServiceRegistry::createSet(emptyset)); edm::ServiceRegistry::Operate operate(services); DQMStore store(emptyps); for (int arg = 2; arg < argc; ++arg) try { // Read in the file. store.open(argv[arg]); } catch (std::exception &e) { std::cerr << "*** FAILED TO READ FILE " << argv[arg] << ":\n" << e.what() << std::endl; exit(1); } store.save(output); return 0; }
#ifndef LOX_APPLICATION_HPP #define LOX_APPLICATION_HPP #pragma once #include <Screen/Interface/ISreen.hpp> class Application { private: bool running = true; IScreen *screen = nullptr; Application( ) = default; public: // Constructs Application( Application const & ) = delete; // Copy construct Application( Application && ) = delete; // Move construct static Application &GetInstance( ); void OnExecute( ); void OnExit( ); void SetScreen( IScreen &nIScreen ); // Operator Application &operator=( Application const & ) = delete; // Copy assign Application &operator=( Application && ) = delete; // Move assign }; #endif //LOX_APPLICATION_HPP
#include "sys.h" #include <time.h> #include <assert.h> #ifdef _WIN32 #include <windows.h> #else #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <execinfo.h> #include <signal.h> #include <sys/resource.h> #endif namespace sing { //////////////////////// // // WIN32 VERSIONS // /////////////////////// #ifdef _WIN32 // implemented in str.cpp std::string utf16_to_8(const wchar_t *src); void utf8_to_16(const char *src, std::vector<wchar_t> *dst); // PROCESSES int32_t system(const char *command) { std::vector<wchar_t> wcommand; utf8_to_16(command, &wcommand); return(::_wsystem(wcommand.data())); } Phandle execute(const char *command) { std::vector<wchar_t> wcommand; utf8_to_16(command, &wcommand); PROCESS_INFORMATION piProcInfo; STARTUPINFOW siStartInfo; BOOL bSuccess = FALSE; ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) ); ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) ); siStartInfo.cb = sizeof(STARTUPINFO); bSuccess = CreateProcessW(&wcommand[0], NULL, // command line NULL, // process security attributes NULL, // primary thread security attributes FALSE, // handles are inherited 0, // creation flags NULL, // use parent's environment NULL, // use parent's current directory &siStartInfo, // STARTUPINFO pointer &piProcInfo); // receives PROCESS_INFORMATION if ( !bSuccess ) return(0); return((Phandle)piProcInfo.hProcess); } class Pipe final : public Stream { HANDLE hh_; public: Pipe() { hh_ = nullptr; } void SetHandle(HANDLE hh) { hh_ = hh; } virtual ~Pipe(); virtual void *get__id() const override { return(nullptr); } // unknown type for sing !! virtual Error get(uint8_t *value) override; virtual Error gets(const int64_t maxbytes, std::string *value) override; virtual Error read(const int64_t count, std::vector<uint8_t> *dst, const bool append = true) override; virtual Error put(const uint8_t value) override; virtual Error puts(const char *value) override; virtual Error write(const int64_t count, const std::vector<uint8_t> &src, const int64_t from = 0) override; virtual Error seek(const int64_t pos, SeekMode mode = SeekMode::seek_set) override { return(-1); } virtual Error tell(int64_t *pos) override { return(-1); } virtual bool eof() const override; virtual Error close() override; }; Pipe::~Pipe() { close(); } Error Pipe::close() { if (hh_ != nullptr) { CloseHandle(hh_); hh_ = nullptr; } return(0); } Error Pipe::get(uint8_t *value) { DWORD dwRead; if (!ReadFile(hh_, value, 1, &dwRead, NULL) || dwRead == 0 ) return(-1); return(0); } Error Pipe::gets(const int64_t maxbytes, std::string *value) { uint8_t cc = 0; *value = ""; do { if (get(&cc) != 0) return(-1); if (cc != 0) *value += cc; } while (cc != '\n' && cc != 0 && (int64_t)value->length() < maxbytes); size_t len = value->length(); if (len > 1 && value->at(len - 1) == '\n' && value->at(len - 2) == '\r') { value->resize(len - 2); *value += '\n'; } return(0); } Error Pipe::read(const int64_t count, std::vector<uint8_t> *dst, const bool append) { DWORD dwRead; size_t pos; if (count < 0) return(-1); if (append) { pos = dst->size(); dst->resize(pos + (size_t)count); } else { pos = 0; dst->clear(); dst->resize(count); } if (!ReadFile(hh_, &(*dst)[pos], count, &dwRead, NULL) || (int64_t)dwRead != count) return(-1); return(0); } Error Pipe::put(const uint8_t value) { DWORD dwWritten; if (!WriteFile(hh_, &value, 1, &dwWritten, NULL)) return(-1); return(0); } Error Pipe::puts(const char *value) { DWORD dwWritten; if (!WriteFile(hh_, value, strlen(value), &dwWritten, NULL)) return(-1); return(0); } Error Pipe::write(const int64_t count, const std::vector<uint8_t> &src, const int64_t from) { DWORD dwWritten; if (from < 0) return(-1); int64_t towrite = std::min(count, (int64_t)src.size() - from); if (towrite > 0) { if (!WriteFile(hh_, src.data(), src.size(), &dwWritten, NULL)) return(-1); } return(0); } bool Pipe::eof() const { return(false); } Phandle automate(const char *command, std::shared_ptr<Stream> *sstdin, std::shared_ptr<Stream> *sstdout, std::shared_ptr<Stream> *sstderr) { std::vector<wchar_t> wcommand; utf8_to_16(command, &wcommand); std::shared_ptr<Pipe> pin = std::make_shared<Pipe>(); std::shared_ptr<Pipe> pout = std::make_shared<Pipe>(); std::shared_ptr<Pipe> perr = std::make_shared<Pipe>(); // craete the pipes SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; HANDLE childout_rd = nullptr; HANDLE childout_wr = nullptr; HANDLE childin_rd = nullptr; HANDLE childin_wr = nullptr; HANDLE childerr_rd = nullptr; HANDLE childerr_wr = nullptr; PROCESS_INFORMATION piProcInfo; STARTUPINFOW siStartInfo; BOOL bSuccess = FALSE; if (!CreatePipe(&childout_rd, &childout_wr, &saAttr, 0)) { goto cleanup; } if (!SetHandleInformation(childout_rd, HANDLE_FLAG_INHERIT, 0)) { // forbit inheritance goto cleanup; } if (!CreatePipe(&childin_rd, &childin_wr, &saAttr, 0)) { goto cleanup; } if (!SetHandleInformation(childin_wr, HANDLE_FLAG_INHERIT, 0)) { // forbit inheritance goto cleanup; } if (!CreatePipe(&childerr_rd, &childerr_wr, &saAttr, 0)) { goto cleanup; } if (!SetHandleInformation(childerr_rd, HANDLE_FLAG_INHERIT, 0)) { // forbit inheritance goto cleanup; } ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) ); ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) ); siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.hStdError = childerr_wr; siStartInfo.hStdOutput = childout_wr; siStartInfo.hStdInput = childin_rd; siStartInfo.dwFlags |= STARTF_USESTDHANDLES; bSuccess = CreateProcessW(NULL, &wcommand[0], // command line NULL, // process security attributes NULL, // primary thread security attributes TRUE, // handles are inherited 0, // creation flags NULL, // use parent's environment NULL, // use parent's current directory &siStartInfo, // STARTUPINFO pointer &piProcInfo); // receives PROCESS_INFORMATION if (! bSuccess ) goto cleanup; // Close handles to the child process and its primary thread. CloseHandle(piProcInfo.hThread); // Close handles to the stdin and stdout pipes no longer needed by the child process. // If they are not explicitly closed, there is no way to recognize that the child process has ended. CloseHandle(childerr_wr); CloseHandle(childout_wr); CloseHandle(childin_rd); (*pin).SetHandle(childin_wr); (*pout).SetHandle(childout_rd); (*perr).SetHandle(childerr_rd); *sstdin = pin; *sstdout = pout; *sstderr = perr; return((Phandle)piProcInfo.hProcess); cleanup: if (childout_rd != nullptr) CloseHandle(childout_rd); if (childout_wr != nullptr) CloseHandle(childout_wr); if (childerr_rd != nullptr) CloseHandle(childerr_rd); if (childerr_wr != nullptr) CloseHandle(childerr_wr); if (childin_rd != nullptr) CloseHandle(childin_rd); if (childin_wr != nullptr) CloseHandle(childin_wr); return(0); } int32_t waitCommandExit(const Phandle handle) { DWORD ecode = 0; WaitForSingleObject((HANDLE)handle, INFINITE); GetExitCodeProcess((HANDLE)handle, &ecode); return((int32_t)ecode); } void exit(const int32_t retcode) { ::exit(retcode); } // ENVIRONMENT std::string getenv(const char *name) { std::vector<wchar_t> wkey; std::vector<wchar_t> value; utf8_to_16(name, &wkey); DWORD length = GetEnvironmentVariableW(wkey.data(), NULL, 0); if (length == 0) return(""); value.reserve(length + 1); if (GetEnvironmentVariableW(wkey.data(), value.data(), length + 1) == 0) { return(""); } return(utf16_to_8(value.data())); } void setenv(const char *name, const char *value, const bool override) { std::vector<wchar_t> wkey; std::vector<wchar_t> wval; utf8_to_16(name, &wkey); utf8_to_16(value, &wval); if (override || GetEnvironmentVariableW(wkey.data(), NULL, 0) == 0) { SetEnvironmentVariableW(wkey.data(), wval.data()); } } // time management void wait(const int32_t microseconds) { ::Sleep(microseconds / 1000); } int64_t time() { return((int64_t)::time(nullptr)); } int64_t clock() { LARGE_INTEGER count; QueryPerformanceCounter(&count); return(count.QuadPart); } int64_t clocksDiff(const int64_t before, const int64_t after) { static LARGE_INTEGER frequency; static bool frequency_known = false; if (!frequency_known) { QueryPerformanceFrequency(&frequency); frequency_known = true; } return((after - before) * 1000000 / frequency.QuadPart); } OsId getOs() { return(OsId::win); } #else //////////////////////// // // LINUX/UNIX VERSIONS // /////////////////////// // PROCESSES void exec(const char *command); int32_t system(const char *command) { return(::system(command)); } Phandle execute(const char *command) { int nChild; nChild = fork(); if (0 == nChild) { // child continues here exec(command); } else if (nChild > 0) { // parent continues here return(nChild); } return(0); } void exec(const char *command) { std::vector<char> commandv; std::vector<char*> argv; commandv.reserve(strlen(command) + 1); // to prevent reallocations !! argv.reserve(16); bool quoted = false; bool separator = true; while (*command != 0) { if (separator) { if (*command != ' ' && *command != '\t') { if (*command == '"') { quoted = true; argv.push_back(&commandv.back() + 1); // where we are going to place the firs char } else { commandv.push_back(*command); argv.push_back(&commandv.back()); } separator = false; } } else if (quoted) { if (*command == '"') { quoted = false; } else { commandv.push_back(*command); } } else { if (*command == ' ' || *command == '\t') { commandv.push_back(0); separator = true; } else { commandv.push_back(*command); } } command++; } commandv.push_back(0); argv.push_back(nullptr); execvp(argv[0], argv.data()); // if we are here exec failed ::exit(0); } class Pipe final : public Stream { int hh_; public: Pipe() { hh_ = -1; } void SetHandle(int hh) { hh_ = hh; } virtual ~Pipe(); virtual void *get__id() const override { return(nullptr); } // unknown type for sing !! virtual Error get(uint8_t *value) override; virtual Error gets(const int64_t maxbytes, std::string *value) override; virtual Error read(const int64_t count, std::vector<uint8_t> *dst, const bool append = true) override; virtual Error put(const uint8_t value) override; virtual Error puts(const char *value) override; virtual Error write(const int64_t count, const std::vector<uint8_t> &src, const int64_t from = 0) override; virtual Error seek(const int64_t pos, SeekMode mode = SeekMode::seek_set) override { return(-1); } virtual Error tell(int64_t *pos) override { return(-1); } virtual bool eof() const override; virtual Error close() override; }; Pipe::~Pipe() { close(); } Error Pipe::close() { if (hh_ != -1) { return(::close(hh_)); hh_ = -1; } return(0); } Error Pipe::get(uint8_t *value) { int ret = ::read(hh_, value, 1); if (ret != 1) { return(-1); } return(0); } Error Pipe::gets(const int64_t maxbytes, std::string *value) { uint8_t cc = 0; *value = ""; do { if (get(&cc) != 0) return(-1); if (cc != 0) *value += cc; } while (cc != '\n' && cc != 0 && (int64_t)value->length() < maxbytes); size_t len = value->length(); if (len > 1 && value->at(len - 1) == '\n' && value->at(len - 2) == '\r') { value->resize(len - 2); *value += '\n'; } return(0); } Error Pipe::read(const int64_t count, std::vector<uint8_t> *dst, const bool append) { size_t pos; if (count < 0) return(-1); if (append) { pos = dst->size(); dst->resize(pos + (size_t)count); } else { pos = 0; dst->clear(); dst->resize(count); } if (::read(hh_, &(*dst)[pos], count) != count) { return(-1); } return(0); } Error Pipe::put(const uint8_t value) { if (::write(hh_, &value, 1) != 1) { return(-1); } return(0); } Error Pipe::puts(const char *value) { size_t towrite = strlen(value); if (towrite < 1) return(0); if (::write(hh_, value, towrite) != towrite) { return(-1); } return(0); } Error Pipe::write(const int64_t count, const std::vector<uint8_t> &src, const int64_t from) { if (from < 0) return(-1); int64_t towrite = std::min(count, (int64_t)src.size() - from); if (towrite > 0) { if (::write(hh_, src.data(), src.size()) != src.size()) { return(-1); } } return(0); } bool Pipe::eof() const { return(false); } Phandle automate(const char *command, std::shared_ptr<Stream> *sstdin, std::shared_ptr<Stream> *sstdout, std::shared_ptr<Stream> *sstderr) { static const int PIPE_READ = 0; static const int PIPE_WRITE = 1; std::shared_ptr<Pipe> pin = std::make_shared<Pipe>(); std::shared_ptr<Pipe> pout = std::make_shared<Pipe>(); std::shared_ptr<Pipe> perr = std::make_shared<Pipe>(); int aStdinPipe[2] = {-1, -1}; int aStdoutPipe[2] = {-1, -1}; int aStderrPipe[2] = {-1, -1}; int nChild; if (pipe(aStdinPipe) < 0) { goto cleanup; } if (pipe(aStdoutPipe) < 0) { goto cleanup; } if (pipe(aStderrPipe) < 0) { goto cleanup; } nChild = fork(); if (nChild == 0) { close(aStdinPipe[PIPE_WRITE]); close(aStdoutPipe[PIPE_READ]); close(aStderrPipe[PIPE_READ]); dup2(aStdinPipe[PIPE_READ], STDIN_FILENO); dup2(aStdoutPipe[PIPE_WRITE], STDOUT_FILENO); dup2(aStderrPipe[PIPE_WRITE], STDERR_FILENO); close(aStdinPipe[PIPE_READ]); close(aStdoutPipe[PIPE_WRITE]); close(aStderrPipe[PIPE_WRITE]); exec(command); } close(aStdinPipe[PIPE_READ]); close(aStdoutPipe[PIPE_WRITE]); close(aStderrPipe[PIPE_WRITE]); if (nChild > 0) { (*pin).SetHandle(aStdinPipe[PIPE_WRITE]); (*pout).SetHandle(aStdoutPipe[PIPE_READ]); (*perr).SetHandle(aStderrPipe[PIPE_READ]); *sstdin = pin; *sstdout = pout; *sstderr = perr; } return nChild; cleanup: if (aStdinPipe[PIPE_READ] != -1) close(aStdinPipe[PIPE_READ]); if (aStdinPipe[PIPE_WRITE] != -1) close(aStdinPipe[PIPE_WRITE]); if (aStdoutPipe[PIPE_READ] != -1) close(aStdoutPipe[PIPE_READ]); if (aStdoutPipe[PIPE_WRITE] != -1) close(aStdoutPipe[PIPE_WRITE]); if (aStderrPipe[PIPE_READ] != -1) close(aStderrPipe[PIPE_READ]); if (aStderrPipe[PIPE_WRITE] != -1) close(aStderrPipe[PIPE_WRITE]); return 0; } int32_t waitCommandExit(const Phandle handle) { if (handle > 0) { int status; waitpid(handle, &status, 0); if (WIFEXITED(status)) { return(WEXITSTATUS(status)); } } return(0); } void exit(const int32_t retcode) { ::exit(retcode); } // ENVIRONMENT std::string getenv(const char *name) { char *value = ::getenv(name); if (value == nullptr) { return(""); } return(value); } void setenv(const char *name, const char *value, const bool override) { ::setenv(name, value, override ? 1 : 0); } // time management void wait(const int32_t microseconds) { timespec tts; tts.tv_sec = microseconds / 1000000; tts.tv_nsec = (microseconds - tts.tv_sec * 1000000) * 1000; nanosleep(&tts, nullptr); } int64_t time() { return((int64_t)::time(nullptr)); } int64_t clock() { timespec ts; clock_gettime(CLOCK_BOOTTIME, &ts); return(ts.tv_sec * 1000000 + ts.tv_nsec / 1000); } int64_t clocksDiff(const int64_t before, const int64_t after) { return(after - before); } void localtime_s(struct tm *bb, const time_t *tt) { tzset(); localtime_r(tt, bb); } void gmtime_s(struct tm *bb, const time_t *tt) { gmtime_r(tt, bb); } OsId getOs() { return(OsId::linux); } #endif //////////////////////// // // COMMON LINUX/UNIX/WINDOWS VERSIONS // /////////////////////// BrokenTime::BrokenTime() { second_ = 0; minute_ = 0; hour_ = 0; mday_ = 0; mon_ = 0; wday_ = 0; yday_ = 0; savings_ = false; year_ = 0; } void BrokenTime::fillLocal(const int64_t time) { struct tm broken; time_t tt = (time_t)time; localtime_s(&broken, &tt); second_ = broken.tm_sec; minute_ = broken.tm_min; hour_ = broken.tm_hour; mday_ = broken.tm_mday; mon_ = broken.tm_mon; wday_ = broken.tm_wday; yday_ = broken.tm_yday; savings_ = broken.tm_isdst > 0; year_ = broken.tm_year + 1900; } void BrokenTime::fillUtc(const int64_t time) { struct tm broken; time_t tt = (time_t)time; gmtime_s(&broken, &tt); second_ = broken.tm_sec; minute_ = broken.tm_min; hour_ = broken.tm_hour; mday_ = broken.tm_mday; mon_ = broken.tm_mon; wday_ = broken.tm_wday; yday_ = broken.tm_yday; savings_ = broken.tm_isdst > 0; year_ = broken.tm_year + 1900; } // random numbers void RndGen::rndSeed(const int64_t seed) { seed_ = (uint64_t)seed; } uint64_t RndGen::rndU64() { seed_ = seed_ * 6364136223846793005 + 1442695040888963407; return(seed_); } RndGen::RndGen() { seed_ = 0; } double RndGen::rnd() { double val = (double)(rndU64() & 0x3fffffffffffffffL) / (double)0x4000000000000000L; return(val == 1.0f ? 0.0f : val); // wrap around } double RndGen::rndNorm() { for (int attempt = 200; attempt > 0; --attempt) { double val = rnd() * 14 - 7; // -7..7 values > 7 are about once in 10^22 cases, we ignore them. // based on the value, reduce the likelihood to be returned. // (discard it with a probability which increses with value) if (rnd() < exp(-0.5 * val * val)) { return(val); } } return(0); // this happens about once in 10^14 calls } // mix void validate(const bool condition) { assert(condition); } } // namespace
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/http/http_stream_factory_impl_request.h" #include "base/callback.h" #include "base/logging.h" #include "base/stl_util.h" #include "net/http/http_stream_factory_impl_job.h" #include "net/spdy/spdy_http_stream.h" #include "net/spdy/spdy_session.h" namespace net { HttpStreamFactoryImpl::Request::Request( const GURL& url, HttpStreamFactoryImpl* factory, HttpStreamRequest::Delegate* delegate, WebSocketHandshakeStreamBase::CreateHelper* websocket_handshake_stream_create_helper, const BoundNetLog& net_log) : url_(url), factory_(factory), websocket_handshake_stream_create_helper_( websocket_handshake_stream_create_helper), delegate_(delegate), net_log_(net_log), completed_(false), was_npn_negotiated_(false), protocol_negotiated_(kProtoUnknown), using_spdy_(false) { DCHECK(factory_); DCHECK(delegate_); net_log_.BeginEvent(NetLog::TYPE_HTTP_STREAM_REQUEST); } HttpStreamFactoryImpl::Request::~Request() { if (bound_job_.get()) DCHECK(jobs_.empty()); else DCHECK(!jobs_.empty()); net_log_.EndEvent(NetLog::TYPE_HTTP_STREAM_REQUEST); for (std::set<Job*>::iterator it = jobs_.begin(); it != jobs_.end(); ++it) factory_->request_map_.erase(*it); RemoveRequestFromSpdySessionRequestMap(); RemoveRequestFromHttpPipeliningRequestMap(); STLDeleteElements(&jobs_); } void HttpStreamFactoryImpl::Request::SetSpdySessionKey( const SpdySessionKey& spdy_session_key) { DCHECK(!spdy_session_key_.get()); spdy_session_key_.reset(new SpdySessionKey(spdy_session_key)); RequestSet& request_set = factory_->spdy_session_request_map_[spdy_session_key]; DCHECK(!ContainsKey(request_set, this)); request_set.insert(this); } bool HttpStreamFactoryImpl::Request::SetHttpPipeliningKey( const HttpPipelinedHost::Key& http_pipelining_key) { CHECK(!http_pipelining_key_.get()); http_pipelining_key_.reset(new HttpPipelinedHost::Key(http_pipelining_key)); bool was_new_key = !ContainsKey(factory_->http_pipelining_request_map_, http_pipelining_key); RequestVector& request_vector = factory_->http_pipelining_request_map_[http_pipelining_key]; request_vector.push_back(this); return was_new_key; } void HttpStreamFactoryImpl::Request::AttachJob(Job* job) { DCHECK(job); jobs_.insert(job); factory_->request_map_[job] = this; } void HttpStreamFactoryImpl::Request::Complete( bool was_npn_negotiated, NextProto protocol_negotiated, bool using_spdy, const BoundNetLog& job_net_log) { DCHECK(!completed_); completed_ = true; was_npn_negotiated_ = was_npn_negotiated; protocol_negotiated_ = protocol_negotiated; using_spdy_ = using_spdy; net_log_.AddEvent( NetLog::TYPE_HTTP_STREAM_REQUEST_BOUND_TO_JOB, job_net_log.source().ToEventParametersCallback()); job_net_log.AddEvent( NetLog::TYPE_HTTP_STREAM_JOB_BOUND_TO_REQUEST, net_log_.source().ToEventParametersCallback()); } void HttpStreamFactoryImpl::Request::OnStreamReady( Job* job, const SSLConfig& used_ssl_config, const ProxyInfo& used_proxy_info, HttpStreamBase* stream) { DCHECK(!factory_->for_websockets_); DCHECK(stream); DCHECK(completed_); OnJobSucceeded(job); delegate_->OnStreamReady(used_ssl_config, used_proxy_info, stream); } void HttpStreamFactoryImpl::Request::OnWebSocketHandshakeStreamReady( Job* job, const SSLConfig& used_ssl_config, const ProxyInfo& used_proxy_info, WebSocketHandshakeStreamBase* stream) { DCHECK(factory_->for_websockets_); DCHECK(stream); DCHECK(completed_); OnJobSucceeded(job); delegate_->OnWebSocketHandshakeStreamReady( used_ssl_config, used_proxy_info, stream); } void HttpStreamFactoryImpl::Request::OnStreamFailed( Job* job, int status, const SSLConfig& used_ssl_config) { DCHECK_NE(OK, status); // |job| should only be NULL if we're being canceled by a late bound // HttpPipelinedConnection (one that was not created by a job in our |jobs_| // set). if (!job) { DCHECK(!bound_job_.get()); DCHECK(!jobs_.empty()); // NOTE(willchan): We do *NOT* call OrphanJobs() here. The reason is because // we *WANT* to cancel the unnecessary Jobs from other requests if another // Job completes first. } else if (!bound_job_.get()) { // Hey, we've got other jobs! Maybe one of them will succeed, let's just // ignore this failure. if (jobs_.size() > 1) { jobs_.erase(job); factory_->request_map_.erase(job); delete job; return; } else { bound_job_.reset(job); jobs_.erase(job); DCHECK(jobs_.empty()); factory_->request_map_.erase(job); } } else { DCHECK(jobs_.empty()); } delegate_->OnStreamFailed(status, used_ssl_config); } void HttpStreamFactoryImpl::Request::OnCertificateError( Job* job, int status, const SSLConfig& used_ssl_config, const SSLInfo& ssl_info) { DCHECK_NE(OK, status); if (!bound_job_.get()) OrphanJobsExcept(job); else DCHECK(jobs_.empty()); delegate_->OnCertificateError(status, used_ssl_config, ssl_info); } void HttpStreamFactoryImpl::Request::OnNeedsProxyAuth( Job* job, const HttpResponseInfo& proxy_response, const SSLConfig& used_ssl_config, const ProxyInfo& used_proxy_info, HttpAuthController* auth_controller) { if (!bound_job_.get()) OrphanJobsExcept(job); else DCHECK(jobs_.empty()); delegate_->OnNeedsProxyAuth( proxy_response, used_ssl_config, used_proxy_info, auth_controller); } void HttpStreamFactoryImpl::Request::OnNeedsClientAuth( Job* job, const SSLConfig& used_ssl_config, SSLCertRequestInfo* cert_info) { if (!bound_job_.get()) OrphanJobsExcept(job); else DCHECK(jobs_.empty()); delegate_->OnNeedsClientAuth(used_ssl_config, cert_info); } void HttpStreamFactoryImpl::Request::OnHttpsProxyTunnelResponse( Job *job, const HttpResponseInfo& response_info, const SSLConfig& used_ssl_config, const ProxyInfo& used_proxy_info, HttpStreamBase* stream) { if (!bound_job_.get()) OrphanJobsExcept(job); else DCHECK(jobs_.empty()); delegate_->OnHttpsProxyTunnelResponse( response_info, used_ssl_config, used_proxy_info, stream); } int HttpStreamFactoryImpl::Request::RestartTunnelWithProxyAuth( const AuthCredentials& credentials) { DCHECK(bound_job_.get()); return bound_job_->RestartTunnelWithProxyAuth(credentials); } void HttpStreamFactoryImpl::Request::SetPriority(RequestPriority priority) { for (std::set<HttpStreamFactoryImpl::Job*>::const_iterator it = jobs_.begin(); it != jobs_.end(); ++it) { (*it)->SetPriority(priority); } if (bound_job_) bound_job_->SetPriority(priority); } LoadState HttpStreamFactoryImpl::Request::GetLoadState() const { if (bound_job_.get()) return bound_job_->GetLoadState(); DCHECK(!jobs_.empty()); // Just pick the first one. return (*jobs_.begin())->GetLoadState(); } bool HttpStreamFactoryImpl::Request::was_npn_negotiated() const { DCHECK(completed_); return was_npn_negotiated_; } NextProto HttpStreamFactoryImpl::Request::protocol_negotiated() const { DCHECK(completed_); return protocol_negotiated_; } bool HttpStreamFactoryImpl::Request::using_spdy() const { DCHECK(completed_); return using_spdy_; } void HttpStreamFactoryImpl::Request::RemoveRequestFromSpdySessionRequestMap() { if (spdy_session_key_.get()) { SpdySessionRequestMap& spdy_session_request_map = factory_->spdy_session_request_map_; DCHECK(ContainsKey(spdy_session_request_map, *spdy_session_key_)); RequestSet& request_set = spdy_session_request_map[*spdy_session_key_]; DCHECK(ContainsKey(request_set, this)); request_set.erase(this); if (request_set.empty()) spdy_session_request_map.erase(*spdy_session_key_); spdy_session_key_.reset(); } } void HttpStreamFactoryImpl::Request::RemoveRequestFromHttpPipeliningRequestMap() { if (http_pipelining_key_.get()) { HttpPipeliningRequestMap& http_pipelining_request_map = factory_->http_pipelining_request_map_; DCHECK(ContainsKey(http_pipelining_request_map, *http_pipelining_key_)); RequestVector& request_vector = http_pipelining_request_map[*http_pipelining_key_]; for (RequestVector::iterator it = request_vector.begin(); it != request_vector.end(); ++it) { if (*it == this) { request_vector.erase(it); break; } } if (request_vector.empty()) http_pipelining_request_map.erase(*http_pipelining_key_); http_pipelining_key_.reset(); } } void HttpStreamFactoryImpl::Request::OnNewSpdySessionReady( Job* job, const base::WeakPtr<SpdySession>& spdy_session, bool direct) { DCHECK(job); DCHECK(job->using_spdy()); // The first case is the usual case. if (!bound_job_.get()) { OrphanJobsExcept(job); } else { // This is the case for HTTPS proxy tunneling. DCHECK_EQ(bound_job_.get(), job); DCHECK(jobs_.empty()); } // Cache these values in case the job gets deleted. const SSLConfig used_ssl_config = job->server_ssl_config(); const ProxyInfo used_proxy_info = job->proxy_info(); const bool was_npn_negotiated = job->was_npn_negotiated(); const NextProto protocol_negotiated = job->protocol_negotiated(); const bool using_spdy = job->using_spdy(); const BoundNetLog net_log = job->net_log(); Complete(was_npn_negotiated, protocol_negotiated, using_spdy, net_log); // Cache this so we can still use it if the request is deleted. HttpStreamFactoryImpl* factory = factory_; if (factory->for_websockets_) { // TODO(ricea): Re-instate this code when WebSockets over SPDY is // implemented. NOTREACHED(); } else { bool use_relative_url = direct || url().SchemeIs("https"); delegate_->OnStreamReady( job->server_ssl_config(), job->proxy_info(), new SpdyHttpStream(spdy_session, use_relative_url)); } // |this| may be deleted after this point. factory->OnNewSpdySessionReady(spdy_session, direct, used_ssl_config, used_proxy_info, was_npn_negotiated, protocol_negotiated, using_spdy, net_log); } void HttpStreamFactoryImpl::Request::OrphanJobsExcept(Job* job) { DCHECK(job); DCHECK(!bound_job_.get()); DCHECK(ContainsKey(jobs_, job)); bound_job_.reset(job); jobs_.erase(job); factory_->request_map_.erase(job); OrphanJobs(); } void HttpStreamFactoryImpl::Request::OrphanJobs() { RemoveRequestFromSpdySessionRequestMap(); RemoveRequestFromHttpPipeliningRequestMap(); std::set<Job*> tmp; tmp.swap(jobs_); for (std::set<Job*>::iterator it = tmp.begin(); it != tmp.end(); ++it) factory_->OrphanJob(*it, this); } void HttpStreamFactoryImpl::Request::OnJobSucceeded(Job* job) { // |job| should only be NULL if we're being serviced by a late bound // SpdySession or HttpPipelinedConnection (one that was not created by a job // in our |jobs_| set). if (!job) { DCHECK(!bound_job_.get()); DCHECK(!jobs_.empty()); // NOTE(willchan): We do *NOT* call OrphanJobs() here. The reason is because // we *WANT* to cancel the unnecessary Jobs from other requests if another // Job completes first. // TODO(mbelshe): Revisit this when we implement ip connection pooling of // SpdySessions. Do we want to orphan the jobs for a different hostname so // they complete? Or do we want to prevent connecting a new SpdySession if // we've already got one available for a different hostname where the ip // address matches up? } else if (!bound_job_.get()) { // We may have other jobs in |jobs_|. For example, if we start multiple jobs // for Alternate-Protocol. OrphanJobsExcept(job); } else { DCHECK(jobs_.empty()); } } } // namespace net
#include <iostream> #include <CGAL/basic.h> #ifdef CGAL_USE_LEDA #include <CGAL/leda_bigfloat.h> #include <CGAL/Test/_test_algebraic_structure.h> #include <CGAL/Test/_test_real_embeddable.h> int main() { typedef leda_bigfloat NT; typedef CGAL::Field_with_kth_root_tag Tag; typedef CGAL::Tag_false Is_exact; CGAL::test_algebraic_structure<NT,Tag, Is_exact>(); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(NT(4),NT(6),NT(15)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(NT(-4),NT(6),NT(15)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(NT(4),NT(-6),NT(15)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(NT(-4),NT(-6),NT(15)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(NT(4),NT(6),NT(-15)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(NT(-4),NT(6), NT(15)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(NT(4),NT(-6),NT(-15)); CGAL::test_algebraic_structure<NT,Tag, Is_exact>(NT(-4),NT(-6),NT(-15)); CGAL::test_real_embeddable<NT>(); return 0; } #else int main() { return 0; } #endif
// // kern_patcher.hpp // Lilu // // Copyright © 2016-2017 vit9696. All rights reserved. // #ifndef kern_patcher_hpp #define kern_patcher_hpp #include <Headers/kern_config.hpp> #include <Headers/kern_compat.hpp> #include <Headers/kern_util.hpp> #include <Headers/kern_mach.hpp> #include <Headers/kern_disasm.hpp> #include <mach/mach_types.h> namespace Patch { union All; void deleter(All *); } #ifdef LILU_KEXTPATCH_SUPPORT struct OSKextLoadedKextSummaryHeader; struct OSKextLoadedKextSummary; #endif /* LILU_KEXTPATCH_SUPPORT */ class KernelPatcher { public: /** * Errors set by functions */ enum class Error { NoError, NoKinfoFound, NoSymbolFound, KernInitFailure, KernRunningInitFailure, KextListeningFailure, DisasmFailure, MemoryIssue, MemoryProtection, PointerRange, AlreadyDone, LockError, Unsupported }; /** * Get last error * * @return error code */ EXPORT Error getError(); /** * Reset all the previous errors */ EXPORT void clearError(); /** * Initialise KernelPatcher, prepare for modifications */ void init(); /** * Deinitialise KernelPatcher, must be called regardless of the init error */ void deinit(); /** * Kernel write lock used for performing kernel & kext writes to disable cpu preemption * See MachInfo::setKernelWriting */ EXPORT static IOSimpleLock *kernelWriteLock; /** * Kext information */ struct KextInfo; #ifdef LILU_KEXTPATCH_SUPPORT struct KextInfo { static constexpr size_t Unloaded {0}; enum SysFlags : size_t { Loaded, // invoke for kext if it is already loaded Reloadable, // allow the kext to unload and get patched again Disabled, // do not load this kext (formerly achieved pathNum = 0, this no longer works) FSOnly, // do not use prelinkedkernel (kextcache) as a symbol source FSFallback, // perform fs fallback if kextcache failed Reserved, SysFlagNum, UserFlagNum = sizeof(size_t)-SysFlagNum }; static_assert(UserFlagNum > 0, "There should be at least one user flag"); const char *id {nullptr}; const char **paths {nullptr}; size_t pathNum {0}; bool sys[SysFlagNum] {}; bool user[UserFlagNum] {}; size_t loadIndex {Unloaded}; // Updated after loading }; static_assert(sizeof(KextInfo) == 5 * sizeof(size_t), "KextInfo is no longer ABI compatible"); #endif /* LILU_KEXTPATCH_SUPPORT */ /** * Loads and stores kinfo information locally * * @param id kernel item identifier * @param paths item filesystem path array * @param num number of path entries * @param isKernel kinfo is kernel info * @param fsonly avoid using prelinkedkernel for kexts * @param fsfallback fallback to reading from filesystem if prelink failed * * @return loaded kinfo id */ EXPORT size_t loadKinfo(const char *id, const char * const paths[], size_t num=1, bool isKernel=false, bool fsonly=false, bool fsfallback=false); #ifdef LILU_KEXTPATCH_SUPPORT /** * Loads and stores kinfo information locally * * @param info kext to load, updated on success * * @return loaded kinfo id */ EXPORT size_t loadKinfo(KextInfo *info); #endif /* LILU_KEXTPATCH_SUPPORT */ /** * Kernel kinfo id */ static constexpr size_t KernelID {0}; /** * Update running information * * @param id loaded kinfo id * @param slide loaded slide * @param size loaded memory size * @param force force recalculatiob */ EXPORT void updateRunningInfo(size_t id, mach_vm_address_t slide=0, size_t size=0, bool force=false); /** * Any kernel */ static constexpr uint32_t KernelAny {0}; /** * Check kernel compatibility * * @param min minimal requested version or KernelAny * @param max maximum supported version or KernelAny * * @return true on success */ EXPORT static bool compatibleKernel(uint32_t min, uint32_t max); /** * Solve a kinfo symbol * * @param id loaded kinfo id * @param symbol symbol to solve * * @return running symbol address or 0 */ EXPORT mach_vm_address_t solveSymbol(size_t id, const char *symbol); /** * Hook kext loading and unloading to access kexts at early stage */ EXPORT void setupKextListening(); /** * Free file buffer resources and effectively make prelinked kext loading impossible */ void freeFileBufferResources(); /** * Activates monitoring functions if necessary */ void activate(); /** * Load handling structure */ class KextHandler { using t_handler = void (*)(KextHandler *); KextHandler(const char * const i, size_t idx, t_handler h, bool l, bool r) : id(i), index(idx), handler(h), loaded(l), reloadable(r) {} public: static KextHandler *create(const char * const i, size_t idx, t_handler h, bool l=false, bool r=false) { return new KextHandler(i, idx, h, l, r); } static void deleter(KextHandler *i) { delete i; } void *self {nullptr}; const char * const id {nullptr}; size_t index {0}; mach_vm_address_t address {0}; size_t size {0}; t_handler handler {nullptr}; bool loaded {false}; bool reloadable {false}; }; #ifdef LILU_KEXTPATCH_SUPPORT /** * Enqueue handler processing at kext loading * * @param handler handler to process */ EXPORT void waitOnKext(KextHandler *handler); /** * Update kext handler features * * @param info loaded kext info with features */ void updateKextHandlerFeatures(KextInfo *info); /** * Arbitrary kext find/replace patch */ struct LookupPatch { KextInfo *kext; const uint8_t *find; const uint8_t *replace; size_t size; size_t count; }; /** * Apply a find/replace patch * * @param patch patch to apply */ EXPORT void applyLookupPatch(const LookupPatch *patch); #endif /* LILU_KEXTPATCH_SUPPORT */ /** * Route function to function * * @param from function to route * @param to routed function * @param buildWrapper create entrance wrapper * @param kernelRoute kernel change requiring memory protection changes and patch reverting at unload * @param revertible patches could be reverted * * @return wrapper pointer or 0 on success */ EXPORT mach_vm_address_t routeFunction(mach_vm_address_t from, mach_vm_address_t to, bool buildWrapper=false, bool kernelRoute=true, bool revertible=true); /** * Route block at assembly level * * @param from address to route * @param opcodes opcodes to insert * @param opnum number of opcodes * @param buildWrapper create entrance wrapper * @param kernelRoute kernel change requiring memory protection changes and patch reverting at unload * * @return wrapper pointer or 0 on success */ EXPORT mach_vm_address_t routeBlock(mach_vm_address_t from, const uint8_t *opcodes, size_t opnum, bool buildWrapper=false, bool kernelRoute=true); private: /** * The minimal reasonable memory requirement */ static constexpr size_t TempExecutableMemorySize {4096}; /** * As of 10.12 we seem to be not allowed to call vm_ functions from several places including onKextSummariesUpdated. */ static uint8_t tempExecutableMemory[TempExecutableMemorySize]; /** * Offset to tempExecutableMemory that is safe to use */ off_t tempExecutableMemoryOff {0}; /** * Patcher status */ bool activated {false}; /** * Created routed trampoline page * * @param func original area * @param min minimal amount of bytes that will be overwritten * @param opcodes opcodes to insert before function * @param opnum number of opcodes * * @return trampoline pointer or 0 */ mach_vm_address_t createTrampoline(mach_vm_address_t func, size_t min, const uint8_t *opcodes=nullptr, size_t opnum=0); #ifdef LILU_KEXTPATCH_SUPPORT /** * Called at kext loading and unloading if kext listening is enabled */ static void onKextSummariesUpdated(); /** * A pointer to loaded kext information */ OSKextLoadedKextSummaryHeader **loadedKextSummaries {nullptr}; /** * A pointer to kext summaries update */ void (*orgUpdateLoadedKextSummaries)(void) {nullptr}; /** * Process already loaded kexts once at the start * * @param summaries loaded kext summaries * @param num number of loaded kext summaries */ void processAlreadyLoadedKexts(OSKextLoadedKextSummary *summaries, size_t num); #endif /* LILU_KEXTPATCH_SUPPORT */ /** * Local disassmebler instance, initialised on demand */ Disassembler disasm; /** * Loaded kernel items */ evector<MachInfo *, MachInfo::deleter> kinfos; /** * Applied patches */ evector<Patch::All *, Patch::deleter> kpatches; #ifdef LILU_KEXTPATCH_SUPPORT /** * Awaiting kext notificators */ evector<KextHandler *, KextHandler::deleter> khandlers; /** * Awaiting already loaded kext list */ bool waitingForAlreadyLoadedKexts {false}; #endif /* LILU_KEXTPATCH_SUPPORT */ /** * Allocated pages */ evector<Page *, Page::deleter> kpages; /** * Current error code */ Error code {Error::NoError}; static constexpr size_t INVALID {0}; /** * Jump instruction sizes */ static constexpr size_t SmallJump {1 + sizeof(int32_t)}; static constexpr size_t LongJump {2 * sizeof(uint64_t)}; /** * Possible kernel paths */ #ifdef LILU_COMPRESSION_SUPPORT static constexpr size_t kernelPathsNum {10}; #else static constexpr size_t kernelPathsNum {4}; #endif /* LILU_COMPRESSION_SUPPORT */ const char *kernelPaths[kernelPathsNum] { #ifdef LILU_COMPRESSION_SUPPORT "/System/Library/Caches/com.apple.kext.caches/Startup/kernelcache", "/System/Library/PrelinkedKernels/prelinkedkernel", #endif /* LILU_COMPRESSION_SUPPORT */ "/System/Library/Kernels/kernel", //since 10.10 "/mach_kernel", #ifdef LILU_COMPRESSION_SUPPORT "/System/Library/Caches/com.apple.kext.caches/Startup/kernelcache.debug", "/System/Library/Caches/com.apple.kext.caches/Startup/kernelcache.development", "/System/Library/PrelinkedKernels/prelinkedkernel.debug", "/System/Library/PrelinkedKernels/prelinkedkernel.development", #endif /* LILU_COMPRESSION_SUPPORT */ "/System/Library/Kernels/kernel.debug", "/System/Library/Kernels/kernel.development" }; }; #endif /* kern_patcher_hpp */
/**************************************************************************** ** Meta object code from reading C++ file 'coincontroltreewidget.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.0.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../src/qt/coincontroltreewidget.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'coincontroltreewidget.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.0.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_CoinControlTreeWidget_t { QByteArrayData data[1]; char stringdata[23]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ offsetof(qt_meta_stringdata_CoinControlTreeWidget_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData) \ ) static const qt_meta_stringdata_CoinControlTreeWidget_t qt_meta_stringdata_CoinControlTreeWidget = { { QT_MOC_LITERAL(0, 0, 21) }, "CoinControlTreeWidget\0" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_CoinControlTreeWidget[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; void CoinControlTreeWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } const QMetaObject CoinControlTreeWidget::staticMetaObject = { { &QTreeWidget::staticMetaObject, qt_meta_stringdata_CoinControlTreeWidget.data, qt_meta_data_CoinControlTreeWidget, qt_static_metacall, 0, 0} }; const QMetaObject *CoinControlTreeWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *CoinControlTreeWidget::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CoinControlTreeWidget.stringdata)) return static_cast<void*>(const_cast< CoinControlTreeWidget*>(this)); return QTreeWidget::qt_metacast(_clname); } int CoinControlTreeWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QTreeWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
// Copyright (c) 2012-2018, The CryptoNote developers, The Bytecoin developers, [ ] developers. // Licensed under the GNU Lesser General Public License. See LICENSE for details. #include "Varint.hpp" #include <stdexcept> namespace common { template<class T> T uint_be_from_bytes(const unsigned char *buf, size_t si) { T result = 0; for (size_t i = 0; i != si; ++i) { result <<= 8; result |= buf[i]; } return result; } template<class T> void uint_be_to_bytes(unsigned char *buf, size_t si, T val) { for (size_t i = si; i-- > 0;) { buf[i] = static_cast<unsigned char>(val); val >>= 8; } } size_t get_varint_sqlite4_size(uint64_t val) { if (val <= 240) return 1; if (val <= 2287) return 2; if (val <= 67823) return 3; if (val <= 16777215) return 4; if (val <= 4294967295) return 5; if (val <= 1099511627775) return 6; if (val <= 281474976710655) return 7; if (val <= 72057594037927935) return 8; return 9; } uint64_t read_varint_sqlite4(const std::string &str) { const char *be = str.data(); const char *en = str.data() + str.size(); uint64_t val = read_varint_sqlite4(be, en); if (be != en) throw std::runtime_error("read_varint_sqlite4 excess symbols in string"); return val; } void read(const unsigned char *&begin, const unsigned char *end, unsigned char *to, size_t len) { if (end < begin + len) throw std::runtime_error("end of read"); memcpy(to, begin, len); begin += len; } uint64_t read_varint_sqlite4(const unsigned char *&begin, const unsigned char *end) { unsigned char a0; read(begin, end, &a0, 1); if (a0 <= 240) { return a0; } if (a0 <= 248) { unsigned char a1; read(begin, end, &a1, 1); return 240 + 256 * (a0 - 241) + a1; } if (a0 == 249) { unsigned char buf[2]; read(begin, end, buf, 2); return 2288 + 256 * buf[0] + buf[1]; } unsigned char buf[8]; int bytes = 3 + a0 - 250; read(begin, end, buf, bytes); return uint_be_from_bytes<uint64_t>(buf, bytes); } std::string str(const unsigned char *buf, size_t len) { return std::string((const char *)buf, len); } std::string write_varint_sqlite4(uint64_t val) { unsigned char buf[9]; if (val <= 240) { buf[0] = static_cast<unsigned char>(val); return str(buf, 1); } if (val <= 2287) { buf[0] = static_cast<unsigned char>((val - 240) / 256 + 241); buf[1] = static_cast<unsigned char>(val - 240); return str(buf, 2); } if (val <= 67823) { buf[0] = 249; buf[1] = static_cast<unsigned char>((val - 2288) / 256); buf[2] = static_cast<unsigned char>(val - 2288); return str(buf, 3); } if (val <= 16777215) { buf[0] = 250; uint_be_to_bytes<uint64_t>(buf + 1, 3, val); return str(buf, 4); } if (val <= 4294967295) { buf[0] = 251; uint_be_to_bytes<uint64_t>(buf + 1, 4, val); return str(buf, 5); } if (val <= 1099511627775) { buf[0] = 252; uint_be_to_bytes<uint64_t>(buf + 1, 5, val); return str(buf, 6); } if (val <= 281474976710655) { buf[0] = 253; uint_be_to_bytes<uint64_t>(buf + 1, 6, val); return str(buf, 7); } if (val <= 72057594037927935) { buf[0] = 254; uint_be_to_bytes<uint64_t>(buf + 1, 7, val); return str(buf, 8); } buf[0] = 255; uint_be_to_bytes<uint64_t>(buf + 1, 8, val); return str(buf, 9); } }
#include <cmath> #include <stack> #include <algorithm> #include <unordered_set> #include "emptyeisner3rd_depparser.h" namespace emptyeisner3rd { WordPOSTag DepParser::empty_taggedword = WordPOSTag(); WordPOSTag DepParser::start_taggedword = WordPOSTag(); WordPOSTag DepParser::end_taggedword = WordPOSTag(); DepParser::DepParser(const std::string & sFeatureInput, const std::string & sFeatureOut, int nState) : DepParserBase(nState), m_tWords(1), m_tPOSTags(1), m_tEmptys(1), m_fLambda(-1.0) { m_nSentenceLength = 0; m_pWeight = new Weightec3rd(sFeatureInput, sFeatureOut, m_nScoreIndex, &m_tWords, &m_tPOSTags, &m_tEmptys); for (int i = 0; i < MAX_SENTENCE_SIZE; ++i) { m_lItems[1][i].init(i, i); } DepParser::empty_taggedword.refer(m_tWords.lookup(EMPTY_WORD), m_tPOSTags.lookup(EMPTY_POSTAG)); DepParser::start_taggedword.refer(m_tWords.lookup(START_WORD), m_tPOSTags.lookup(START_POSTAG)); DepParser::end_taggedword.refer(m_tWords.lookup(END_WORD), m_tPOSTags.lookup(END_POSTAG)); m_pWeight->init(DepParser::empty_taggedword, DepParser::start_taggedword, DepParser::end_taggedword); } DepParser::~DepParser() { delete m_pWeight; } void DepParser::train(const DependencyTree & correct, const int & round) { // initialize m_vecCorrectArcs.clear(); readEmptySentAndArcs(correct); if (m_nSentenceLength >= MAX_SENTENCE_SIZE - 1) { std::cout << "skip one" << std::endl; return; } ++m_nTrainingRound; if (!testEmptyTree(m_vecCorrectArcs, m_nSentenceLength)) { std::cout << m_nTrainingRound << std::endl; std::cout << "tree error" << std::endl; std::cout << "arcs" << std::endl; for (const auto & arc : m_vecCorrectArcs) { std::cout << arc.first() << " " << arc.second() << std::endl; } } Arcs2TriArcs(m_vecCorrectArcs, m_vecCorrectTriArcs); if (m_nState == ParserState::GOLDTEST) { m_setFirstGoldScore.clear(); m_setSecondGoldScore.clear(); m_setThirdGoldScore.clear(); for (const auto & triarc : m_vecCorrectTriArcs) { m_setFirstGoldScore.insert(BiGram<int>(triarc.first(), triarc.forth())); m_setSecondGoldScore.insert(TriGram<int>(triarc.first(), triarc.third(), triarc.forth())); m_setThirdGoldScore.insert(QuarGram<int>(triarc.first(), triarc.second(), triarc.third(), triarc.forth())); } } m_pWeight->referRound(m_nTrainingRound); work(nullptr, correct); if (m_nTrainingRound % OUTPUT_STEP == 0) { std::cout << m_nTotalErrors << " / " << m_nTrainingRound << std::endl; } } void DepParser::parse(const Sentence & sentence, DependencyTree * retval) { int idx = 0; m_nTrainingRound = 0; DependencyTree correct; m_nSentenceLength = sentence.size(); if (m_nSentenceLength >= MAX_SENTENCE_SIZE - 1) { std::cout << "skip one" << std::endl; return; } for (const auto & token : sentence) { m_lSentence[idx][0].refer(m_tWords.lookup(SENT_WORD(token)), m_tPOSTags.lookup(SENT_POSTAG(token))); for (int ec = 1; ec <= MAX_EMPTY_SIZE; ++ec) { m_lSentence[idx][ec].refer( m_tWords.lookup( (idx == 0 ? START_WORD : m_tWords.key(m_lSentence[idx - 1][0].first())) + m_tEmptys.key(ec) + SENT_WORD(token) ), m_tPOSTags.lookup("NN") ); } correct.push_back(DependencyTreeNode(token, -1, NULL_LABEL)); ++idx; } m_lSentence[idx][0].refer(m_tWords.lookup(ROOT_WORD), m_tPOSTags.lookup(ROOT_POSTAG)); for (int ec = 1; ec <= MAX_EMPTY_SIZE; ++ec) { m_lSentence[idx][ec].refer( m_tWords.lookup( m_tWords.key(m_lSentence[idx - 1][0].first()) + m_tEmptys.key(ec) + END_WORD ), m_tPOSTags.lookup("NN") ); } work(retval, correct); } void DepParser::work(DependencyTree * retval, const DependencyTree & correct) { decode(); decodeArcs(); switch (m_nState) { case ParserState::TRAIN: update(); break; case ParserState::PARSE: generate(retval, correct); break; case ParserState::GOLDTEST: goldCheck(); break; default: break; } } void DepParser::decode() { for (int d = 1; d <= m_nSentenceLength + 1; ++d) { initFirstOrderScore(d); if (d > 1) { initSecondOrderScore(d); } for (int i = 0, max_i = m_nSentenceLength - d + 1; i < max_i; ++i) { int l = i + d - 1; tscore l2r_arc_score = m_lFirstOrderScore[ENCODE_L2R(i)]; tscore r2l_arc_score = m_lFirstOrderScore[ENCODE_R2L(i)]; StateItem & item = m_lItems[d][i]; // initialize item.init(i, l); for (int s = i; s < l; ++s) { const StateItem & litem = m_lItems[s - i + 1][i]; const StateItem & ritem = m_lItems[l - s][s + 1]; // jux item.updateJUX(s, litem.l2r.getScore() + ritem.r2l.getScore()); // l2r_empty_inside tscore l_empty_inside_base_score = l2r_arc_score + ritem.r2l.getScore(); for (const auto & l_beam : litem.l2r_empty_outside) { int p = ENCODE_EMPTY(s, DECODE_EMPTY_TAG(l_beam->getSplit())); int k = ENCODE_EMPTY(s + 1, DECODE_EMPTY_TAG(l_beam->getSplit())); int j = DECODE_EMPTY_POS(l_beam->getSplit()); item.updateL2REmptyInside(p, l_beam->getSplit(), l_empty_inside_base_score + l_beam->getScore() + twoArcScore(i, k, l) + triArcScore(i, j == i ? -1 : j, k, l)); //std::cout << "(1)" << std::endl; //std::cout << i << " -> " << k << " with " << l << " : " << twoArcScore(i, k, l) << std::endl; //std::cout << i << " -> " << (j == i ? -1 : j) << " with " << k << " with " << l << " : " << triArcScore(i, j == i ? -1 : j, k, l) << std::endl; } // r2l_empty_inside tscore r_empty_inside_base_score = r2l_arc_score + litem.l2r.getScore(); for (const auto & r_beam : ritem.r2l_empty_outside) { int p = ENCODE_EMPTY(s, DECODE_EMPTY_TAG(r_beam->getSplit())); int k = ENCODE_EMPTY(s + 1, DECODE_EMPTY_TAG(r_beam->getSplit())); int j = DECODE_EMPTY_POS(r_beam->getSplit()); item.updateR2LEmptyInside(p, r_beam->getSplit(), r_empty_inside_base_score + r_beam->getScore() + twoArcScore(l, k, i) + triArcScore(l, j == l ? -1 : j, k, i)); //std::cout << "(2)" << std::endl; //std::cout << l << " -> " << k << " with " << i << " : " << twoArcScore(l, k, i) << std::endl; //std::cout << l << " -> " << (j == l ? -1 : j) << " with " << k << " with " << i << " : " << triArcScore(l, j == l ? -1 : j, k, i) << std::endl; } } for (int k = i + 1; k < l; ++k) { StateItem & litem = m_lItems[k - i + 1][i]; StateItem & ritem = m_lItems[l - k + 1][k]; const auto & l_beam = litem.l2r_solid_outside; const auto & r_beam = ritem.r2l_solid_outside; // l2r_solid_both tscore l_solid_both_base_score = ritem.jux.getScore() + l2r_arc_score + m_lSecondOrderScore[ENCODE_2ND_L2R(i, k)]; for (const auto & swbs : l_beam) { // j is inner split const int & j = swbs->getSplit(); item.updateL2RSolidBoth(k, j, l_solid_both_base_score + swbs->getScore() + triArcScore(i, j == i ? -1 : IS_EMPTY(j) ? j + 1 : j, k, l)); //std::cout << "(3)" << std::endl; //std::cout << i << " -> " << (j == i ? -1 : IS_EMPTY(j) ? j + 1 : j) << " with " << k << " with " << l << " : " << triArcScore(i, j == i ? -1 : IS_EMPTY(j) ? j + 1 : j, k, l) << std::endl; } // l2r_empty_outside for (const auto & swt : m_abFirstOrderEmptyScore[ENCODE_L2R(i)]) { const int & t = swt->getType(); // s is split with type int s = ENCODE_EMPTY(k, t); // o is outside empty int o = ENCODE_EMPTY(l + 1, t); tscore l_empty_outside_base_score = ritem.l2r.getScore() + swt->getScore() + twoArcScore(i, k, o); for (const auto & swbs : l_beam) { // j is inner split const int & j = swbs->getSplit(); item.updateL2REmptyOutside(s, j, l_empty_outside_base_score + swbs->getScore() + triArcScore(i, j == i ? -1 : IS_EMPTY(j) ? j + 1 : j, k, o)); //std::cout << "(4)" << std::endl; //std::cout << i << " -> " << (j == i ? -1 : IS_EMPTY(j) ? j + 1 : j) << " with " << k << " with " << o << " : " << triArcScore(i, j == i ? -1 : IS_EMPTY(j) ? j + 1 : j, k, o) << std::endl; } } // l2r item.updateL2R(k, litem.l2r_solid_outside.bestItem().getScore() + ritem.l2r.getScore()); // r2l_solid_both tscore r_solid_both_base_score = litem.jux.getScore() + r2l_arc_score + m_lSecondOrderScore[ENCODE_2ND_R2L(i, k)]; for (const auto & swbs : r_beam) { const int & j = swbs->getSplit(); item.updateR2LSolidBoth(k, j, r_solid_both_base_score + swbs->getScore() + triArcScore(l, j == l ? -1 : IS_EMPTY(j) ? j + 1 : j, k, i)); //std::cout << "(5)" << std::endl; //std::cout << l << " -> " << (j == l ? -1 : IS_EMPTY(j) ? j + 1 : j) << " with " << k << " with " << i << " : " << triArcScore(l, j == l ? -1 : IS_EMPTY(j) ? j + 1 : j, k, i) << std::endl; } // r2l_empty_outside for (const auto & swt : m_abFirstOrderEmptyScore[ENCODE_R2L(i)]) { const int & t = swt->getType(); int s = ENCODE_EMPTY(k, t); int o = ENCODE_EMPTY(i, t); tscore r_empty_outside_base_score = litem.r2l.getScore() + swt->getScore() + twoArcScore(l, k, o); for (const auto & swbs : r_beam) { const int & j = swbs->getSplit(); item.updateR2LEmptyOutside(s, j, r_empty_outside_base_score + swbs->getScore() + triArcScore(l, j == l ? -1 : IS_EMPTY(j) ? j + 1 : j, k, o)); //std::cout << "(6)" << std::endl; //std::cout << l << " -> " << (j == l ? -1 : IS_EMPTY(j) ? j + 1 : j) << " with " << k << " with " << o << " : " << triArcScore(l, j == l ? -1 : IS_EMPTY(j) ? j + 1 : j, k, o) << std::endl; } } // r2l item.updateR2L(k, ritem.r2l_solid_outside.bestItem().getScore() + litem.r2l.getScore()); } if (d > 1) { // l2r_solid_both item.updateL2RSolidBoth(i, i, m_lItems[d - 1][i + 1].r2l.getScore() + l2r_arc_score + m_lSecondOrderScore[ENCODE_2ND_L2R(i, i)] + triArcScore(i, -1, -1, l)); //std::cout << "(7)" << std::endl; //std::cout << i << " -> " << -1 << " with " << -1 << " with " << l << " : " << triArcScore(i, -1, -1, l) << std::endl; // r2l_solid_both item.updateR2LSolidBoth(l, l, m_lItems[d - 1][i].l2r.getScore() + r2l_arc_score + m_lSecondOrderScore[ENCODE_2ND_R2L(i, i)] + triArcScore(l, -1, -1, i)); //std::cout << "(8)" << std::endl; //std::cout << l << " -> " << -1 << " with " << -1 << " with " << i << " : " << triArcScore(l, -1, -1, i) << std::endl; // l2r_solid_outside for (const auto & swbs : item.l2r_empty_inside) { item.updateL2RSolidOutside(swbs->getSplit(), swbs->getInnerSplit(), swbs->getScore()); } for (const auto & swbs : item.l2r_solid_both) { item.updateL2RSolidOutside(swbs->getSplit(), swbs->getInnerSplit(), swbs->getScore()); } // r2l_solid_outside for (const auto & swbs : item.r2l_empty_inside) { item.updateR2LSolidOutside(swbs->getSplit(), swbs->getInnerSplit(), swbs->getScore()); } for (const auto & swbs : item.r2l_solid_both) { item.updateR2LSolidOutside(swbs->getSplit(), swbs->getInnerSplit(), swbs->getScore()); } } // l2r_empty_ouside for (const auto & swt : m_abFirstOrderEmptyScore[ENCODE_L2R(i)]) { const int & t = swt->getType(); int s = ENCODE_EMPTY(l, t); int o = ENCODE_EMPTY(l + 1, t); if (d > 1) { tscore base_l2r_empty_outside_score = swt->getScore() + twoArcScore(i, l, o) + m_lItems[1][l].l2r.getScore(); for (const auto & swbs : item.l2r_solid_outside) { const int & j = swbs->getSplit(); //std::cout << "score " << swbs->getScore() << std::endl; item.updateL2REmptyOutside(s, swbs->getSplit(), base_l2r_empty_outside_score + swbs->getScore() + triArcScore(i, j == i ? -1 : IS_EMPTY(j) ? j + 1 : j, l, o)); //std::cout << "(9)" << std::endl; //std::cout << i << " -> " << (j == i ? -1 : IS_EMPTY(j) ? j + 1 : j) << " with " << l << " with " << o << " : " << triArcScore(i, j == i ? -1 : IS_EMPTY(j) ? j + 1 : j, l, o) << std::endl; } } else { item.updateL2REmptyOutside(s, i, swt->getScore() + twoArcScore(i, -1, o) + triArcScore(i, -1, -1, o)); //std::cout << "(10)" << std::endl; //std::cout << i << " -> " << -1 << " with " << o << twoArcScore(i, -1, o) << std::endl; //std::cout << i << " -> " << -1 << " with " << -1 << " with " << o << " : " << triArcScore(i, -1, -1, o) << std::endl; } } // r2l_empty_outside for (const auto & swt : m_abFirstOrderEmptyScore[ENCODE_R2L(i)]) { const int & t = swt->getType(); int s = ENCODE_EMPTY(i, t); int o = ENCODE_EMPTY(i, t); if (d > 1) { tscore base_r2l_empty_outside_score = swt->getScore() + twoArcScore(l, i, o) + m_lItems[1][i].r2l.getScore(); for (const auto & swbs : item.r2l_solid_outside) { const int & j = swbs->getSplit(); item.updateR2LEmptyOutside(s, swbs->getSplit(), base_r2l_empty_outside_score + swbs->getScore() + triArcScore(l, j == l ? -1 : IS_EMPTY(j) ? j + 1 : j, i, o)); //std::cout << "(11)" << std::endl; //std::cout << l << " -> " << (j == l ? -1 : IS_EMPTY(j) ? j + 1 : j) << " with " << i << " with " << o << " : " << triArcScore(l, j == l ? -1 : IS_EMPTY(j) ? j + 1 : j, i, o) << std::endl; } } else { item.updateR2LEmptyOutside(s, l, swt->getScore() + twoArcScore(l, -1, o) + triArcScore(l, -1, -1, o)); //std::cout << "(12)" << std::endl; //std::cout << l << " -> " << -1 << " with " << i << twoArcScore(l, -1, o) << std::endl; //std::cout << l << " -> " << -1 << " with " << -1 << " with " << o << " : " << triArcScore(l, -1, -1, o) << std::endl; } } // l2r item.updateL2R(l, item.l2r_solid_outside.bestItem().getScore() + m_lItems[1][l].l2r.getScore()); if (item.l2r_empty_outside.size() > 0) { item.updateL2R(item.l2r_empty_outside.bestItem().getSplit(), item.l2r_empty_outside.bestItem().getScore()); } // r2l item.updateR2L(i, item.r2l_solid_outside.bestItem().getScore() + m_lItems[1][i].r2l.getScore()); if (item.r2l_empty_outside.size() > 0) { item.updateR2L(item.r2l_empty_outside.bestItem().getSplit(), item.r2l_empty_outside.bestItem().getScore()); } } if (d > 1) { // root StateItem & item = m_lItems[d][m_nSentenceLength - d + 1]; item.init(m_nSentenceLength - d + 1, m_nSentenceLength); // r2l_solid_outside item.updateR2LSolidOutside(m_nSentenceLength, m_nSentenceLength, m_lItems[d - 1][item.left].l2r.getScore() + m_lFirstOrderScore[ENCODE_R2L(item.left)] + m_lSecondOrderScore[ENCODE_2ND_R2L(item.left, item.left)] + triArcScore(item.right, -1, -1, item.left)); //std::cout << "(13)" << std::endl; //std::cout << item.right << " -> -1 with -1 with " << item.left << " : " << triArcScore(item.right, -1, -1, item.left) << std::endl; // r2l item.updateR2L(item.left, item.r2l_solid_outside.bestItem().getScore() + m_lItems[1][item.left].r2l.getScore()); for (int i = item.left, s = item.left + 1, j = m_nSentenceLength + 1; s < j - 1; ++s) { item.updateR2L(s, m_lItems[j - s][s].r2l_solid_outside.bestItem().getScore() + m_lItems[s - i + 1][i].r2l.getScore()); } } } } void DepParser::decodeArcs() { m_vecTrainArcs.clear(); std::stack<std::tuple<int, int, int, int>> stack; stack.push(std::tuple<int, int, int, int>(m_nSentenceLength + 1, -1, 0, R2L)); m_lItems[m_nSentenceLength + 1][0].type = R2L; while (!stack.empty()) { std::tuple<int, int, int, int> span = stack.top(); stack.pop(); StateItem & item = m_lItems[std::get<0>(span)][std::get<2>(span)]; item.type = std::get<3>(span); int split = std::get<1>(span); int innersplit = -1; //item.print(); switch (item.type) { case JUX: split = item.jux.getSplit(); stack.push(std::tuple<int, int, int, int>(split - item.left + 1, -1, item.left, L2R)); stack.push(std::tuple<int, int, int, int>(item.right - split, -1, split + 1, R2L)); break; case L2R: split = item.l2r.getSplit(); if (IS_EMPTY(split)) { std::get<1>(span) = item.l2r_empty_outside.bestItem().getSplit(); std::get<3>(span) = L2R_EMPTY_OUTSIDE; stack.push(span); break; } if (item.left == item.right) { break; } stack.push(std::tuple<int, int, int, int>(split - item.left + 1, m_lItems[split - item.left + 1][item.left].l2r_solid_outside.bestItem().getSplit(), item.left, L2R_SOLID_OUTSIDE)); stack.push(std::tuple<int, int, int, int>(item.right - split + 1, -1, split, L2R)); break; case R2L: split = item.r2l.getSplit(); if (IS_EMPTY(split)) { std::get<1>(span) = item.r2l_empty_outside.bestItem().getSplit(); std::get<3>(span) = R2L_EMPTY_OUTSIDE; stack.push(span); break; } if (item.left == item.right) { break; } stack.push(std::tuple<int, int, int, int>(item.right - split + 1, m_lItems[item.right - split + 1][split].r2l_solid_outside.bestItem().getSplit(), split, R2L_SOLID_OUTSIDE)); stack.push(std::tuple<int, int, int, int>(split - item.left + 1, -1, item.left, R2L)); break; case L2R_SOLID_BOTH: if (item.left == item.right) { break; } m_vecTrainArcs.push_back(BiGram<int>(item.left, item.right)); if (split == item.left) { stack.push(std::tuple<int, int, int, int>(item.right - split, -1, split + 1, R2L)); } else { item.l2r_solid_both.sortItems(); innersplit = findInnerSplit(item.l2r_solid_both, split); stack.push(std::tuple<int, int, int, int>(split - item.left + 1, innersplit, item.left, L2R_SOLID_OUTSIDE)); stack.push(std::tuple<int, int, int, int>(item.right - split + 1, -1, split, JUX)); } break; case R2L_SOLID_BOTH: if (item.left == item.right) { break; } m_vecTrainArcs.push_back(BiGram<int>(item.right == m_nSentenceLength ? -1 : item.right, item.left)); if (split == item.right) { stack.push(std::tuple<int, int, int, int>(split - item.left, -1, item.left, L2R)); } else { item.r2l_solid_both.sortItems(); innersplit = findInnerSplit(item.r2l_solid_both, split); stack.push(std::tuple<int, int, int, int>(item.right - split + 1, innersplit, split, R2L_SOLID_OUTSIDE)); stack.push(std::tuple<int, int, int, int>(split - item.left + 1, -1, item.left, JUX)); } break; case L2R_EMPTY_INSIDE: if (item.left == item.right) { break; } m_vecTrainArcs.push_back(BiGram<int>(item.left, item.right)); item.l2r_empty_inside.sortItems(); innersplit = findInnerSplit(item.l2r_empty_inside, split); split = DECODE_EMPTY_POS(split); stack.push(std::tuple<int, int, int, int>(split - item.left + 1, innersplit, item.left, L2R_EMPTY_OUTSIDE)); stack.push(std::tuple<int, int, int, int>(item.right - split, -1, split + 1, R2L)); break; case R2L_EMPTY_INSIDE: if (item.left == item.right) { break; } m_vecTrainArcs.push_back(BiGram<int>(item.right, item.left)); item.r2l_empty_inside.sortItems(); innersplit = findInnerSplit(item.r2l_empty_inside, split); split = DECODE_EMPTY_POS(split); stack.push(std::tuple<int, int, int, int>(item.right - split, innersplit, split + 1, R2L_EMPTY_OUTSIDE)); stack.push(std::tuple<int, int, int, int>(split - item.left + 1, -1, item.left, L2R)); break; case L2R_EMPTY_OUTSIDE: m_vecTrainArcs.push_back(BiGram<int>(item.left, ENCODE_EMPTY(item.right + 1, DECODE_EMPTY_TAG(split)))); if (item.left == item.right) { break; } innersplit = findInnerSplit(item.l2r_empty_outside, split); split = DECODE_EMPTY_POS(split); stack.push(std::tuple<int, int, int, int>(split - item.left + 1, innersplit, item.left, L2R_SOLID_OUTSIDE)); stack.push(std::tuple<int, int, int, int>(item.right - split + 1, -1, split, L2R)); break; case R2L_EMPTY_OUTSIDE: m_vecTrainArcs.push_back(BiGram<int>(item.right, ENCODE_EMPTY(item.left, DECODE_EMPTY_TAG(split)))); if (item.left == item.right) { break; } innersplit = findInnerSplit(item.r2l_empty_outside, split); split = DECODE_EMPTY_POS(split); stack.push(std::tuple<int, int, int, int>(item.right - split + 1, innersplit, split, R2L_SOLID_OUTSIDE)); stack.push(std::tuple<int, int, int, int>(split - item.left + 1, -1, item.left, R2L)); break; case L2R_SOLID_OUTSIDE: if (item.left == item.right) { break; } std::get<3>(span) = IS_EMPTY(split) ? L2R_EMPTY_INSIDE : L2R_SOLID_BOTH; stack.push(span); break; case R2L_SOLID_OUTSIDE: if (item.left == item.right) { break; } if (item.right == m_nSentenceLength) { m_vecTrainArcs.push_back(BiGram<int>(-1, item.left)); stack.push(std::tuple<int, int, int, int>(item.right - item.left, -1, item.left, L2R)); break; } std::get<3>(span) = IS_EMPTY(split) ? R2L_EMPTY_INSIDE : R2L_SOLID_BOTH; stack.push(span); break; default: break; } } if (!testEmptyTree(m_vecTrainArcs, m_nSentenceLength)) { if (m_vecTrainArcs.size() != m_nSentenceLength) { std::cout << "len error" << std::endl; std::cout << "correct len is " << m_vecCorrectArcs.size() << std::endl; std::cout << "train len is " << m_vecTrainArcs.size() << std::endl; } else { std::cout << "tree error" << std::endl; } std::cout << "train arcs" << std::endl; for (const auto & arc : m_vecTrainArcs) { std::cout << "from " << arc.first() << " to " << arc.second() << std::endl; } std::cout << "correct arcs" << std::endl; for (const auto & arc : m_vecCorrectArcs) { std::cout << "from " << arc.first() << " to " << arc.second() << std::endl; } } } void DepParser::update() { Arcs2TriArcs(m_vecTrainArcs, m_vecTrainTriArcs); std::unordered_set<TriArc> positiveArcs; positiveArcs.insert(m_vecCorrectTriArcs.begin(), m_vecCorrectTriArcs.end()); for (const auto & arc : m_vecTrainTriArcs) { positiveArcs.erase(arc); } std::unordered_set<TriArc> negativeArcs; negativeArcs.insert(m_vecTrainTriArcs.begin(), m_vecTrainTriArcs.end()); for (const auto & arc : m_vecCorrectTriArcs) { negativeArcs.erase(arc); } if (!positiveArcs.empty() || !negativeArcs.empty()) { ++m_nTotalErrors; } else { for (const auto & arc : m_vecTrainArcs) { if (IS_EMPTY(arc.second())) { std::cout << "generate an empty edge at " << m_nTrainingRound << std::endl; break; } } } //std::cout << "positive" << std::endl; //debug for (const auto & arc : positiveArcs) { //std::cout << arc << std::endl; //debug getOrUpdateStackScore(arc.first(), arc.second(), arc.third(), arc.forth(), 1); getOrUpdateStackScore(arc.first(), arc.third(), arc.forth(), 1); getOrUpdateStackScore(arc.first(), arc.forth(), 1); } //std::cout << "negative" << std::endl; //debug for (const auto & arc : negativeArcs) { //std::cout << arc << std::endl; //debug getOrUpdateStackScore(arc.first(), arc.second(), arc.third(), arc.forth(), -1); getOrUpdateStackScore(arc.first(), arc.third(), arc.forth(), -1); getOrUpdateStackScore(arc.first(), arc.forth(), -1); } } void DepParser::generate(DependencyTree * retval, const DependencyTree & correct) { retval->clear(); std::vector<Arc> emptyArcs; for (const auto & arc : m_vecTrainArcs) { if (IS_EMPTY(arc.second())) { emptyArcs.push_back(arc); } } std::sort(emptyArcs.begin(), emptyArcs.end(), [](const Arc & arc1, const Arc & arc2) { return compareArc(arc1, arc2); }); auto itr_e = emptyArcs.begin(); int idx = 0, nidx = 0; std::unordered_map<int, int> nidmap; nidmap[-1] = -1; while (itr_e != emptyArcs.end() && idx != m_nSentenceLength) { if (idx < DECODE_EMPTY_POS(itr_e->second())) { nidmap[idx] = nidx++; retval->push_back(DependencyTreeNode(TREENODE_POSTAGGEDWORD(correct[idx++]), -1, NULL_LABEL)); } else { nidmap[(itr_e->second() << MAX_SENTENCE_BITS) + itr_e->first()] = nidx++; retval->push_back(DependencyTreeNode(POSTaggedWord(m_tEmptys.key(DECODE_EMPTY_TAG((itr_e++)->second())), EMPTYTAG), -1, NULL_LABEL)); } } while (idx != m_nSentenceLength) { nidmap[idx] = nidx++; retval->push_back(DependencyTreeNode(TREENODE_POSTAGGEDWORD(correct[idx++]), -1, NULL_LABEL)); } while (itr_e != emptyArcs.end()) { nidmap[(itr_e->second() << MAX_SENTENCE_BITS) + itr_e->first()] = nidx++; retval->push_back(DependencyTreeNode(POSTaggedWord(m_tEmptys.key(DECODE_EMPTY_TAG((itr_e++)->second())), EMPTYTAG), -1, NULL_LABEL)); } for (const auto & arc : m_vecTrainArcs) { TREENODE_HEAD(retval->at(nidmap[IS_EMPTY(arc.second()) ? ((arc.second() << MAX_SENTENCE_BITS) + arc.first()) : arc.second()])) = nidmap[arc.first()]; } } void DepParser::goldCheck() { Arcs2TriArcs(m_vecTrainArcs, m_vecTrainTriArcs); if (m_vecCorrectArcs.size() != m_vecTrainArcs.size() || m_lItems[m_nSentenceLength + 1][0].r2l.getScore() / GOLD_POS_SCORE != 3 * m_vecTrainArcs.size()) { ++m_nTotalErrors; std::cout << "gold parse len error at " << m_nTrainingRound << std::endl; for (const auto & triarc : m_vecTrainTriArcs) { std::cout << triarc.first() << " " << triarc.second() << " " << triarc.third() << " " << triarc.forth() << std::endl; } std::cout << std::endl; } else { int i = 0; std::sort(m_vecCorrectArcs.begin(), m_vecCorrectArcs.end(), [](const Arc & arc1, const Arc & arc2) { return arc1 < arc2; }); std::sort(m_vecTrainArcs.begin(), m_vecTrainArcs.end(), [](const Arc & arc1, const Arc & arc2) { return arc1 < arc2; }); for (int n = m_vecCorrectArcs.size(); i < n; ++i) { if (m_vecCorrectArcs[i].first() != m_vecTrainArcs[i].first() || m_vecCorrectArcs[i].second() != m_vecTrainArcs[i].second()) { ++m_nTotalErrors; break; } } if (i != m_vecCorrectArcs.size()) { std::cout << "gold parse tree error at " << m_nTrainingRound << std::endl; for (const auto & triarc : m_vecTrainTriArcs) { std::cout << triarc.first() << " " << triarc.second() << " " << triarc.third() << " " << triarc.forth() << std::endl; } std::cout << std::endl; } } } tscore DepParser::arcScore(const int & p, const int & c) { tscore retval = 0; if (m_nState == ParserState::GOLDTEST) { retval = m_setFirstGoldScore.find(BiGram<int>(p, c)) == m_setFirstGoldScore.end() ? GOLD_NEG_SCORE : GOLD_POS_SCORE; return retval; } retval = getOrUpdateStackScore(p, c, 0); if (m_fLambda > 0) retval *= m_fLambda; // std::cout << p << " -> " << c << " : " << m_nRetval << std::endl; return retval; } tscore DepParser::twoArcScore(const int & p, const int & c, const int & c2) { tscore retval = 0; if (m_nState == ParserState::GOLDTEST) { retval = m_setSecondGoldScore.find(TriGram<int>(p, c, c2)) == m_setSecondGoldScore.end() ? GOLD_NEG_SCORE : GOLD_POS_SCORE; return retval; } retval = getOrUpdateStackScore(p, c, c2, 0); if (m_fLambda > 0) retval *= m_fLambda; // std::cout << p << " -> " << c << " with " << c2 << " : " << m_nRetval << std::endl; return retval; } tscore DepParser::triArcScore(const int & p, const int & c, const int & c2, const int & c3) { tscore retval = 0; if (m_nState == ParserState::GOLDTEST) { retval = m_setThirdGoldScore.find(QuarGram<int>(p, c, c2, c3)) == m_setThirdGoldScore.end() ? GOLD_NEG_SCORE : GOLD_POS_SCORE; return retval; } retval = getOrUpdateStackScore(p, c, c2, c3, 0); if (m_fLambda > 0) retval *= m_fLambda; // std::cout << retval << " -> " << c << " with " << c2 << " with " << c3 << " : " << m_nRetval << std::endl; return retval; } void DepParser::initFirstOrderScore(const int & d) { for (int i = 0, max_i = m_nSentenceLength - d + 1; i < max_i; ++i) { int l = i + d - 1; if (d > 1) { m_lFirstOrderScore[ENCODE_L2R(i)] = arcScore(i, i + d - 1); m_lFirstOrderScore[ENCODE_R2L(i)] = arcScore(i + d - 1, i); //std::cout << i << " -> " << l << " : " << m_lFirstOrderScore[ENCODE_L2R(i)] << std::endl; //std::cout << l << " -> " << i << " : " << m_lFirstOrderScore[ENCODE_R2L(i)] << std::endl; } m_abFirstOrderEmptyScore[ENCODE_L2R(i)].clear(); m_abFirstOrderEmptyScore[ENCODE_R2L(i)].clear(); for (int t = 1; t <= MAX_EMPTY_SIZE; ++t) { if (m_nState == ParserState::GOLDTEST || m_pWeight->testEmptyNode(i, ENCODE_EMPTY(i + d, t), m_lSentence)) { const tscore & score = arcScore(i, ENCODE_EMPTY(i + d, t)); m_abFirstOrderEmptyScore[ENCODE_L2R(i)].insertItem(ScoreWithType(t, score)); } if (m_nState == ParserState::GOLDTEST || m_pWeight->testEmptyNode(i + d - 1, ENCODE_EMPTY(i, t), m_lSentence)) { const tscore & score = arcScore(i + d - 1, ENCODE_EMPTY(i, t)); m_abFirstOrderEmptyScore[ENCODE_R2L(i)].insertItem(ScoreWithType(t, score)); } } m_abFirstOrderEmptyScore[ENCODE_L2R(i)].sortItems(); m_abFirstOrderEmptyScore[ENCODE_R2L(i)].sortItems(); //for (int i = 0; i < m_abFirstOrderEmptyScore[ENCODE_L2R(i)].size(); ++i) { // std::cout << i << " -> " << l << " : " << m_abFirstOrderEmptyScore[ENCODE_L2R(i)].bestItem(0).getScore() << std::endl; //} //for (int i = 0; i < m_abFirstOrderEmptyScore[ENCODE_R2L(i)].size(); ++i) { // std::cout << l << " -> " << i << " : " << m_abFirstOrderEmptyScore[ENCODE_R2L(i)].bestItem(0).getScore() << std::endl; //} } int i = m_nSentenceLength - d + 1; m_lFirstOrderScore[ENCODE_R2L(i)] = arcScore(m_nSentenceLength, i); //std::cout << m_nSentenceLength << " -> " << i << " : " << m_lFirstOrderScore[ENCODE_R2L(i)] << std::endl; } void DepParser::initSecondOrderScore(const int & d) { for (int i = 0, max_i = m_nSentenceLength - d + 1; i < max_i; ++i) { int l = i + d - 1; m_lSecondOrderScore[ENCODE_2ND_L2R(i, i)] = twoArcScore(i, -1, l); m_lSecondOrderScore[ENCODE_2ND_R2L(i, i)] = twoArcScore(l, -1, i); //std::cout << i << " -> " << -1 << " with " << l << " : " << m_lSecondOrderScore[ENCODE_2ND_L2R(i, i)] << std::endl; //std::cout << l << " -> " << -1 << " with " << i << " : " << m_lSecondOrderScore[ENCODE_2ND_R2L(i, i)] << std::endl; for (int k = i + 1, l = i + d - 1; k < l; ++k) { m_lSecondOrderScore[ENCODE_2ND_L2R(i, k)] = twoArcScore(i, k, l); m_lSecondOrderScore[ENCODE_2ND_R2L(i, k)] = twoArcScore(l, k, i); //std::cout << i << " -> " << k << " with " << l << " : " << m_lSecondOrderScore[ENCODE_2ND_L2R(i, k)] << std::endl; //std::cout << l << " -> " << k << " with " << i << " : " << m_lSecondOrderScore[ENCODE_2ND_R2L(i, k)] << std::endl; } } int i = m_nSentenceLength - d + 1; m_lSecondOrderScore[ENCODE_2ND_R2L(i, i)] = twoArcScore(m_nSentenceLength, -1, i); //std::cout << m_nSentenceLength << " -> " << -1 << " with " << i << " : " << m_lSecondOrderScore[ENCODE_2ND_R2L(i, i)] << std::endl; } int DepParser::encodeEmptyWord(int i, int ec) { ttoken token = (i > 0 ? m_tWords.key(m_lSentence[i - 1][0].first()) : START_WORD) + m_tEmptys.key(ec) + (i < m_nSentenceLength ? m_tWords.key(m_lSentence[i][0].first()) : END_WORD); return m_tWords.lookup(token); } int DepParser::encodeEmptyPOSTag(int i, int ec) { ttoken token = "NN"; return m_tPOSTags.lookup(token); } void DepParser::readEmptySentAndArcs(const DependencyTree & correct) { // for normal sentence m_nSentenceLength = 0; std::vector<int> tIds; std::vector<Arc> ecarcs; for (const auto & node : correct) { int h = TREENODE_HEAD(node), p = tIds.size(); if (TREENODE_POSTAG(node) != EMPTYTAG) { tIds.push_back(m_nSentenceLength); m_lSentence[m_nSentenceLength++][0].refer(m_tWords.lookup(TREENODE_WORD(node)), m_tPOSTags.lookup(TREENODE_POSTAG(node))); } else { tIds.push_back(ENCODE_EMPTY(m_nSentenceLength, m_tEmptys.lookup(TREENODE_WORD(node)))); } ecarcs.push_back(Arc(h, p)); if (m_nSentenceLength >= MAX_SENTENCE_SIZE - 1) return; } m_lSentence[m_nSentenceLength][0].refer(m_tWords.lookup(ROOT_WORD), m_tPOSTags.lookup(ROOT_POSTAG)); // refer empty node for (int i = 0; i <= m_nSentenceLength; ++i) { for (int ec = 1; ec <= MAX_EMPTY_SIZE; ++ec) { m_lSentence[i][ec].refer(encodeEmptyWord(i, ec), encodeEmptyPOSTag(i, ec)); } } for (const auto & ecarc : ecarcs) { m_vecCorrectArcs.push_back(Arc(ecarc.first() == -1 ? -1 : tIds[ecarc.first()], tIds[ecarc.second()])); } } tscore DepParser::getOrUpdateStackScore(const int & p, const int & c, const int & amount) { return m_pWeight->getOrUpdateArcScore(p, c, amount, m_nSentenceLength, m_lSentence); } tscore DepParser::getOrUpdateStackScore(const int & p, const int & c, const int & c2, const int & amount) { return m_pWeight->getOrUpdateBiArcScore(p, c, c2, amount, m_nSentenceLength, m_lSentence); } tscore DepParser::getOrUpdateStackScore(const int & p, const int & c, const int & c2, const int & c3, const int & amount) { return m_pWeight->getOrUpdateTriArcScore(p, c, c2, c3, amount, m_nSentenceLength, m_lSentence); } void DepParser::initScore(const DependencyTree & tree, float lambda) { m_fLambda = lambda; readEmptySentAndArcs(tree); for (int d = 1; d <= m_nSentenceLength + 1; ++d) { for (int i = 0, max_i = m_nSentenceLength - d + 1; i < max_i; ++i) { int l = i + d - 1; if (d > 1) { m_lScore[i][l][0] = arcScore(i, i + d - 1); m_lScore[i][l][1] = arcScore(i + d - 1, i); //std::cout << i << ' ' << l << ' ' << m_lScore[i][l][0] << std::endl; //std::cout << l << ' ' << i << ' ' << m_lScore[i][l][1] << std::endl; } m_abScore[i][l][0].clear(); m_abScore[i][l][1].clear(); for (int t = 1; t <= MAX_EMPTY_SIZE; ++t) { if (m_nState == ParserState::GOLDTEST || m_pWeight->testEmptyNode(i, ENCODE_EMPTY(i + d, t), m_lSentence)) { const tscore & score = arcScore(i, ENCODE_EMPTY(i + d, t)); m_abScore[i][l][0].insertItem(ScoreWithType(t, score)); } if (m_nState == ParserState::GOLDTEST || m_pWeight->testEmptyNode(i + d - 1, ENCODE_EMPTY(i, t), m_lSentence)) { const tscore & score = arcScore(i + d - 1, ENCODE_EMPTY(i, t)); m_abScore[i][l][1].insertItem(ScoreWithType(t, score)); } } m_abScore[i][l][0].sortItems(); m_abScore[i][l][1].sortItems(); } int i = m_nSentenceLength - d + 1; m_lScore[i][m_nSentenceLength][1] = arcScore(m_nSentenceLength, i); } } void DepParser::decodeAfterScore() { for (int d = 1; d <= m_nSentenceLength + 1; ++d) { if (d > 1) { initSecondOrderScore(d); } for (int i = 0, max_i = m_nSentenceLength - d + 1; i < max_i; ++i) { int l = i + d - 1; tscore l2r_arc_score = m_lScore[i][l][0]; tscore r2l_arc_score = m_lScore[i][l][1]; //std::cout << "()" << i << ' ' << l << ' ' << l2r_arc_score << std::endl; //std::cout << "()" << l << ' ' << i << ' ' << r2l_arc_score << std::endl; StateItem & item = m_lItems[d][i]; // initialize item.init(i, l); for (int s = i; s < l; ++s) { const StateItem & litem = m_lItems[s - i + 1][i]; const StateItem & ritem = m_lItems[l - s][s + 1]; // jux item.updateJUX(s, litem.l2r.getScore() + ritem.r2l.getScore()); // l2r_empty_inside tscore l_empty_inside_base_score = l2r_arc_score + ritem.r2l.getScore(); for (const auto & l_beam : litem.l2r_empty_outside) { int p = ENCODE_EMPTY(s, DECODE_EMPTY_TAG(l_beam->getSplit())); int k = ENCODE_EMPTY(s + 1, DECODE_EMPTY_TAG(l_beam->getSplit())); int j = DECODE_EMPTY_POS(l_beam->getSplit()); item.updateL2REmptyInside(p, l_beam->getSplit(), l_empty_inside_base_score + l_beam->getScore() + twoArcScore(i, k, l) + triArcScore(i, j == i ? -1 : j, k, l)); } // r2l_empty_inside tscore r_empty_inside_base_score = r2l_arc_score + litem.l2r.getScore(); for (const auto & r_beam : ritem.r2l_empty_outside) { int p = ENCODE_EMPTY(s, DECODE_EMPTY_TAG(r_beam->getSplit())); int k = ENCODE_EMPTY(s + 1, DECODE_EMPTY_TAG(r_beam->getSplit())); int j = DECODE_EMPTY_POS(r_beam->getSplit()); item.updateR2LEmptyInside(p, r_beam->getSplit(), r_empty_inside_base_score + r_beam->getScore() + twoArcScore(l, k, i) + triArcScore(l, j == l ? -1 : j, k, i)); } } for (int k = i + 1; k < l; ++k) { StateItem & litem = m_lItems[k - i + 1][i]; StateItem & ritem = m_lItems[l - k + 1][k]; const auto & l_beam = litem.l2r_solid_outside; const auto & r_beam = ritem.r2l_solid_outside; // l2r_solid_both tscore l_solid_both_base_score = ritem.jux.getScore() + l2r_arc_score + m_lSecondOrderScore[ENCODE_2ND_L2R(i, k)]; for (const auto & swbs : l_beam) { // j is inner split const int & j = swbs->getSplit(); item.updateL2RSolidBoth(k, j, l_solid_both_base_score + swbs->getScore() + triArcScore(i, j == i ? -1 : IS_EMPTY(j) ? j + 1 : j, k, l)); } // l2r_empty_outside for (const auto & swt : m_abScore[i][l][0]) { const int & t = swt->getType(); // s is split with type int s = ENCODE_EMPTY(k, t); // o is outside empty int o = ENCODE_EMPTY(l + 1, t); tscore l_empty_outside_base_score = ritem.l2r.getScore() + swt->getScore() + twoArcScore(i, k, o); for (const auto & swbs : l_beam) { // j is inner split const int & j = swbs->getSplit(); item.updateL2REmptyOutside(s, j, l_empty_outside_base_score + swbs->getScore() + triArcScore(i, j == i ? -1 : IS_EMPTY(j) ? j + 1 : j, k, o)); } } // l2r item.updateL2R(k, litem.l2r_solid_outside.bestItem().getScore() + ritem.l2r.getScore()); // r2l_solid_both tscore r_solid_both_base_score = litem.jux.getScore() + r2l_arc_score + m_lSecondOrderScore[ENCODE_2ND_R2L(i, k)]; for (const auto & swbs : r_beam) { const int & j = swbs->getSplit(); item.updateR2LSolidBoth(k, j, r_solid_both_base_score + swbs->getScore() + triArcScore(l, j == l ? -1 : IS_EMPTY(j) ? j + 1 : j, k, i)); } // r2l_empty_outside for (const auto & swt : m_abScore[i][l][1]) { const int & t = swt->getType(); int s = ENCODE_EMPTY(k, t); int o = ENCODE_EMPTY(i, t); tscore r_empty_outside_base_score = litem.r2l.getScore() + swt->getScore() + twoArcScore(l, k, o); for (const auto & swbs : r_beam) { const int & j = swbs->getSplit(); item.updateR2LEmptyOutside(s, j, r_empty_outside_base_score + swbs->getScore() + triArcScore(l, j == l ? -1 : IS_EMPTY(j) ? j + 1 : j, k, o)); } } // r2l item.updateR2L(k, ritem.r2l_solid_outside.bestItem().getScore() + litem.r2l.getScore()); } if (d > 1) { // l2r_solid_both item.updateL2RSolidBoth(i, i, m_lItems[d - 1][i + 1].r2l.getScore() + l2r_arc_score + m_lSecondOrderScore[ENCODE_2ND_L2R(i, i)] + triArcScore(i, -1, -1, l)); // r2l_solid_both item.updateR2LSolidBoth(l, l, m_lItems[d - 1][i].l2r.getScore() + r2l_arc_score + m_lSecondOrderScore[ENCODE_2ND_R2L(i, i)] + triArcScore(l, -1, -1, i)); // l2r_solid_outside for (const auto & swbs : item.l2r_empty_inside) { item.updateL2RSolidOutside(swbs->getSplit(), swbs->getInnerSplit(), swbs->getScore()); } for (const auto & swbs : item.l2r_solid_both) { item.updateL2RSolidOutside(swbs->getSplit(), swbs->getInnerSplit(), swbs->getScore()); } // r2l_solid_outside for (const auto & swbs : item.r2l_empty_inside) { item.updateR2LSolidOutside(swbs->getSplit(), swbs->getInnerSplit(), swbs->getScore()); } for (const auto & swbs : item.r2l_solid_both) { item.updateR2LSolidOutside(swbs->getSplit(), swbs->getInnerSplit(), swbs->getScore()); } } // l2r_empty_ouside for (const auto & swt : m_abScore[i][l][0]) { const int & t = swt->getType(); int s = ENCODE_EMPTY(l, t); int o = ENCODE_EMPTY(l + 1, t); if (d > 1) { tscore base_l2r_empty_outside_score = swt->getScore() + twoArcScore(i, l, o) + m_lItems[1][l].l2r.getScore(); for (const auto & swbs : item.l2r_solid_outside) { const int & j = swbs->getSplit(); item.updateL2REmptyOutside(s, swbs->getSplit(), base_l2r_empty_outside_score + swbs->getScore() + triArcScore(i, j == i ? -1 : IS_EMPTY(j) ? j + 1 : j, l, o)); } } else { item.updateL2REmptyOutside(s, i, swt->getScore() + twoArcScore(i, -1, o) + triArcScore(i, -1, -1, o)); } } // r2l_empty_outside for (const auto & swt : m_abScore[i][l][1]) { const int & t = swt->getType(); int s = ENCODE_EMPTY(i, t); int o = ENCODE_EMPTY(i, t); if (d > 1) { tscore base_r2l_empty_outside_score = swt->getScore() + twoArcScore(l, i, o) + m_lItems[1][i].r2l.getScore(); for (const auto & swbs : item.r2l_solid_outside) { const int & j = swbs->getSplit(); item.updateR2LEmptyOutside(s, swbs->getSplit(), base_r2l_empty_outside_score + swbs->getScore() + triArcScore(l, j == l ? -1 : IS_EMPTY(j) ? j + 1 : j, i, o)); } } else { item.updateR2LEmptyOutside(s, l, swt->getScore() + twoArcScore(l, -1, o) + triArcScore(l, -1, -1, o)); } } // l2r item.updateL2R(l, item.l2r_solid_outside.bestItem().getScore() + m_lItems[1][l].l2r.getScore()); if (item.l2r_empty_outside.size() > 0) { item.updateL2R(item.l2r_empty_outside.bestItem().getSplit(), item.l2r_empty_outside.bestItem().getScore()); } // r2l item.updateR2L(i, item.r2l_solid_outside.bestItem().getScore() + m_lItems[1][i].r2l.getScore()); if (item.r2l_empty_outside.size() > 0) { item.updateR2L(item.r2l_empty_outside.bestItem().getSplit(), item.r2l_empty_outside.bestItem().getScore()); } } if (d > 1) { // root StateItem & item = m_lItems[d][m_nSentenceLength - d + 1]; item.init(m_nSentenceLength - d + 1, m_nSentenceLength); // r2l_solid_outside item.updateR2LSolidOutside(m_nSentenceLength, m_nSentenceLength, m_lItems[d - 1][item.left].l2r.getScore() + m_lScore[item.left][item.right][1] + m_lSecondOrderScore[ENCODE_2ND_R2L(item.left, item.left)] + triArcScore(item.right, -1, -1, item.left)); // r2l item.updateR2L(item.left, item.r2l_solid_outside.bestItem().getScore() + m_lItems[1][item.left].r2l.getScore()); for (int i = item.left, s = item.left + 1, j = m_nSentenceLength + 1; s < j - 1; ++s) { item.updateR2L(s, m_lItems[j - s][s].r2l_solid_outside.bestItem().getScore() + m_lItems[s - i + 1][i].r2l.getScore()); } //std::cout << "d = " << d << " score = " << item.r2l.getScore() << std::endl; } } } void DepParser::parseScore(const DependencyTree & tree, DependencyTree * retval) { DependencyTree correct; retval->clear(); //std::cout << "here " << std::endl << tree << std::endl; for (const auto & node : tree) { if (TREENODE_POSTAG(node) != EMPTYTAG) { correct.push_back(node); } } decodeAfterScore(); decodeArcs(); generate(retval, correct); } }
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: E. Gil Jones */ #include <gtest/gtest.h> #include <urdf_parser/urdf_parser.h> #include <chomp_motion_planner/chomp_planner.h> #include <chomp_motion_planner/chomp_parameters.h> #include <moveit_msgs/GetMotionPlan.h> #include <kinematic_constraints/utils.h> #include <planning_models/conversions.h> #include <collision_distance_field/collision_detector_allocator_distance_field.h> #include <rdf_loader/rdf_loader.h> class Pr2ChompPlannerTester : public testing::Test { protected: virtual void SetUp() { rml_.reset(new rdf_loader::RDFLoader("robot_description")); acm_.reset(new collision_detection::AllowedCollisionMatrix()); ros::NodeHandle nh; XmlRpc::XmlRpcValue coll_ops; nh.getParam("robot_description_planning/default_collision_operations", coll_ops); if (coll_ops.getType() != XmlRpc::XmlRpcValue::TypeArray) { ROS_WARN("default_collision_operations is not an array"); return; } if (coll_ops.size() == 0) { ROS_WARN("No collision operations in default collision operations"); return; } for (int i = 0; i < coll_ops.size(); ++i) { if (!coll_ops[i].hasMember("object1") || !coll_ops[i].hasMember("object2") || !coll_ops[i].hasMember("operation")) { ROS_WARN("All collision operations must have two objects and an operation"); continue; } acm_->setEntry(std::string(coll_ops[i]["object1"]), std::string(coll_ops[i]["object2"]), std::string(coll_ops[i]["operation"]) == "disable"); } } virtual void TearDown() { } protected: boost::shared_ptr<rdf_loader::RDFLoader> rml_; collision_detection::AllowedCollisionMatrixPtr acm_; }; TEST_F(Pr2ChompPlannerTester, SimplePlan) { planning_scene::PlanningScenePtr ps(new planning_scene::PlanningScene()); ps->setActiveCollisionDetector(collision_detection::CollisionDetectorAllocatorDistanceField::create()); ps->configure(rml_->getURDF(), rml_->getSRDF()); ASSERT_TRUE(ps->isConfigured()); ps->getAllowedCollisionMatrixNonConst() = *acm_; chomp::ChompPlanner chomp_planner(ps->getRobotModel()); moveit_msgs::GetMotionPlan::Request mplan_req; moveit_msgs::GetMotionPlan::Response mplan_res; mplan_req.motion_plan_request.group_name = "right_arm"; mplan_req.motion_plan_request.num_planning_attempts = 5; mplan_req.motion_plan_request.allowed_planning_time = ros::Duration(5.0); const std::vector<std::string>& joint_names = ps->getRobotModel()->getJointModelGroup("right_arm")->getJointModelNames(); mplan_req.motion_plan_request.goal_constraints.resize(1); mplan_req.motion_plan_request.goal_constraints[0].joint_constraints.resize(joint_names.size()); for (unsigned int i = 0; i < joint_names.size(); i++) { mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[i].joint_name = joint_names[i]; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[i].position = 0.0; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[i].tolerance_above = 0.001; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[i].tolerance_below = 0.001; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[i].weight = 1.0; } mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[0].position = -2.0; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[3].position = -.2; mplan_req.motion_plan_request.goal_constraints[0].joint_constraints[5].position = -.2; chomp::ChompParameters params; chomp_planner.solve(ps, mplan_req, params, mplan_res); ASSERT_EQ(mplan_res.error_code.val, mplan_res.error_code.SUCCESS); EXPECT_GT(mplan_res.trajectory.joint_trajectory.points.size(), 0); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); ros::init(argc, argv, "test_chomp_planning"); return RUN_ALL_TESTS(); }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/iotwireless/model/SidewalkEventNotificationConfigurations.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace IoTWireless { namespace Model { SidewalkEventNotificationConfigurations::SidewalkEventNotificationConfigurations() : m_amazonIdEventTopic(EventNotificationTopicStatus::NOT_SET), m_amazonIdEventTopicHasBeenSet(false) { } SidewalkEventNotificationConfigurations::SidewalkEventNotificationConfigurations(JsonView jsonValue) : m_amazonIdEventTopic(EventNotificationTopicStatus::NOT_SET), m_amazonIdEventTopicHasBeenSet(false) { *this = jsonValue; } SidewalkEventNotificationConfigurations& SidewalkEventNotificationConfigurations::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("AmazonIdEventTopic")) { m_amazonIdEventTopic = EventNotificationTopicStatusMapper::GetEventNotificationTopicStatusForName(jsonValue.GetString("AmazonIdEventTopic")); m_amazonIdEventTopicHasBeenSet = true; } return *this; } JsonValue SidewalkEventNotificationConfigurations::Jsonize() const { JsonValue payload; if(m_amazonIdEventTopicHasBeenSet) { payload.WithString("AmazonIdEventTopic", EventNotificationTopicStatusMapper::GetNameForEventNotificationTopicStatus(m_amazonIdEventTopic)); } return payload; } } // namespace Model } // namespace IoTWireless } // namespace Aws
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "config.h" #include "core/animation/TimingInput.h" #include "bindings/core/v8/Dictionary.h" #include "core/animation/AnimationNodeTiming.h" #include "core/animation/AnimationTestHelper.h" #include <gtest/gtest.h> #include <v8.h> namespace blink { class AnimationTimingInputTest : public ::testing::Test { protected: AnimationTimingInputTest() : m_isolate(v8::Isolate::GetCurrent()) , m_scope(m_isolate) { } Timing applyTimingInputNumber(String timingProperty, double timingPropertyValue) { v8::Handle<v8::Object> timingInput = v8::Object::New(m_isolate); setV8ObjectPropertyAsNumber(timingInput, timingProperty, timingPropertyValue); Dictionary timingInputDictionary = Dictionary(v8::Handle<v8::Value>::Cast(timingInput), m_isolate, exceptionState); return TimingInput::convert(timingInputDictionary); } Timing applyTimingInputString(String timingProperty, String timingPropertyValue) { v8::Handle<v8::Object> timingInput = v8::Object::New(m_isolate); setV8ObjectPropertyAsString(timingInput, timingProperty, timingPropertyValue); Dictionary timingInputDictionary = Dictionary(v8::Handle<v8::Value>::Cast(timingInput), m_isolate, exceptionState); return TimingInput::convert(timingInputDictionary); } v8::Isolate* m_isolate; TrackExceptionState exceptionState; private: V8TestingScope m_scope; }; TEST_F(AnimationTimingInputTest, TimingInputStartDelay) { EXPECT_EQ(1.1, applyTimingInputNumber("delay", 1100).startDelay); EXPECT_EQ(-1, applyTimingInputNumber("delay", -1000).startDelay); EXPECT_EQ(1, applyTimingInputString("delay", "1000").startDelay); EXPECT_EQ(0, applyTimingInputString("delay", "1s").startDelay); EXPECT_EQ(0, applyTimingInputString("delay", "Infinity").startDelay); EXPECT_EQ(0, applyTimingInputString("delay", "-Infinity").startDelay); EXPECT_EQ(0, applyTimingInputString("delay", "NaN").startDelay); EXPECT_EQ(0, applyTimingInputString("delay", "rubbish").startDelay); } TEST_F(AnimationTimingInputTest, TimingInputEndDelay) { EXPECT_EQ(10, applyTimingInputNumber("endDelay", 10000).endDelay); EXPECT_EQ(-2.5, applyTimingInputNumber("endDelay", -2500).endDelay); } TEST_F(AnimationTimingInputTest, TimingInputFillMode) { Timing::FillMode defaultFillMode = Timing::FillModeAuto; EXPECT_EQ(Timing::FillModeAuto, applyTimingInputString("fill", "auto").fillMode); EXPECT_EQ(Timing::FillModeForwards, applyTimingInputString("fill", "forwards").fillMode); EXPECT_EQ(Timing::FillModeNone, applyTimingInputString("fill", "none").fillMode); EXPECT_EQ(Timing::FillModeBackwards, applyTimingInputString("fill", "backwards").fillMode); EXPECT_EQ(Timing::FillModeBoth, applyTimingInputString("fill", "both").fillMode); EXPECT_EQ(defaultFillMode, applyTimingInputString("fill", "everything!").fillMode); EXPECT_EQ(defaultFillMode, applyTimingInputString("fill", "backwardsandforwards").fillMode); EXPECT_EQ(defaultFillMode, applyTimingInputNumber("fill", 2).fillMode); } TEST_F(AnimationTimingInputTest, TimingInputIterationStart) { EXPECT_EQ(1.1, applyTimingInputNumber("iterationStart", 1.1).iterationStart); EXPECT_EQ(0, applyTimingInputNumber("iterationStart", -1).iterationStart); EXPECT_EQ(0, applyTimingInputString("iterationStart", "Infinity").iterationStart); EXPECT_EQ(0, applyTimingInputString("iterationStart", "-Infinity").iterationStart); EXPECT_EQ(0, applyTimingInputString("iterationStart", "NaN").iterationStart); EXPECT_EQ(0, applyTimingInputString("iterationStart", "rubbish").iterationStart); } TEST_F(AnimationTimingInputTest, TimingInputIterationCount) { EXPECT_EQ(2.1, applyTimingInputNumber("iterations", 2.1).iterationCount); EXPECT_EQ(0, applyTimingInputNumber("iterations", -1).iterationCount); Timing timing = applyTimingInputString("iterations", "Infinity"); EXPECT_TRUE(std::isinf(timing.iterationCount)); EXPECT_GT(timing.iterationCount, 0); EXPECT_EQ(0, applyTimingInputString("iterations", "-Infinity").iterationCount); EXPECT_EQ(1, applyTimingInputString("iterations", "NaN").iterationCount); EXPECT_EQ(1, applyTimingInputString("iterations", "rubbish").iterationCount); } TEST_F(AnimationTimingInputTest, TimingInputIterationDuration) { EXPECT_EQ(1.1, applyTimingInputNumber("duration", 1100).iterationDuration); EXPECT_TRUE(std::isnan(applyTimingInputNumber("duration", -1000).iterationDuration)); EXPECT_EQ(1, applyTimingInputString("duration", "1000").iterationDuration); Timing timing = applyTimingInputString("duration", "Infinity"); EXPECT_TRUE(std::isinf(timing.iterationDuration)); EXPECT_GT(timing.iterationDuration, 0); EXPECT_TRUE(std::isnan(applyTimingInputString("duration", "-Infinity").iterationDuration)); EXPECT_TRUE(std::isnan(applyTimingInputString("duration", "NaN").iterationDuration)); EXPECT_TRUE(std::isnan(applyTimingInputString("duration", "auto").iterationDuration)); EXPECT_TRUE(std::isnan(applyTimingInputString("duration", "rubbish").iterationDuration)); } TEST_F(AnimationTimingInputTest, TimingInputPlaybackRate) { EXPECT_EQ(2.1, applyTimingInputNumber("playbackRate", 2.1).playbackRate); EXPECT_EQ(-1, applyTimingInputNumber("playbackRate", -1).playbackRate); EXPECT_EQ(1, applyTimingInputString("playbackRate", "Infinity").playbackRate); EXPECT_EQ(1, applyTimingInputString("playbackRate", "-Infinity").playbackRate); EXPECT_EQ(1, applyTimingInputString("playbackRate", "NaN").playbackRate); EXPECT_EQ(1, applyTimingInputString("playbackRate", "rubbish").playbackRate); } TEST_F(AnimationTimingInputTest, TimingInputDirection) { Timing::PlaybackDirection defaultPlaybackDirection = Timing::PlaybackDirectionNormal; EXPECT_EQ(Timing::PlaybackDirectionNormal, applyTimingInputString("direction", "normal").direction); EXPECT_EQ(Timing::PlaybackDirectionReverse, applyTimingInputString("direction", "reverse").direction); EXPECT_EQ(Timing::PlaybackDirectionAlternate, applyTimingInputString("direction", "alternate").direction); EXPECT_EQ(Timing::PlaybackDirectionAlternateReverse, applyTimingInputString("direction", "alternate-reverse").direction); EXPECT_EQ(defaultPlaybackDirection, applyTimingInputString("direction", "rubbish").direction); EXPECT_EQ(defaultPlaybackDirection, applyTimingInputNumber("direction", 2).direction); } TEST_F(AnimationTimingInputTest, TimingInputTimingFunction) { const RefPtr<TimingFunction> defaultTimingFunction = LinearTimingFunction::shared(); EXPECT_EQ(*CubicBezierTimingFunction::preset(CubicBezierTimingFunction::Ease), *applyTimingInputString("easing", "ease").timingFunction); EXPECT_EQ(*CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn), *applyTimingInputString("easing", "ease-in").timingFunction); EXPECT_EQ(*CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut), *applyTimingInputString("easing", "ease-out").timingFunction); EXPECT_EQ(*CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseInOut), *applyTimingInputString("easing", "ease-in-out").timingFunction); EXPECT_EQ(*LinearTimingFunction::shared(), *applyTimingInputString("easing", "linear").timingFunction); EXPECT_EQ(*StepsTimingFunction::preset(StepsTimingFunction::Start), *applyTimingInputString("easing", "step-start").timingFunction); EXPECT_EQ(*StepsTimingFunction::preset(StepsTimingFunction::Middle), *applyTimingInputString("easing", "step-middle").timingFunction); EXPECT_EQ(*StepsTimingFunction::preset(StepsTimingFunction::End), *applyTimingInputString("easing", "step-end").timingFunction); EXPECT_EQ(*CubicBezierTimingFunction::create(1, 1, 0.3, 0.3), *applyTimingInputString("easing", "cubic-bezier(1, 1, 0.3, 0.3)").timingFunction); EXPECT_EQ(*StepsTimingFunction::create(3, StepsTimingFunction::Start), *applyTimingInputString("easing", "steps(3, start)").timingFunction); EXPECT_EQ(*StepsTimingFunction::create(5, StepsTimingFunction::Middle), *applyTimingInputString("easing", "steps(5, middle)").timingFunction); EXPECT_EQ(*StepsTimingFunction::create(5, StepsTimingFunction::End), *applyTimingInputString("easing", "steps(5, end)").timingFunction); EXPECT_EQ(*defaultTimingFunction, *applyTimingInputString("easing", "steps(5.6, end)").timingFunction); EXPECT_EQ(*defaultTimingFunction, *applyTimingInputString("easing", "cubic-bezier(2, 2, 0.3, 0.3)").timingFunction); EXPECT_EQ(*defaultTimingFunction, *applyTimingInputString("easing", "rubbish").timingFunction); EXPECT_EQ(*defaultTimingFunction, *applyTimingInputNumber("easing", 2).timingFunction); EXPECT_EQ(*defaultTimingFunction, *applyTimingInputString("easing", "initial").timingFunction); } TEST_F(AnimationTimingInputTest, TimingInputEmpty) { Timing controlTiming; v8::Handle<v8::Object> timingInput = v8::Object::New(m_isolate); Dictionary timingInputDictionary = Dictionary(v8::Handle<v8::Value>::Cast(timingInput), m_isolate, exceptionState); Timing updatedTiming = TimingInput::convert(timingInputDictionary); EXPECT_EQ(controlTiming.startDelay, updatedTiming.startDelay); EXPECT_EQ(controlTiming.fillMode, updatedTiming.fillMode); EXPECT_EQ(controlTiming.iterationStart, updatedTiming.iterationStart); EXPECT_EQ(controlTiming.iterationCount, updatedTiming.iterationCount); EXPECT_TRUE(std::isnan(updatedTiming.iterationDuration)); EXPECT_EQ(controlTiming.playbackRate, updatedTiming.playbackRate); EXPECT_EQ(controlTiming.direction, updatedTiming.direction); EXPECT_EQ(*controlTiming.timingFunction, *updatedTiming.timingFunction); } } // namespace blink
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include <algorithm> #include <memory> #include <string> #include <type_traits> #include <utility> #include <gtest/gtest.h> #include "arrow/array.h" #include "arrow/buffer.h" #include "arrow/compute/api.h" #include "arrow/compute/kernels/codegen_internal.h" #include "arrow/compute/kernels/test_util.h" #include "arrow/type.h" #include "arrow/type_traits.h" #include "arrow/util/bit_util.h" #include "arrow/util/checked_cast.h" #include "arrow/util/string.h" #include "arrow/testing/gtest_common.h" #include "arrow/testing/gtest_util.h" #include "arrow/testing/random.h" namespace arrow { namespace compute { std::shared_ptr<Array> TweakValidityBit(const std::shared_ptr<Array>& array, int64_t index, bool validity) { auto data = array->data()->Copy(); if (data->buffers[0] == nullptr) { data->buffers[0] = *AllocateBitmap(data->length); BitUtil::SetBitsTo(data->buffers[0]->mutable_data(), 0, data->length, true); } BitUtil::SetBitTo(data->buffers[0]->mutable_data(), index, validity); data->null_count = kUnknownNullCount; // Need to return a new array, because Array caches the null bitmap pointer return MakeArray(data); } template <typename T> class TestUnaryArithmetic : public TestBase { protected: using ArrowType = T; using CType = typename ArrowType::c_type; static std::shared_ptr<DataType> type_singleton() { return TypeTraits<ArrowType>::type_singleton(); } using UnaryFunction = std::function<Result<Datum>(const Datum&, ArithmeticOptions, ExecContext*)>; void SetUp() override { options_.check_overflow = false; } std::shared_ptr<Scalar> MakeNullScalar() { return arrow::MakeNullScalar(type_singleton()); } std::shared_ptr<Scalar> MakeScalar(CType value) { return *arrow::MakeScalar(type_singleton(), value); } // (Scalar) void AssertUnaryOp(UnaryFunction func, CType argument, CType expected) { auto arg = MakeScalar(argument); auto exp = MakeScalar(expected); ASSERT_OK_AND_ASSIGN(auto actual, func(arg, options_, nullptr)); AssertScalarsApproxEqual(*exp, *actual.scalar(), /*verbose=*/true); } // (Scalar) void AssertUnaryOp(UnaryFunction func, const std::shared_ptr<Scalar>& arg, const std::shared_ptr<Scalar>& expected) { ASSERT_OK_AND_ASSIGN(auto actual, func(arg, options_, nullptr)); AssertScalarsApproxEqual(*expected, *actual.scalar(), /*verbose=*/true); } // (Array) void AssertUnaryOp(UnaryFunction func, const std::string& argument, const std::string& expected) { auto arg = ArrayFromJSON(type_singleton(), argument); AssertUnaryOp(func, arg, expected); } // (Array) void AssertUnaryOp(UnaryFunction func, const std::shared_ptr<Array>& arg, const std::string& expected_json) { const auto expected = ArrayFromJSON(type_singleton(), expected_json); ASSERT_OK_AND_ASSIGN(Datum actual, func(arg, options_, nullptr)); ValidateAndAssertApproxEqual(actual.make_array(), expected); // Also check (Scalar) operations const int64_t length = expected->length(); for (int64_t i = 0; i < length; ++i) { const auto expected_scalar = *expected->GetScalar(i); ASSERT_OK_AND_ASSIGN(actual, func(*arg->GetScalar(i), options_, nullptr)); AssertScalarsApproxEqual(*expected_scalar, *actual.scalar(), /*verbose=*/true, equal_options_); } } void AssertUnaryOpRaises(UnaryFunction func, const std::string& argument, const std::string& expected_msg) { auto arg = ArrayFromJSON(type_singleton(), argument); EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid, ::testing::HasSubstr(expected_msg), func(arg, options_, nullptr)); } void AssertUnaryOpNotImplemented(UnaryFunction func, const std::string& argument) { auto arg = ArrayFromJSON(type_singleton(), argument); const char* expected_msg = "has no kernel matching input types"; EXPECT_RAISES_WITH_MESSAGE_THAT(NotImplemented, ::testing::HasSubstr(expected_msg), func(arg, options_, nullptr)); } void ValidateAndAssertApproxEqual(const std::shared_ptr<Array>& actual, const std::string& expected) { const auto exp = ArrayFromJSON(type_singleton(), expected); ValidateAndAssertApproxEqual(actual, exp); } void ValidateAndAssertApproxEqual(const std::shared_ptr<Array>& actual, const std::shared_ptr<Array>& expected) { ASSERT_OK(actual->ValidateFull()); AssertArraysApproxEqual(*expected, *actual, /*verbose=*/true, equal_options_); } void SetOverflowCheck(bool value = true) { options_.check_overflow = value; } void SetNansEqual(bool value = true) { this->equal_options_ = equal_options_.nans_equal(value); } ArithmeticOptions options_ = ArithmeticOptions(); EqualOptions equal_options_ = EqualOptions::Defaults(); }; template <typename T> class TestUnaryArithmeticIntegral : public TestUnaryArithmetic<T> {}; template <typename T> class TestUnaryArithmeticSigned : public TestUnaryArithmeticIntegral<T> {}; template <typename T> class TestUnaryArithmeticUnsigned : public TestUnaryArithmeticIntegral<T> {}; template <typename T> class TestUnaryArithmeticFloating : public TestUnaryArithmetic<T> {}; template <typename T> class TestBinaryArithmetic : public TestBase { protected: using ArrowType = T; using CType = typename ArrowType::c_type; static std::shared_ptr<DataType> type_singleton() { return TypeTraits<ArrowType>::type_singleton(); } using BinaryFunction = std::function<Result<Datum>(const Datum&, const Datum&, ArithmeticOptions, ExecContext*)>; void SetUp() override { options_.check_overflow = false; } std::shared_ptr<Scalar> MakeNullScalar() { return arrow::MakeNullScalar(type_singleton()); } std::shared_ptr<Scalar> MakeScalar(CType value) { return *arrow::MakeScalar(type_singleton(), value); } // (Scalar, Scalar) void AssertBinop(BinaryFunction func, CType lhs, CType rhs, CType expected) { auto left = MakeScalar(lhs); auto right = MakeScalar(rhs); auto exp = MakeScalar(expected); ASSERT_OK_AND_ASSIGN(auto actual, func(left, right, options_, nullptr)); AssertScalarsApproxEqual(*exp, *actual.scalar(), /*verbose=*/true); } // (Scalar, Array) void AssertBinop(BinaryFunction func, CType lhs, const std::string& rhs, const std::string& expected) { auto left = MakeScalar(lhs); AssertBinop(func, left, rhs, expected); } // (Scalar, Array) void AssertBinop(BinaryFunction func, const std::shared_ptr<Scalar>& left, const std::string& rhs, const std::string& expected) { auto right = ArrayFromJSON(type_singleton(), rhs); auto exp = ArrayFromJSON(type_singleton(), expected); ASSERT_OK_AND_ASSIGN(auto actual, func(left, right, options_, nullptr)); ValidateAndAssertApproxEqual(actual.make_array(), expected); } // (Array, Scalar) void AssertBinop(BinaryFunction func, const std::string& lhs, CType rhs, const std::string& expected) { auto right = MakeScalar(rhs); AssertBinop(func, lhs, right, expected); } // (Array, Scalar) void AssertBinop(BinaryFunction func, const std::string& lhs, const std::shared_ptr<Scalar>& right, const std::string& expected) { auto left = ArrayFromJSON(type_singleton(), lhs); auto exp = ArrayFromJSON(type_singleton(), expected); ASSERT_OK_AND_ASSIGN(auto actual, func(left, right, options_, nullptr)); ValidateAndAssertApproxEqual(actual.make_array(), expected); } // (Array, Array) void AssertBinop(BinaryFunction func, const std::string& lhs, const std::string& rhs, const std::string& expected) { auto left = ArrayFromJSON(type_singleton(), lhs); auto right = ArrayFromJSON(type_singleton(), rhs); AssertBinop(func, left, right, expected); } // (Array, Array) void AssertBinop(BinaryFunction func, const std::shared_ptr<Array>& left, const std::shared_ptr<Array>& right, const std::string& expected_json) { const auto expected = ArrayFromJSON(type_singleton(), expected_json); ASSERT_OK_AND_ASSIGN(Datum actual, func(left, right, options_, nullptr)); ValidateAndAssertApproxEqual(actual.make_array(), expected); // Also check (Scalar, Scalar) operations const int64_t length = expected->length(); for (int64_t i = 0; i < length; ++i) { const auto expected_scalar = *expected->GetScalar(i); ASSERT_OK_AND_ASSIGN( actual, func(*left->GetScalar(i), *right->GetScalar(i), options_, nullptr)); AssertScalarsApproxEqual(*expected_scalar, *actual.scalar(), /*verbose=*/true, equal_options_); } } void AssertBinopRaises(BinaryFunction func, const std::string& lhs, const std::string& rhs, const std::string& expected_msg) { auto left = ArrayFromJSON(type_singleton(), lhs); auto right = ArrayFromJSON(type_singleton(), rhs); EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid, testing::HasSubstr(expected_msg), func(left, right, options_, nullptr)); } void ValidateAndAssertApproxEqual(const std::shared_ptr<Array>& actual, const std::string& expected) { ValidateAndAssertApproxEqual(actual, ArrayFromJSON(type_singleton(), expected)); } void ValidateAndAssertApproxEqual(const std::shared_ptr<Array>& actual, const std::shared_ptr<Array>& expected) { ASSERT_OK(actual->ValidateFull()); AssertArraysApproxEqual(*expected, *actual, /*verbose=*/true, equal_options_); } void SetOverflowCheck(bool value = true) { options_.check_overflow = value; } void SetNansEqual(bool value = true) { this->equal_options_ = equal_options_.nans_equal(value); } ArithmeticOptions options_ = ArithmeticOptions(); EqualOptions equal_options_ = EqualOptions::Defaults(); }; template <typename... Elements> std::string MakeArray(Elements... elements) { std::vector<std::string> elements_as_strings = {std::to_string(elements)...}; std::vector<util::string_view> elements_as_views(sizeof...(Elements)); std::copy(elements_as_strings.begin(), elements_as_strings.end(), elements_as_views.begin()); return "[" + ::arrow::internal::JoinStrings(elements_as_views, ",") + "]"; } template <typename T> class TestBinaryArithmeticIntegral : public TestBinaryArithmetic<T> {}; template <typename T> class TestBinaryArithmeticSigned : public TestBinaryArithmeticIntegral<T> {}; template <typename T> class TestBinaryArithmeticUnsigned : public TestBinaryArithmeticIntegral<T> {}; template <typename T> class TestBinaryArithmeticFloating : public TestBinaryArithmetic<T> {}; // InputType - OutputType pairs using IntegralTypes = testing::Types<Int8Type, Int16Type, Int32Type, Int64Type, UInt8Type, UInt16Type, UInt32Type, UInt64Type>; using SignedIntegerTypes = testing::Types<Int8Type, Int16Type, Int32Type, Int64Type>; using UnsignedIntegerTypes = testing::Types<UInt8Type, UInt16Type, UInt32Type, UInt64Type>; // TODO(kszucs): add half-float using FloatingTypes = testing::Types<FloatType, DoubleType>; TYPED_TEST_SUITE(TestUnaryArithmeticIntegral, IntegralTypes); TYPED_TEST_SUITE(TestUnaryArithmeticSigned, SignedIntegerTypes); TYPED_TEST_SUITE(TestUnaryArithmeticUnsigned, UnsignedIntegerTypes); TYPED_TEST_SUITE(TestUnaryArithmeticFloating, FloatingTypes); TYPED_TEST_SUITE(TestBinaryArithmeticIntegral, IntegralTypes); TYPED_TEST_SUITE(TestBinaryArithmeticSigned, SignedIntegerTypes); TYPED_TEST_SUITE(TestBinaryArithmeticUnsigned, UnsignedIntegerTypes); TYPED_TEST_SUITE(TestBinaryArithmeticFloating, FloatingTypes); TYPED_TEST(TestBinaryArithmeticIntegral, Add) { for (auto check_overflow : {false, true}) { this->SetOverflowCheck(check_overflow); this->AssertBinop(Add, "[]", "[]", "[]"); this->AssertBinop(Add, "[3, 2, 6]", "[1, 0, 2]", "[4, 2, 8]"); // Nulls on left side this->AssertBinop(Add, "[null, 1, null]", "[3, 4, 5]", "[null, 5, null]"); this->AssertBinop(Add, "[3, 4, 5]", "[null, 1, null]", "[null, 5, null]"); // Nulls on both sides this->AssertBinop(Add, "[null, 1, 2]", "[3, 4, null]", "[null, 5, null]"); // All nulls this->AssertBinop(Add, "[null]", "[null]", "[null]"); // Scalar on the left this->AssertBinop(Add, 3, "[1, 2]", "[4, 5]"); this->AssertBinop(Add, 3, "[null, 2]", "[null, 5]"); this->AssertBinop(Add, this->MakeNullScalar(), "[1, 2]", "[null, null]"); this->AssertBinop(Add, this->MakeNullScalar(), "[null, 2]", "[null, null]"); // Scalar on the right this->AssertBinop(Add, "[1, 2]", 3, "[4, 5]"); this->AssertBinop(Add, "[null, 2]", 3, "[null, 5]"); this->AssertBinop(Add, "[1, 2]", this->MakeNullScalar(), "[null, null]"); this->AssertBinop(Add, "[null, 2]", this->MakeNullScalar(), "[null, null]"); } } TYPED_TEST(TestBinaryArithmeticIntegral, Sub) { for (auto check_overflow : {false, true}) { this->SetOverflowCheck(check_overflow); this->AssertBinop(Subtract, "[]", "[]", "[]"); this->AssertBinop(Subtract, "[3, 2, 6]", "[1, 0, 2]", "[2, 2, 4]"); // Nulls on left side this->AssertBinop(Subtract, "[null, 4, null]", "[2, 1, 0]", "[null, 3, null]"); this->AssertBinop(Subtract, "[5, 4, 3]", "[null, 1, null]", "[null, 3, null]"); // Nulls on both sides this->AssertBinop(Subtract, "[null, 4, 3]", "[2, 1, null]", "[null, 3, null]"); // All nulls this->AssertBinop(Subtract, "[null]", "[null]", "[null]"); // Scalar on the left this->AssertBinop(Subtract, 3, "[1, 2]", "[2, 1]"); this->AssertBinop(Subtract, 3, "[null, 2]", "[null, 1]"); this->AssertBinop(Subtract, this->MakeNullScalar(), "[1, 2]", "[null, null]"); this->AssertBinop(Subtract, this->MakeNullScalar(), "[null, 2]", "[null, null]"); // Scalar on the right this->AssertBinop(Subtract, "[4, 5]", 3, "[1, 2]"); this->AssertBinop(Subtract, "[null, 5]", 3, "[null, 2]"); this->AssertBinop(Subtract, "[1, 2]", this->MakeNullScalar(), "[null, null]"); this->AssertBinop(Subtract, "[null, 2]", this->MakeNullScalar(), "[null, null]"); } } TEST(TestBinaryArithmetic, SubtractTimestamps) { random::RandomArrayGenerator rand(kRandomSeed); const int64_t length = 100; auto lhs = rand.Int64(length, 0, 100000000); auto rhs = rand.Int64(length, 0, 100000000); auto expected_int64 = (*Subtract(lhs, rhs)).make_array(); for (auto unit : internal::AllTimeUnits()) { auto timestamp_ty = timestamp(unit); auto duration_ty = duration(unit); auto lhs_timestamp = *lhs->View(timestamp_ty); auto rhs_timestamp = *rhs->View(timestamp_ty); auto result = (*Subtract(lhs_timestamp, rhs_timestamp)).make_array(); ASSERT_TRUE(result->type()->Equals(*duration_ty)); AssertArraysEqual(**result->View(int64()), *expected_int64); } } TYPED_TEST(TestBinaryArithmeticIntegral, Mul) { for (auto check_overflow : {false, true}) { this->SetOverflowCheck(check_overflow); this->AssertBinop(Multiply, "[]", "[]", "[]"); this->AssertBinop(Multiply, "[3, 2, 6]", "[1, 0, 2]", "[3, 0, 12]"); // Nulls on left side this->AssertBinop(Multiply, "[null, 2, null]", "[4, 5, 6]", "[null, 10, null]"); this->AssertBinop(Multiply, "[4, 5, 6]", "[null, 2, null]", "[null, 10, null]"); // Nulls on both sides this->AssertBinop(Multiply, "[null, 2, 3]", "[4, 5, null]", "[null, 10, null]"); // All nulls this->AssertBinop(Multiply, "[null]", "[null]", "[null]"); // Scalar on the left this->AssertBinop(Multiply, 3, "[4, 5]", "[12, 15]"); this->AssertBinop(Multiply, 3, "[null, 5]", "[null, 15]"); this->AssertBinop(Multiply, this->MakeNullScalar(), "[1, 2]", "[null, null]"); this->AssertBinop(Multiply, this->MakeNullScalar(), "[null, 2]", "[null, null]"); // Scalar on the right this->AssertBinop(Multiply, "[4, 5]", 3, "[12, 15]"); this->AssertBinop(Multiply, "[null, 5]", 3, "[null, 15]"); this->AssertBinop(Multiply, "[1, 2]", this->MakeNullScalar(), "[null, null]"); this->AssertBinop(Multiply, "[null, 2]", this->MakeNullScalar(), "[null, null]"); } } TYPED_TEST(TestBinaryArithmeticSigned, Add) { this->AssertBinop(Add, "[-7, 6, 5, 4, 3, 2, 1]", "[-6, 5, -4, 3, -2, 1, 0]", "[-13, 11, 1, 7, 1, 3, 1]"); this->AssertBinop(Add, -1, "[-6, 5, -4, 3, -2, 1, 0]", "[-7, 4, -5, 2, -3, 0, -1]"); this->AssertBinop(Add, -10, 5, -5); } TYPED_TEST(TestBinaryArithmeticSigned, OverflowWraps) { using CType = typename TestFixture::CType; auto min = std::numeric_limits<CType>::lowest(); auto max = std::numeric_limits<CType>::max(); this->AssertBinop(Subtract, MakeArray(min, max, min), MakeArray(1, max, max), MakeArray(max, 0, 1)); this->AssertBinop(Multiply, MakeArray(min, max, max), MakeArray(max, 2, max), MakeArray(min, CType(-2), 1)); } TYPED_TEST(TestBinaryArithmeticIntegral, OverflowRaises) { using CType = typename TestFixture::CType; auto min = std::numeric_limits<CType>::lowest(); auto max = std::numeric_limits<CType>::max(); this->SetOverflowCheck(true); this->AssertBinopRaises(Add, MakeArray(min, max, max), MakeArray(CType(-1), 1, max), "overflow"); this->AssertBinopRaises(Subtract, MakeArray(min, max), MakeArray(1, max), "overflow"); this->AssertBinopRaises(Subtract, MakeArray(min), MakeArray(max), "overflow"); this->AssertBinopRaises(Multiply, MakeArray(min, max, max), MakeArray(max, 2, max), "overflow"); } TYPED_TEST(TestBinaryArithmeticSigned, AddOverflowRaises) { using CType = typename TestFixture::CType; auto min = std::numeric_limits<CType>::lowest(); auto max = std::numeric_limits<CType>::max(); this->SetOverflowCheck(true); this->AssertBinop(Add, MakeArray(max), MakeArray(-1), MakeArray(max - 1)); this->AssertBinop(Add, MakeArray(min), MakeArray(1), MakeArray(min + 1)); this->AssertBinop(Add, MakeArray(-1), MakeArray(2), MakeArray(1)); this->AssertBinop(Add, MakeArray(1), MakeArray(-2), MakeArray(-1)); this->AssertBinopRaises(Add, MakeArray(max), MakeArray(1), "overflow"); this->AssertBinopRaises(Add, MakeArray(min), MakeArray(-1), "overflow"); // Overflow should not be checked on underlying value slots when output would be null auto left = ArrayFromJSON(this->type_singleton(), MakeArray(1, max, min)); auto right = ArrayFromJSON(this->type_singleton(), MakeArray(1, 1, -1)); left = TweakValidityBit(left, 1, false); right = TweakValidityBit(right, 2, false); this->AssertBinop(Add, left, right, "[2, null, null]"); } TYPED_TEST(TestBinaryArithmeticSigned, SubOverflowRaises) { using CType = typename TestFixture::CType; auto min = std::numeric_limits<CType>::lowest(); auto max = std::numeric_limits<CType>::max(); this->SetOverflowCheck(true); this->AssertBinop(Subtract, MakeArray(max), MakeArray(1), MakeArray(max - 1)); this->AssertBinop(Subtract, MakeArray(min), MakeArray(-1), MakeArray(min + 1)); this->AssertBinop(Subtract, MakeArray(-1), MakeArray(-2), MakeArray(1)); this->AssertBinop(Subtract, MakeArray(1), MakeArray(2), MakeArray(-1)); this->AssertBinopRaises(Subtract, MakeArray(max), MakeArray(-1), "overflow"); this->AssertBinopRaises(Subtract, MakeArray(min), MakeArray(1), "overflow"); // Overflow should not be checked on underlying value slots when output would be null auto left = ArrayFromJSON(this->type_singleton(), MakeArray(2, max, min)); auto right = ArrayFromJSON(this->type_singleton(), MakeArray(1, -1, 1)); left = TweakValidityBit(left, 1, false); right = TweakValidityBit(right, 2, false); this->AssertBinop(Subtract, left, right, "[1, null, null]"); } TYPED_TEST(TestBinaryArithmeticSigned, MulOverflowRaises) { using CType = typename TestFixture::CType; auto min = std::numeric_limits<CType>::lowest(); auto max = std::numeric_limits<CType>::max(); this->SetOverflowCheck(true); this->AssertBinop(Multiply, MakeArray(max), MakeArray(-1), MakeArray(min + 1)); this->AssertBinop(Multiply, MakeArray(max / 2), MakeArray(-2), MakeArray(min + 2)); this->AssertBinopRaises(Multiply, MakeArray(max), MakeArray(2), "overflow"); this->AssertBinopRaises(Multiply, MakeArray(max / 2), MakeArray(3), "overflow"); this->AssertBinopRaises(Multiply, MakeArray(max / 2), MakeArray(-3), "overflow"); this->AssertBinopRaises(Multiply, MakeArray(min), MakeArray(2), "overflow"); this->AssertBinopRaises(Multiply, MakeArray(min / 2), MakeArray(3), "overflow"); this->AssertBinopRaises(Multiply, MakeArray(min), MakeArray(-1), "overflow"); this->AssertBinopRaises(Multiply, MakeArray(min / 2), MakeArray(-2), "overflow"); // Overflow should not be checked on underlying value slots when output would be null auto left = ArrayFromJSON(this->type_singleton(), MakeArray(2, max, min / 2)); auto right = ArrayFromJSON(this->type_singleton(), MakeArray(1, 2, 3)); left = TweakValidityBit(left, 1, false); right = TweakValidityBit(right, 2, false); this->AssertBinop(Multiply, left, right, "[2, null, null]"); } TYPED_TEST(TestBinaryArithmeticUnsigned, OverflowWraps) { using CType = typename TestFixture::CType; auto min = std::numeric_limits<CType>::lowest(); auto max = std::numeric_limits<CType>::max(); this->SetOverflowCheck(false); this->AssertBinop(Add, MakeArray(min, max, max), MakeArray(CType(-1), 1, max), MakeArray(max, min, CType(-2))); this->AssertBinop(Subtract, MakeArray(min, max, min), MakeArray(1, max, max), MakeArray(max, 0, 1)); this->AssertBinop(Multiply, MakeArray(min, max, max), MakeArray(max, 2, max), MakeArray(min, CType(-2), 1)); } TYPED_TEST(TestBinaryArithmeticSigned, Sub) { this->AssertBinop(Subtract, "[0, 1, 2, 3, 4, 5, 6]", "[1, 2, 3, 4, 5, 6, 7]", "[-1, -1, -1, -1, -1, -1, -1]"); this->AssertBinop(Subtract, "[0, 0, 0, 0, 0, 0, 0]", "[6, 5, 4, 3, 2, 1, 0]", "[-6, -5, -4, -3, -2, -1, 0]"); this->AssertBinop(Subtract, "[10, 12, 4, 50, 50, 32, 11]", "[2, 0, 6, 1, 5, 3, 4]", "[8, 12, -2, 49, 45, 29, 7]"); this->AssertBinop(Subtract, "[null, 1, 3, null, 2, 5]", "[1, 4, 2, 5, 0, 3]", "[null, -3, 1, null, 2, 2]"); } TYPED_TEST(TestBinaryArithmeticSigned, Mul) { this->AssertBinop(Multiply, "[-10, 12, 4, 50, -5, 32, 11]", "[-2, 0, -6, 1, 5, 3, 4]", "[20, 0, -24, 50, -25, 96, 44]"); this->AssertBinop(Multiply, -2, "[-10, 12, 4, 50, -5, 32, 11]", "[20, -24, -8, -100, 10, -64, -22]"); this->AssertBinop(Multiply, -5, -5, 25); } // NOTE: cannot test Inf / -Inf (ARROW-9495) TYPED_TEST(TestBinaryArithmeticFloating, Add) { this->AssertBinop(Add, "[]", "[]", "[]"); this->AssertBinop(Add, "[1.5, 0.5]", "[2.0, -3]", "[3.5, -2.5]"); // Nulls on the left this->AssertBinop(Add, "[null, 0.5]", "[2.0, -3]", "[null, -2.5]"); // Nulls on the right this->AssertBinop(Add, "[1.5, 0.5]", "[null, -3]", "[null, -2.5]"); // Nulls on both sides this->AssertBinop(Add, "[null, 1.5, 0.5]", "[2.0, -3, null]", "[null, -1.5, null]"); // Scalar on the left this->AssertBinop(Add, -1.5f, "[0.0, 2.0]", "[-1.5, 0.5]"); this->AssertBinop(Add, -1.5f, "[null, 2.0]", "[null, 0.5]"); this->AssertBinop(Add, this->MakeNullScalar(), "[0.0, 2.0]", "[null, null]"); this->AssertBinop(Add, this->MakeNullScalar(), "[null, 2.0]", "[null, null]"); // Scalar on the right this->AssertBinop(Add, "[0.0, 2.0]", -1.5f, "[-1.5, 0.5]"); this->AssertBinop(Add, "[null, 2.0]", -1.5f, "[null, 0.5]"); this->AssertBinop(Add, "[0.0, 2.0]", this->MakeNullScalar(), "[null, null]"); this->AssertBinop(Add, "[null, 2.0]", this->MakeNullScalar(), "[null, null]"); } TYPED_TEST(TestBinaryArithmeticFloating, Div) { for (auto check_overflow : {false, true}) { this->SetOverflowCheck(check_overflow); // Empty arrays this->AssertBinop(Divide, "[]", "[]", "[]"); // Ordinary arrays this->AssertBinop(Divide, "[3.4, 0.64, 1.28]", "[1, 2, 4]", "[3.4, 0.32, 0.32]"); // Array with nulls this->AssertBinop(Divide, "[null, 1, 3.3, null, 2]", "[1, 4, 2, 5, 0.1]", "[null, 0.25, 1.65, null, 20]"); // Scalar divides by array this->AssertBinop(Divide, 10.0F, "[null, 1, 2.5, null, 2, 5]", "[null, 10, 4, null, 5, 2]"); // Array divides by scalar this->AssertBinop(Divide, "[null, 1, 2.5, null, 2, 5]", 10.0F, "[null, 0.1, 0.25, null, 0.2, 0.5]"); // Array with infinity this->AssertBinop(Divide, "[3.4, Inf, -Inf]", "[1, 2, 3]", "[3.4, Inf, -Inf]"); // Array with NaN this->SetNansEqual(true); this->AssertBinop(Divide, "[3.4, NaN, 2.0]", "[1, 2, 2.0]", "[3.4, NaN, 1.0]"); // Scalar divides by scalar this->AssertBinop(Divide, 21.0F, 3.0F, 7.0F); } } TYPED_TEST(TestBinaryArithmeticIntegral, Div) { for (auto check_overflow : {false, true}) { this->SetOverflowCheck(check_overflow); // Empty arrays this->AssertBinop(Divide, "[]", "[]", "[]"); // Ordinary arrays this->AssertBinop(Divide, "[3, 2, 6]", "[1, 1, 2]", "[3, 2, 3]"); // Array with nulls this->AssertBinop(Divide, "[null, 10, 30, null, 20]", "[1, 4, 2, 5, 10]", "[null, 2, 15, null, 2]"); // Scalar divides by array this->AssertBinop(Divide, 33, "[null, 1, 3, null, 2]", "[null, 33, 11, null, 16]"); // Array divides by scalar this->AssertBinop(Divide, "[null, 10, 30, null, 2]", 3, "[null, 3, 10, null, 0]"); // Scalar divides by scalar this->AssertBinop(Divide, 16, 7, 2); } } TYPED_TEST(TestBinaryArithmeticSigned, Div) { // Ordinary arrays this->AssertBinop(Divide, "[-3, 2, -6]", "[1, 1, 2]", "[-3, 2, -3]"); // Array with nulls this->AssertBinop(Divide, "[null, 10, 30, null, -20]", "[1, 4, 2, 5, 10]", "[null, 2, 15, null, -2]"); // Scalar divides by array this->AssertBinop(Divide, 33, "[null, -1, -3, null, 2]", "[null, -33, -11, null, 16]"); // Array divides by scalar this->AssertBinop(Divide, "[null, 10, 30, null, 2]", 3, "[null, 3, 10, null, 0]"); // Scalar divides by scalar this->AssertBinop(Divide, -16, -8, 2); } TYPED_TEST(TestBinaryArithmeticIntegral, DivideByZero) { for (auto check_overflow : {false, true}) { this->SetOverflowCheck(check_overflow); this->AssertBinopRaises(Divide, "[3, 2, 6]", "[1, 1, 0]", "divide by zero"); } } TYPED_TEST(TestBinaryArithmeticFloating, DivideByZero) { this->SetOverflowCheck(true); this->AssertBinopRaises(Divide, "[3.0, 2.0, 6.0]", "[1.0, 1.0, 0.0]", "divide by zero"); this->AssertBinopRaises(Divide, "[3.0, 2.0, 0.0]", "[1.0, 1.0, 0.0]", "divide by zero"); this->AssertBinopRaises(Divide, "[3.0, 2.0, -6.0]", "[1.0, 1.0, 0.0]", "divide by zero"); this->SetOverflowCheck(false); this->SetNansEqual(true); this->AssertBinop(Divide, "[3.0, 2.0, 6.0]", "[1.0, 1.0, 0.0]", "[3.0, 2.0, Inf]"); this->AssertBinop(Divide, "[3.0, 2.0, 0.0]", "[1.0, 1.0, 0.0]", "[3.0, 2.0, NaN]"); this->AssertBinop(Divide, "[3.0, 2.0, -6.0]", "[1.0, 1.0, 0.0]", "[3.0, 2.0, -Inf]"); } TYPED_TEST(TestBinaryArithmeticSigned, DivideOverflowRaises) { using CType = typename TestFixture::CType; auto min = std::numeric_limits<CType>::lowest(); this->SetOverflowCheck(true); this->AssertBinopRaises(Divide, MakeArray(min), MakeArray(-1), "overflow"); this->SetOverflowCheck(false); this->AssertBinop(Divide, MakeArray(min), MakeArray(-1), "[0]"); } TYPED_TEST(TestBinaryArithmeticFloating, Power) { using CType = typename TestFixture::CType; auto max = std::numeric_limits<CType>::max(); this->SetNansEqual(true); for (auto check_overflow : {false, true}) { this->SetOverflowCheck(check_overflow); // Empty arrays this->AssertBinop(Power, "[]", "[]", "[]"); // Ordinary arrays this->AssertBinop(Power, "[3.4, 16, 0.64, 1.2, 0]", "[1, 0.5, 2, 4, 0]", "[3.4, 4, 0.4096, 2.0736, 1]"); // Array with nulls this->AssertBinop(Power, "[null, 1, 3.3, null, 2]", "[1, 4, 2, 5, 0.1]", "[null, 1, 10.89, null, 1.07177346]"); // Scalar exponentiated by array this->AssertBinop(Power, 10.0F, "[null, 1, 2.5, null, 2, 5]", "[null, 10, 316.227766017, null, 100, 100000]"); // Array exponentiated by scalar this->AssertBinop(Power, "[null, 1, 2.5, null, 2, 5]", 10.0F, "[null, 1, 9536.74316406, null, 1024, 9765625]"); // Array with infinity this->AssertBinop(Power, "[3.4, Inf, -Inf, 1.1, 100000]", "[1, 2, 3, Inf, 100000]", "[3.4, Inf, -Inf, Inf, Inf]"); // Array with NaN this->AssertBinop(Power, "[3.4, NaN, 2.0]", "[1, 2, 2.0]", "[3.4, NaN, 4.0]"); // Scalar exponentiated by scalar this->AssertBinop(Power, 21.0F, 3.0F, 9261.0F); // Divide by zero this->AssertBinop(Power, "[0.0, 0.0]", "[-1.0, -3.0]", "[Inf, Inf]"); // Check overflow behaviour this->AssertBinop(Power, max, 10, INFINITY); } // Edge cases - removing NaNs this->AssertBinop(Power, "[1, NaN, 0, null, 1.2, -Inf, Inf, 1.1, 1, 0, 1, 0]", "[NaN, 0, NaN, 1, null, 1, 2, -Inf, Inf, 0, 0, 42]", "[1, 1, NaN, null, null, -Inf, Inf, 0, 1, 1, 1, 0]"); } TYPED_TEST(TestBinaryArithmeticIntegral, Power) { using CType = typename TestFixture::CType; auto max = std::numeric_limits<CType>::max(); for (auto check_overflow : {false, true}) { this->SetOverflowCheck(check_overflow); // Empty arrays this->AssertBinop(Power, "[]", "[]", "[]"); // Ordinary arrays this->AssertBinop(Power, "[3, 2, 6, 2]", "[1, 1, 2, 0]", "[3, 2, 36, 1]"); // Array with nulls this->AssertBinop(Power, "[null, 2, 3, null, 20]", "[1, 6, 2, 5, 1]", "[null, 64, 9, null, 20]"); // Scalar exponentiated by array this->AssertBinop(Power, 3, "[null, 3, 4, null, 2]", "[null, 27, 81, null, 9]"); // Array exponentiated by scalar this->AssertBinop(Power, "[null, 10, 3, null, 2]", 2, "[null, 100, 9, null, 4]"); // Scalar exponentiated by scalar this->AssertBinop(Power, 4, 3, 64); // Edge cases this->AssertBinop(Power, "[0, 1, 0]", "[0, 0, 42]", "[1, 1, 0]"); } // Overflow raises this->SetOverflowCheck(true); this->AssertBinopRaises(Power, MakeArray(max), MakeArray(10), "overflow"); // Disable overflow check this->SetOverflowCheck(false); this->AssertBinop(Power, max, 10, 1); } TYPED_TEST(TestBinaryArithmeticSigned, Power) { using CType = typename TestFixture::CType; auto max = std::numeric_limits<CType>::max(); for (auto check_overflow : {false, true}) { this->SetOverflowCheck(check_overflow); // Empty arrays this->AssertBinop(Power, "[]", "[]", "[]"); // Ordinary arrays this->AssertBinop(Power, "[-3, 2, -6, 2]", "[3, 1, 2, 0]", "[-27, 2, 36, 1]"); // Array with nulls this->AssertBinop(Power, "[null, 10, 127, null, -20]", "[1, 2, 1, 5, 1]", "[null, 100, 127, null, -20]"); // Scalar exponentiated by array this->AssertBinop(Power, 11, "[null, 1, null, 2]", "[null, 11, null, 121]"); // Array exponentiated by scalar this->AssertBinop(Power, "[null, 1, 3, null, 2]", 3, "[null, 1, 27, null, 8]"); // Scalar exponentiated by scalar this->AssertBinop(Power, 16, 1, 16); // Edge cases this->AssertBinop(Power, "[1, 0, -1, 2]", "[0, 42, 0, 1]", "[1, 0, 1, 2]"); // Divide by zero raises this->AssertBinopRaises(Power, MakeArray(0), MakeArray(-1), "integers to negative integer powers are not allowed"); } // Overflow raises this->SetOverflowCheck(true); this->AssertBinopRaises(Power, MakeArray(max), MakeArray(10), "overflow"); // Disable overflow check this->SetOverflowCheck(false); this->AssertBinop(Power, max, 10, 1); } TYPED_TEST(TestBinaryArithmeticFloating, Sub) { this->AssertBinop(Subtract, "[]", "[]", "[]"); this->AssertBinop(Subtract, "[1.5, 0.5]", "[2.0, -3]", "[-0.5, 3.5]"); // Nulls on the left this->AssertBinop(Subtract, "[null, 0.5]", "[2.0, -3]", "[null, 3.5]"); // Nulls on the right this->AssertBinop(Subtract, "[1.5, 0.5]", "[null, -3]", "[null, 3.5]"); // Nulls on both sides this->AssertBinop(Subtract, "[null, 1.5, 0.5]", "[2.0, -3, null]", "[null, 4.5, null]"); // Scalar on the left this->AssertBinop(Subtract, -1.5f, "[0.0, 2.0]", "[-1.5, -3.5]"); this->AssertBinop(Subtract, -1.5f, "[null, 2.0]", "[null, -3.5]"); this->AssertBinop(Subtract, this->MakeNullScalar(), "[0.0, 2.0]", "[null, null]"); this->AssertBinop(Subtract, this->MakeNullScalar(), "[null, 2.0]", "[null, null]"); // Scalar on the right this->AssertBinop(Subtract, "[0.0, 2.0]", -1.5f, "[1.5, 3.5]"); this->AssertBinop(Subtract, "[null, 2.0]", -1.5f, "[null, 3.5]"); this->AssertBinop(Subtract, "[0.0, 2.0]", this->MakeNullScalar(), "[null, null]"); this->AssertBinop(Subtract, "[null, 2.0]", this->MakeNullScalar(), "[null, null]"); } TYPED_TEST(TestBinaryArithmeticFloating, Mul) { this->AssertBinop(Multiply, "[]", "[]", "[]"); this->AssertBinop(Multiply, "[1.5, 0.5]", "[2.0, -3]", "[3.0, -1.5]"); // Nulls on the left this->AssertBinop(Multiply, "[null, 0.5]", "[2.0, -3]", "[null, -1.5]"); // Nulls on the right this->AssertBinop(Multiply, "[1.5, 0.5]", "[null, -3]", "[null, -1.5]"); // Nulls on both sides this->AssertBinop(Multiply, "[null, 1.5, 0.5]", "[2.0, -3, null]", "[null, -4.5, null]"); // Scalar on the left this->AssertBinop(Multiply, -1.5f, "[0.0, 2.0]", "[0.0, -3.0]"); this->AssertBinop(Multiply, -1.5f, "[null, 2.0]", "[null, -3.0]"); this->AssertBinop(Multiply, this->MakeNullScalar(), "[0.0, 2.0]", "[null, null]"); this->AssertBinop(Multiply, this->MakeNullScalar(), "[null, 2.0]", "[null, null]"); // Scalar on the right this->AssertBinop(Multiply, "[0.0, 2.0]", -1.5f, "[0.0, -3.0]"); this->AssertBinop(Multiply, "[null, 2.0]", -1.5f, "[null, -3.0]"); this->AssertBinop(Multiply, "[0.0, 2.0]", this->MakeNullScalar(), "[null, null]"); this->AssertBinop(Multiply, "[null, 2.0]", this->MakeNullScalar(), "[null, null]"); } TEST(TestBinaryArithmetic, DispatchBest) { for (std::string name : {"add", "subtract", "multiply", "divide", "power"}) { for (std::string suffix : {"", "_checked"}) { name += suffix; CheckDispatchBest(name, {int32(), int32()}, {int32(), int32()}); CheckDispatchBest(name, {int32(), null()}, {int32(), int32()}); CheckDispatchBest(name, {null(), int32()}, {int32(), int32()}); CheckDispatchBest(name, {int32(), int8()}, {int32(), int32()}); CheckDispatchBest(name, {int32(), int16()}, {int32(), int32()}); CheckDispatchBest(name, {int32(), int32()}, {int32(), int32()}); CheckDispatchBest(name, {int32(), int64()}, {int64(), int64()}); CheckDispatchBest(name, {int32(), uint8()}, {int32(), int32()}); CheckDispatchBest(name, {int32(), uint16()}, {int32(), int32()}); CheckDispatchBest(name, {int32(), uint32()}, {int64(), int64()}); CheckDispatchBest(name, {int32(), uint64()}, {int64(), int64()}); CheckDispatchBest(name, {uint8(), uint8()}, {uint8(), uint8()}); CheckDispatchBest(name, {uint8(), uint16()}, {uint16(), uint16()}); CheckDispatchBest(name, {int32(), float32()}, {float32(), float32()}); CheckDispatchBest(name, {float32(), int64()}, {float32(), float32()}); CheckDispatchBest(name, {float64(), int32()}, {float64(), float64()}); CheckDispatchBest(name, {dictionary(int8(), float64()), float64()}, {float64(), float64()}); CheckDispatchBest(name, {dictionary(int8(), float64()), int16()}, {float64(), float64()}); } } } TEST(TestBinaryArithmetic, AddWithImplicitCasts) { CheckScalarBinary("add", ArrayFromJSON(int32(), "[0, 1, 2, null]"), ArrayFromJSON(float64(), "[0.25, 0.5, 0.75, 1.0]"), ArrayFromJSON(float64(), "[0.25, 1.5, 2.75, null]")); CheckScalarBinary("add", ArrayFromJSON(int8(), "[-16, 0, 16, null]"), ArrayFromJSON(uint32(), "[3, 4, 5, 7]"), ArrayFromJSON(int64(), "[-13, 4, 21, null]")); CheckScalarBinary("add", ArrayFromJSON(dictionary(int32(), int32()), "[8, 6, 3, null, 2]"), ArrayFromJSON(uint32(), "[3, 4, 5, 7, 0]"), ArrayFromJSON(int64(), "[11, 10, 8, null, 2]")); CheckScalarBinary("add", ArrayFromJSON(int32(), "[0, 1, 2, null]"), std::make_shared<NullArray>(4), ArrayFromJSON(int32(), "[null, null, null, null]")); CheckScalarBinary("add", ArrayFromJSON(dictionary(int32(), int8()), "[0, 1, 2, null]"), ArrayFromJSON(uint32(), "[3, 4, 5, 7]"), ArrayFromJSON(int64(), "[3, 5, 7, null]")); } TEST(TestBinaryArithmetic, AddWithImplicitCastsUint64EdgeCase) { // int64 is as wide as we can promote CheckDispatchBest("add", {int8(), uint64()}, {int64(), int64()}); // this works sometimes CheckScalarBinary("add", ArrayFromJSON(int8(), "[-1]"), ArrayFromJSON(uint64(), "[0]"), ArrayFromJSON(int64(), "[-1]")); // ... but it can result in impossible implicit casts in the presence of uint64, since // some uint64 values cannot be cast to int64: ASSERT_RAISES(Invalid, CallFunction("add", {ArrayFromJSON(int64(), "[-1]"), ArrayFromJSON(uint64(), "[18446744073709551615]")})); } TEST(TestUnaryArithmetic, DispatchBest) { for (std::string name : {"negate", "abs", "abs_checked"}) { for (const auto& ty : {int8(), int16(), int32(), int64(), uint8(), uint16(), uint32(), uint64(), float32(), float64()}) { CheckDispatchBest(name, {ty}, {ty}); CheckDispatchBest(name, {dictionary(int8(), ty)}, {ty}); } } for (std::string name : {"negate_checked"}) { for (const auto& ty : {int8(), int16(), int32(), int64(), float32(), float64()}) { CheckDispatchBest(name, {ty}, {ty}); CheckDispatchBest(name, {dictionary(int8(), ty)}, {ty}); } } for (std::string name : {"negate", "negate_checked", "abs", "abs_checked"}) { CheckDispatchFails(name, {null()}); } } TYPED_TEST(TestUnaryArithmeticSigned, Negate) { using CType = typename TestFixture::CType; auto min = std::numeric_limits<CType>::min(); auto max = std::numeric_limits<CType>::max(); for (auto check_overflow : {false, true}) { this->SetOverflowCheck(check_overflow); // Empty arrays this->AssertUnaryOp(Negate, "[]", "[]"); // Array with nulls this->AssertUnaryOp(Negate, "[null]", "[null]"); this->AssertUnaryOp(Negate, this->MakeNullScalar(), this->MakeNullScalar()); this->AssertUnaryOp(Negate, "[1, null, -10]", "[-1, null, 10]"); // Arrays with zeros this->AssertUnaryOp(Negate, "[0, 0, -0]", "[0, -0, 0]"); this->AssertUnaryOp(Negate, 0, -0); this->AssertUnaryOp(Negate, -0, 0); this->AssertUnaryOp(Negate, 0, 0); // Ordinary arrays (positive inputs) this->AssertUnaryOp(Negate, "[1, 10, 127]", "[-1, -10, -127]"); this->AssertUnaryOp(Negate, 1, -1); this->AssertUnaryOp(Negate, this->MakeScalar(1), this->MakeScalar(-1)); // Ordinary arrays (negative inputs) this->AssertUnaryOp(Negate, "[-1, -10, -127]", "[1, 10, 127]"); this->AssertUnaryOp(Negate, -1, 1); this->AssertUnaryOp(Negate, MakeArray(-1), "[1]"); // Min/max (wrap arounds and overflow) this->AssertUnaryOp(Negate, max, min + 1); if (check_overflow) { this->AssertUnaryOpRaises(Negate, MakeArray(min), "overflow"); } else { this->AssertUnaryOp(Negate, min, min); } } // Overflow should not be checked on underlying value slots when output would be null this->SetOverflowCheck(true); auto arg = ArrayFromJSON(this->type_singleton(), MakeArray(1, max, min)); arg = TweakValidityBit(arg, 1, false); arg = TweakValidityBit(arg, 2, false); this->AssertUnaryOp(Negate, arg, "[-1, null, null]"); } TYPED_TEST(TestUnaryArithmeticUnsigned, Negate) { using CType = typename TestFixture::CType; auto min = std::numeric_limits<CType>::min(); auto max = std::numeric_limits<CType>::max(); // Empty arrays this->AssertUnaryOp(Negate, "[]", "[]"); // Array with nulls this->AssertUnaryOp(Negate, "[null]", "[null]"); this->AssertUnaryOp(Negate, this->MakeNullScalar(), this->MakeNullScalar()); // Min/max (wrap around) this->AssertUnaryOp(Negate, min, min); this->AssertUnaryOp(Negate, max, 1); this->AssertUnaryOp(Negate, 1, max); // Not implemented kernels this->SetOverflowCheck(true); this->AssertUnaryOpNotImplemented(Negate, "[0]"); } TYPED_TEST(TestUnaryArithmeticFloating, Negate) { using CType = typename TestFixture::CType; auto min = std::numeric_limits<CType>::lowest(); auto max = std::numeric_limits<CType>::max(); for (auto check_overflow : {false, true}) { this->SetOverflowCheck(check_overflow); // Empty arrays this->AssertUnaryOp(Negate, "[]", "[]"); // Array with nulls this->AssertUnaryOp(Negate, "[null]", "[null]"); this->AssertUnaryOp(Negate, this->MakeNullScalar(), this->MakeNullScalar()); this->AssertUnaryOp(Negate, "[1.3, null, -10.80]", "[-1.3, null, 10.80]"); // Arrays with zeros this->AssertUnaryOp(Negate, "[0.0, 0.0, -0.0]", "[0.0, -0.0, 0.0]"); this->AssertUnaryOp(Negate, 0.0F, -0.0F); this->AssertUnaryOp(Negate, -0.0F, 0.0F); this->AssertUnaryOp(Negate, 0.0F, 0.0F); // Ordinary arrays (positive inputs) this->AssertUnaryOp(Negate, "[1.3, 10.80, 12748.001]", "[-1.3, -10.80, -12748.001]"); this->AssertUnaryOp(Negate, 1.3F, -1.3F); this->AssertUnaryOp(Negate, this->MakeScalar(1.3F), this->MakeScalar(-1.3F)); // Ordinary arrays (negative inputs) this->AssertUnaryOp(Negate, "[-1.3, -10.80, -12748.001]", "[1.3, 10.80, 12748.001]"); this->AssertUnaryOp(Negate, -1.3F, 1.3F); this->AssertUnaryOp(Negate, MakeArray(-1.3F), "[1.3]"); // Arrays with infinites this->AssertUnaryOp(Negate, "[Inf, -Inf]", "[-Inf, Inf]"); // Arrays with NaNs this->SetNansEqual(true); this->AssertUnaryOp(Negate, "[NaN]", "[NaN]"); this->AssertUnaryOp(Negate, "[NaN]", "[-NaN]"); this->AssertUnaryOp(Negate, "[-NaN]", "[NaN]"); // Min/max this->AssertUnaryOp(Negate, min, max); this->AssertUnaryOp(Negate, max, min); } } TYPED_TEST(TestUnaryArithmeticSigned, AbsoluteValue) { using CType = typename TestFixture::CType; auto min = std::numeric_limits<CType>::min(); auto max = std::numeric_limits<CType>::max(); for (auto check_overflow : {false, true}) { this->SetOverflowCheck(check_overflow); // Empty array this->AssertUnaryOp(AbsoluteValue, "[]", "[]"); // Scalar/arrays with nulls this->AssertUnaryOp(AbsoluteValue, "[null]", "[null]"); this->AssertUnaryOp(AbsoluteValue, "[1, null, -10]", "[1, null, 10]"); this->AssertUnaryOp(AbsoluteValue, this->MakeNullScalar(), this->MakeNullScalar()); // Scalar/arrays with zeros this->AssertUnaryOp(AbsoluteValue, "[0, -0]", "[0, 0]"); this->AssertUnaryOp(AbsoluteValue, -0, 0); this->AssertUnaryOp(AbsoluteValue, 0, 0); // Ordinary scalar/arrays (positive inputs) this->AssertUnaryOp(AbsoluteValue, "[1, 10, 127]", "[1, 10, 127]"); this->AssertUnaryOp(AbsoluteValue, 1, 1); this->AssertUnaryOp(AbsoluteValue, this->MakeScalar(1), this->MakeScalar(1)); // Ordinary scalar/arrays (negative inputs) this->AssertUnaryOp(AbsoluteValue, "[-1, -10, -127]", "[1, 10, 127]"); this->AssertUnaryOp(AbsoluteValue, -1, 1); this->AssertUnaryOp(AbsoluteValue, MakeArray(-1), "[1]"); // Min/max this->AssertUnaryOp(AbsoluteValue, max, max); if (check_overflow) { this->AssertUnaryOpRaises(AbsoluteValue, MakeArray(min), "overflow"); } else { this->AssertUnaryOp(AbsoluteValue, min, min); } } // Overflow should not be checked on underlying value slots when output would be null this->SetOverflowCheck(true); auto arg = ArrayFromJSON(this->type_singleton(), MakeArray(-1, max, min)); arg = TweakValidityBit(arg, 1, false); arg = TweakValidityBit(arg, 2, false); this->AssertUnaryOp(AbsoluteValue, arg, "[1, null, null]"); } TYPED_TEST(TestUnaryArithmeticUnsigned, AbsoluteValue) { using CType = typename TestFixture::CType; auto min = std::numeric_limits<CType>::min(); auto max = std::numeric_limits<CType>::max(); for (auto check_overflow : {false, true}) { this->SetOverflowCheck(check_overflow); // Empty arrays this->AssertUnaryOp(AbsoluteValue, "[]", "[]"); // Array with nulls this->AssertUnaryOp(AbsoluteValue, "[null]", "[null]"); this->AssertUnaryOp(AbsoluteValue, this->MakeNullScalar(), this->MakeNullScalar()); // Ordinary arrays this->AssertUnaryOp(AbsoluteValue, "[0, 1, 10, 127]", "[0, 1, 10, 127]"); // Min/max this->AssertUnaryOp(AbsoluteValue, min, min); this->AssertUnaryOp(AbsoluteValue, max, max); } } TYPED_TEST(TestUnaryArithmeticFloating, AbsoluteValue) { using CType = typename TestFixture::CType; auto min = std::numeric_limits<CType>::lowest(); auto max = std::numeric_limits<CType>::max(); for (auto check_overflow : {false, true}) { this->SetOverflowCheck(check_overflow); // Empty array this->AssertUnaryOp(AbsoluteValue, "[]", "[]"); // Scalar/arrays with nulls this->AssertUnaryOp(AbsoluteValue, "[null]", "[null]"); this->AssertUnaryOp(AbsoluteValue, "[1.3, null, -10.80]", "[1.3, null, 10.80]"); this->AssertUnaryOp(AbsoluteValue, this->MakeNullScalar(), this->MakeNullScalar()); // Scalars/arrays with zeros this->AssertUnaryOp(AbsoluteValue, "[0.0, -0.0]", "[0.0, 0.0]"); this->AssertUnaryOp(AbsoluteValue, -0.0F, 0.0F); this->AssertUnaryOp(AbsoluteValue, 0.0F, 0.0F); // Ordinary scalars/arrays (positive inputs) this->AssertUnaryOp(AbsoluteValue, "[1.3, 10.80, 12748.001]", "[1.3, 10.80, 12748.001]"); this->AssertUnaryOp(AbsoluteValue, 1.3F, 1.3F); this->AssertUnaryOp(AbsoluteValue, this->MakeScalar(1.3F), this->MakeScalar(1.3F)); // Ordinary scalars/arrays (negative inputs) this->AssertUnaryOp(AbsoluteValue, "[-1.3, -10.80, -12748.001]", "[1.3, 10.80, 12748.001]"); this->AssertUnaryOp(AbsoluteValue, -1.3F, 1.3F); this->AssertUnaryOp(AbsoluteValue, MakeArray(-1.3F), "[1.3]"); // Arrays with infinites this->AssertUnaryOp(AbsoluteValue, "[Inf, -Inf]", "[Inf, Inf]"); // Arrays with NaNs this->SetNansEqual(true); this->AssertUnaryOp(AbsoluteValue, "[NaN]", "[NaN]"); this->AssertUnaryOp(AbsoluteValue, "[-NaN]", "[NaN]"); // Min/max this->AssertUnaryOp(AbsoluteValue, min, max); this->AssertUnaryOp(AbsoluteValue, max, max); } } } // namespace compute } // namespace arrow
/* * Copyright (c) 2015, The Linux Foundation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of The Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <utils/sys.h> #include <sys/ioctl.h> #include <fcntl.h> #include <unistd.h> #define __CLASS__ "Sys" namespace sdm { #ifndef SDM_VIRTUAL_DRIVER int PthreadCancel(pthread_t /* thread */) { return 0; } // Pointer to actual driver interfaces. Sys::ioctl Sys::ioctl_ = ::ioctl; Sys::open Sys::open_ = ::open; Sys::close Sys::close_ = ::close; Sys::poll Sys::poll_ = ::poll; Sys::pread Sys::pread_ = ::pread; Sys::pwrite Sys::pwrite_ = ::pwrite; Sys::fopen Sys::fopen_ = ::fopen; Sys::fclose Sys::fclose_ = ::fclose; Sys::getline Sys::getline_ = ::getline; Sys::pthread_cancel Sys::pthread_cancel_ = PthreadCancel; Sys::dup Sys::dup_ = ::dup; #else // Point to virtual driver interfaces. extern int virtual_ioctl(int fd, int cmd, ...); extern int virtual_open(const char *file_name, int access, ...); extern int virtual_close(int fd); extern int virtual_poll(struct pollfd *fds, nfds_t num, int timeout); extern ssize_t virtual_pread(int fd, void *data, size_t count, off_t offset); extern ssize_t virtual_pwrite(int fd, const void *data, size_t count, off_t offset); extern FILE* virtual_fopen(const char *fname, const char *mode); extern int virtual_fclose(FILE* fileptr); extern ssize_t virtual_getline(char **lineptr, size_t *linelen, FILE *stream); extern int virtual_dup(int fd); Sys::ioctl Sys::ioctl_ = virtual_ioctl; Sys::open Sys::open_ = virtual_open; Sys::close Sys::close_ = virtual_close; Sys::poll Sys::poll_ = virtual_poll; Sys::pread Sys::pread_ = virtual_pread; Sys::pwrite Sys::pwrite_ = virtual_pwrite; Sys::fopen Sys::fopen_ = virtual_fopen; Sys::fclose Sys::fclose_ = virtual_fclose; Sys::getline Sys::getline_ = virtual_getline; Sys::pthread_cancel Sys::pthread_cancel_ = ::pthread_cancel; Sys::dup Sys::dup_ = virtual_dup; #endif // SDM_VIRTUAL_DRIVER } // namespace sdm
// (C) Copyright 2013-2015 Steven R. Brandt // // SPDX-License-Identifier: BSL-1.0 // 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 <hpx/local/init.hpp> #include <hpx/modules/lcos_local.hpp> #include <atomic> #include <iostream> #include <memory> // This program illustrates the use of composable guards to perform // a computation that might otherwise rely on mutexes. In fact, guards // are like mutexes, but with the distinction that they are locked for // you (at the start of a task), and unlocked for you. // // In the example below, we use guards to manage incrementing the variables // i1 and i2. We don't need to use atomics for this, but it makes the // load, increment, and store steps more explicit. At the end, in order to // pass the test and get the correct total, every compare_exchange must // succeed. // // Because guards don't add locking structures to the current environment // during a calculation, they can never deadlock. Guards use only a // few atomic operations to perform their operations, and never cause a // task to block, so they should be quite fast. // // To use guards, call the run_guarded() method, supplying it with // a guard or guard set, and a task to be performed. typedef std::atomic<int> int_atomic; int_atomic i1(0), i2(0); hpx::lcos::local::guard_set guards; std::shared_ptr<hpx::lcos::local::guard> l1(new hpx::lcos::local::guard()); std::shared_ptr<hpx::lcos::local::guard> l2(new hpx::lcos::local::guard()); void incr1() { // implicitly lock l1 int tmp = i1.load(); i1.compare_exchange_strong(tmp, tmp + 1); // implicitly unlock l1 } void incr2() { // implicitly lock l2 int tmp = i2.load(); i2.compare_exchange_strong(tmp, tmp + 1); // implicitly unlock l2 } void both() { // implicitly lock l1 and l2 int tmp = i1.load(); i1.compare_exchange_strong(tmp, tmp + 1); tmp = i2.load(); i2.compare_exchange_strong(tmp, tmp + 1); // implicitly unlock l1 and l2 } int increments = 3000; void check_() { if (2 * increments == i1 && 2 * increments == i2) { std::cout << "Test passed" << std::endl; } else { std::cout << "Test failed: i1=" << i1 << " i2=" << i2 << std::endl; } } int hpx_main(hpx::program_options::variables_map& vm) { if (vm.count("increments")) increments = vm["increments"].as<int>(); // create the guard set guards.add(l1); guards.add(l2); for (int i = 0; i < increments; i++) { // spawn 3 asynchronous tasks run_guarded(guards, both); run_guarded(*l1, incr1); run_guarded(*l2, incr2); } run_guarded(guards, check_); return hpx::local::finalize(); } int main(int argc, char* argv[]) { hpx::program_options::options_description desc_commandline( "Usage: " HPX_APPLICATION_STRING " [options]"); // clang-format off desc_commandline.add_options() ("increments,n", hpx::program_options::value<int>()->default_value(3000), "the number of times to increment the counters") ; // clang-format on // Initialize and run HPX hpx::local::init_params init_args; init_args.desc_cmdline = desc_commandline; return hpx::local::init(hpx_main, argc, argv, init_args); }
// Time: O(n) // Space: O(1) class Solution { public: vector<int> decode(vector<int>& encoded) { int curr = 0; for (int i = 0; i <= size(encoded) + 1; ++i) { curr ^= i; if (i <= size(encoded) && i % 2 == 1) { curr ^= encoded[i]; } } vector<int> result = {curr}; for (const auto& x: encoded) { result.emplace_back(result.back() ^ x); } return result; } };
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/developer/debug/zxdb/symbols/array_type.h" #include "src/developer/debug/zxdb/symbols/arch.h" #include "src/lib/fxl/strings/string_printf.h" namespace zxdb { ArrayType::ArrayType(fxl::RefPtr<Type> value_type, std::optional<size_t> num_elts) : Type(DwarfTag::kArrayType), value_type_(std::move(value_type)), num_elts_(num_elts) { if (num_elts_) set_byte_size(*num_elts_ * value_type_->byte_size()); } ArrayType::~ArrayType() = default; const ArrayType* ArrayType::AsArrayType() const { return this; } std::string ArrayType::ComputeFullName() const { // Same as the nested case but with no "outer" string. return ComputeFullNameOfNestedArray(std::string()); } std::string ArrayType::ComputeFullNameOfNestedArray(const std::string& outer_dims) const { std::string elt_count = num_elts_ ? fxl::StringPrintf("[%zu]", *num_elts_) : "[]"; if (const ArrayType* inner_array = value_type_->AsArrayType()) { // Special-case nested arrays. return inner_array->ComputeFullNameOfNestedArray(outer_dims + elt_count); } return value_type_->GetFullName() + outer_dims + elt_count; } } // namespace zxdb
#pragma once #include "Drawer.hpp" #include "Listener.hpp" class App; class Camera : public Drawer, public Listener { public: Camera(App* app); ~Camera(); virtual void draw(); virtual bool mousePress(const int button); virtual void mouseRelease(const int button); virtual bool mouseMove(const int x, const int y); virtual bool mouseWheelMove(const int w); virtual bool keyPress(sf::Event::KeyEvent k); bool isRotationLocked() const; bool isPositionLocked() const; void isRotationLocked(const bool locked); void isPositionLocked(const bool locked); void setRadius(const float r); float getRadius() const; void setRotationX(const float x); void setRotationY(const float y); float getRotationX() const; float getRotationY() const; void setOriginX(const float x); void setOriginY(const float y); void setOriginZ(const float z); float getOriginX() const; float getOriginY() const; float getOriginZ() const; float getCameraX() const; float getCameraY() const; float getCameraZ() const; void moveRight(const float dist); void moveForward(const float dist); void moveUp(const float dist); void rotateX(const float deg); void rotateY(const float deg); App* getApp(); private: App* m_app; bool m_isRotLocked; bool m_isPosLocked; float m_radius; float m_oriX; float m_oriY; float m_oriZ; float m_rotX; float m_rotY; int m_oldMouseX; int m_oldMouseY; void _zoomIn(); void _zoomOut(); };
/** * Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved. * http://soramitsu.co.jp * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef IROHA_VALIDATION_MOCKS_HPP #define IROHA_VALIDATION_MOCKS_HPP #include <gmock/gmock.h> #include "validation/chain_validator.hpp" #include "validation/stateful_validator.hpp" #include "validation/stateless_validator.hpp" namespace iroha { namespace validation { class MockStatelessValidator : public StatelessValidator { public: MOCK_CONST_METHOD1(validate, bool(const model::Transaction &)); MOCK_CONST_METHOD1(validate, bool(const model::Query &)); }; class MockStatefulValidator : public validation::StatefulValidator { public: MOCK_METHOD2(validate, model::Proposal(const model::Proposal &, ametsuchi::TemporaryWsv &)); }; class MockChainValidator : public ChainValidator { public: MOCK_METHOD2(validateChain, bool(Commit, ametsuchi::MutableStorage &)); MOCK_METHOD2(validateBlock, bool(const model::Block &, ametsuchi::MutableStorage &)); }; } // namespace validation } // namespace iroha #endif // IROHA_VALIDATION_MOCKS_HPP
#ifndef PYTHONIC_NUMPY_ASCONTIGUOUSARRAY_HPP #define PYTHONIC_NUMPY_ASCONTIGUOUSARRAY_HPP #include "pythonic/include/numpy/ascontiguousarray.hpp" #include "pythonic/numpy/asarray.hpp" namespace pythonic { namespace numpy { FPROXY_IMPL(pythonic::numpy, ascontiguousarray, asarray); } } #endif
//================================================================================================== /** KIWAKU - Containers Well Made Copyright 2020 Joel FALCOU Licensed under the MIT License <http://opensource.org/licenses/MIT>. SPDX-License-Identifier: MIT **/ //================================================================================================== #include "test.hpp" #include <kiwaku/container/view.hpp> #include <kiwaku/algorithm/all.hpp> #include <algorithm> #include <vector> TTS_CASE( "Build a 4D view with constexpr shape settings from a C array" ) { float ref[24] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24}; kwk::view<float,kwk::_4D> view(ref,kwk::of_shape(4,1,3,2)); TTS_EQUAL( sizeof(view), sizeof(void*)*4*2 ); TTS_EQUAL( view.size() , 24 ); TTS_EQUAL( view.shape(), kwk::of_shape(4,1,3,2) ); TTS_EXPECT( (std::equal( view.begin(), view.end(), &ref[0])) ); TTS_EXPECT( (kwk::all ( [&](auto i, auto j, auto k, auto l) { return view(i,j,k,l) == ref[i+4*(j+1*(k+3*l))]; } , view.shape()) ) ); }; TTS_CASE( "Build a 4D view with constexpr shape settings from a pointer" ) { float ref[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24}; kwk::view<float,kwk::_4D> view(&ref[0],kwk::of_shape(4,1,3,2)); TTS_EQUAL( sizeof(view), sizeof(void*)*4*2 ); TTS_EQUAL( view.size() , 24 ); TTS_EQUAL( view.shape(), kwk::of_shape(4,1,3,2) ); TTS_EXPECT( (std::equal( view.begin(), view.end(), &ref[0])) ); TTS_EXPECT( (kwk::all ( [&](auto i, auto j, auto k, auto l) { return view(i,j,k,l) == ref[i+4*(j+1*(k+3*l))]; } , view.shape()) ) ); }; TTS_CASE( "Build a 4D view with constexpr shape settings from a pointer to const" ) { float const ref[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24}; kwk::view<float const,kwk::_4D> view(&ref[0],kwk::of_shape(4,1,3,2)); TTS_EQUAL( sizeof(view), sizeof(void*)*4*2 ); TTS_EQUAL( view.size() , 24 ); TTS_EQUAL( view.shape(), kwk::of_shape(4,1,3,2) ); TTS_EXPECT( (std::equal( view.begin(), view.end(), &ref[0])) ); TTS_EXPECT( (kwk::all ( [&](auto i, auto j, auto k, auto l) { return view(i,j,k,l) == ref[i+4*(j+1*(k+3*l))]; } , view.shape()) ) ); }; TTS_CASE( "Build a 4D view with constexpr shape settings from a ContiguousSequence" ) { std::vector<float> ref = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24}; kwk::view<float,kwk::_4D> view(ref,kwk::of_shape(4,1,3,2)); TTS_EQUAL( sizeof(view), sizeof(void*)*4*2 ); TTS_EQUAL( view.size() , 24 ); TTS_EQUAL( view.shape(), kwk::of_shape(4,1,3,2) ); TTS_EXPECT( (std::equal( view.begin(), view.end(), &ref[0])) ); TTS_EXPECT( (kwk::all ( [&](auto i, auto j, auto k, auto l) { return view(i,j,k,l) == ref[i+4*(j+1*(k+3*l))]; } , view.shape()) ) ); }; TTS_CASE( "Build a 4D view with constexpr shape settings from a const ContiguousSequence" ) { std::vector<float> const ref = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24}; kwk::view<float const,kwk::_4D> view(ref,kwk::of_shape(4,1,3,2)); TTS_EQUAL( sizeof(view), sizeof(void*)*4*2 ); TTS_EQUAL( view.size() , 24 ); TTS_EQUAL( view.shape(), kwk::of_shape(4,1,3,2) ); TTS_EXPECT( (std::equal( view.begin(), view.end(), &ref[0])) ); TTS_EXPECT( (kwk::all ( [&](auto i, auto j, auto k, auto l) { return view(i,j,k,l) == ref[i+4*(j+1*(k+3*l))]; } , view.shape()) ) ); };
#pragma once #include <vector> #include <algorithm> #include "Individual.hpp" namespace GA { /** * Популяция. */ template< typename GeneType> class Population { public: // Тип особи using individual_type = Individual<GeneType>; // Тип функции приспособленности using fitness_function = typename Individual<GeneType>::fitness_function; public: /** * Конструктор. * * \param populationSize Размер популяции */ Population( const std::size_t populationSize) : m_population(populationSize) {} // Задаём размер массива особей /** * Инициализация популяции * * \param generator Алгоритм генерации популяции * \param engine Движок генерации случайных чисел * \return */ template< typename Generator, typename Engine> void Init( const Generator& generator, Engine& engine) { // Проходим по каждой особи. // На данном этапе особи созданы, но не содержат полезной информации // поскольку были сконструированы дефолтным конструктором for (auto& individual : m_population) { // individual - неконстантная ссылка на текущую особь // Герерируем новую особь individual = generator(engine); } } /** * Получение размера популяции * * \return */ std::size_t GetSize() const { return m_population.size(); } /** * Доступ к особям * * \param index Индекс особи * \return Ссылка на особь */ individual_type& operator [] ( const std::size_t index) { return m_population[index]; } /** * Доступ к особям * * \param index Индекс особи * \return Константная ссылка на особь */ const individual_type& operator [] ( const std::size_t index) const { return m_population[index]; } /** * Вычисление приспособленности у каждой особи * * \param fitnessFn Функция приспособленности * \return */ void CalculateFitness( const fitness_function& fitnessFn) { // Проходим по каждой особи for (auto& individual : m_population) { // и вычисляем приспособленность individual.CalculateFitness(fitnessFn); } } /** * Мутация популяции * * \param mutator Алгоритм мутации * \param engine Движок генерации случайных чисел * \return */ template< typename Mutator, typename Engine> void Mutate( const Mutator& mutator, Engine& engine) { // Проходим по каждой особи for (auto& individual : m_population) { // и применяем алгоритм мутации mutator(individual, engine); } } /** * Получение наиболее приспособленной особи * * \return */ individual_type GetBestIndividual() { // Отсортируем массив выбранных особей по возрастанию // TODO: Добавить предикат сравнения функций приспособленности, // поскольку сейчас реализована задача минимизации, но необходимо // предусмотреть возможность решать задачу максимизации std::sort(m_population.begin(), m_population.end(), [] (const auto& individual1, const auto& individual2) { return individual1.GetFitness() < individual2.GetFitness(); }); // и вернём наиболее приспособленную return m_population.front(); } private: // Массив особей std::vector<individual_type> m_population; }; }
//===----------------------------------------------------------------------===// // // Peloton // // database_metrics_catalog.cpp // // Identification: src/catalog/query_metrics_catalog.cpp // // Copyright (c) 2015-17, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "catalog/database_metrics_catalog.h" #include "executor/logical_tile.h" #include "storage/data_table.h" #include "type/value_factory.h" namespace peloton { namespace catalog { DatabaseMetricsCatalog *DatabaseMetricsCatalog::GetInstance( concurrency::TransactionContext *txn) { static DatabaseMetricsCatalog database_metrics_catalog{txn}; return &database_metrics_catalog; } DatabaseMetricsCatalog::DatabaseMetricsCatalog(concurrency::TransactionContext *txn) : AbstractCatalog("CREATE TABLE " CATALOG_DATABASE_NAME "." DATABASE_METRICS_CATALOG_NAME " (" "database_oid INT NOT NULL, " "txn_committed INT NOT NULL, " "txn_aborted INT NOT NULL, " "time_stamp INT NOT NULL);", txn) { // Add secondary index here if necessary } DatabaseMetricsCatalog::~DatabaseMetricsCatalog() {} bool DatabaseMetricsCatalog::InsertDatabaseMetrics( oid_t database_oid, oid_t txn_committed, oid_t txn_aborted, oid_t time_stamp, type::AbstractPool *pool, concurrency::TransactionContext *txn) { std::unique_ptr<storage::Tuple> tuple( new storage::Tuple(catalog_table_->GetSchema(), true)); auto val0 = type::ValueFactory::GetIntegerValue(database_oid); auto val1 = type::ValueFactory::GetIntegerValue(txn_committed); auto val2 = type::ValueFactory::GetIntegerValue(txn_aborted); auto val3 = type::ValueFactory::GetIntegerValue(time_stamp); tuple->SetValue(ColumnId::DATABASE_OID, val0, pool); tuple->SetValue(ColumnId::TXN_COMMITTED, val1, pool); tuple->SetValue(ColumnId::TXN_ABORTED, val2, pool); tuple->SetValue(ColumnId::TIME_STAMP, val3, pool); // Insert the tuple into catalog table return InsertTuple(std::move(tuple), txn); } bool DatabaseMetricsCatalog::DeleteDatabaseMetrics( oid_t database_oid, concurrency::TransactionContext *txn) { oid_t index_offset = IndexId::PRIMARY_KEY; // Primary key index std::vector<type::Value> values; values.push_back(type::ValueFactory::GetIntegerValue(database_oid).Copy()); return DeleteWithIndexScan(index_offset, values, txn); } } // namespace catalog } // namespace peloton
#ifndef BOOST_CORE_REF_HPP #define BOOST_CORE_REF_HPP // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif #include <boost/config.hpp> #include <boost/config/workaround.hpp> #include <boost/core/addressof.hpp> #include <boost/core/enable_if.hpp> // // ref.hpp - ref/cref, useful helper functions // // Copyright (C) 1999, 2000 Jaakko Jarvi (jaakko.jarvi@cs.utu.fi) // Copyright (C) 2001, 2002 Peter Dimov // Copyright (C) 2002 David Abrahams // // Copyright (C) 2014 Glen Joseph Fernandes // (glenjofe@gmail.com) // // Copyright (C) 2014 Agustin Berge // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/core/doc/html/core/ref.html for documentation. // /** @file */ /** Boost namespace. */ namespace lslboost { #if defined( BOOST_MSVC ) && BOOST_WORKAROUND( BOOST_MSVC, == 1600 ) struct ref_workaround_tag {}; #endif namespace detail { template< class Y, class T > struct ref_convertible { typedef char (&yes) [1]; typedef char (&no) [2]; static yes f( T* ); static no f( ... ); enum _vt { value = sizeof( (f)( static_cast<Y*>(0) ) ) == sizeof(yes) }; }; struct ref_empty { }; } // namespace detail // reference_wrapper /** @brief Contains a reference to an object of type `T`. `reference_wrapper` is primarily used to "feed" references to function templates (algorithms) that take their parameter by value. It provides an implicit conversion to `T&`, which usually allows the function templates to work on references unmodified. */ template<class T> class reference_wrapper { public: /** Type `T`. */ typedef T type; /** Constructs a `reference_wrapper` object that stores a reference to `t`. @remark Does not throw. */ BOOST_FORCEINLINE explicit reference_wrapper(T& t): t_(lslboost::addressof(t)) {} #if defined( BOOST_MSVC ) && BOOST_WORKAROUND( BOOST_MSVC, == 1600 ) BOOST_FORCEINLINE explicit reference_wrapper( T & t, ref_workaround_tag ): t_( lslboost::addressof( t ) ) {} #endif #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) /** @remark Construction from a temporary object is disabled. */ BOOST_DELETED_FUNCTION(reference_wrapper(T&& t)) public: #endif template<class Y> friend class reference_wrapper; /** Constructs a `reference_wrapper` object that stores the reference stored in the compatible `reference_wrapper` `r`. @remark Only enabled when `Y*` is convertible to `T*`. @remark Does not throw. */ template<class Y> reference_wrapper( reference_wrapper<Y> r, typename enable_if_c<lslboost::detail::ref_convertible<Y, T>::value, lslboost::detail::ref_empty>::type = lslboost::detail::ref_empty() ): t_( r.t_ ) { } /** @return The stored reference. @remark Does not throw. */ BOOST_FORCEINLINE operator T& () const { return *t_; } /** @return The stored reference. @remark Does not throw. */ BOOST_FORCEINLINE T& get() const { return *t_; } /** @return A pointer to the object referenced by the stored reference. @remark Does not throw. */ BOOST_FORCEINLINE T* get_pointer() const { return t_; } private: T* t_; }; // ref /** @cond */ #if defined( BOOST_BORLANDC ) && BOOST_WORKAROUND( BOOST_BORLANDC, BOOST_TESTED_AT(0x581) ) # define BOOST_REF_CONST #else # define BOOST_REF_CONST const #endif /** @endcond */ /** @return `reference_wrapper<T>(t)` @remark Does not throw. */ template<class T> BOOST_FORCEINLINE reference_wrapper<T> BOOST_REF_CONST ref( T & t ) { #if defined( BOOST_MSVC ) && BOOST_WORKAROUND( BOOST_MSVC, == 1600 ) return reference_wrapper<T>( t, ref_workaround_tag() ); #else return reference_wrapper<T>( t ); #endif } // cref /** @return `reference_wrapper<T const>(t)` @remark Does not throw. */ template<class T> BOOST_FORCEINLINE reference_wrapper<T const> BOOST_REF_CONST cref( T const & t ) { return reference_wrapper<T const>(t); } #undef BOOST_REF_CONST #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) /** @cond */ #if defined(BOOST_NO_CXX11_DELETED_FUNCTIONS) # define BOOST_REF_DELETE #else # define BOOST_REF_DELETE = delete #endif /** @endcond */ /** @remark Construction from a temporary object is disabled. */ template<class T> void ref(T const&&) BOOST_REF_DELETE; /** @remark Construction from a temporary object is disabled. */ template<class T> void cref(T const&&) BOOST_REF_DELETE; #undef BOOST_REF_DELETE #endif // is_reference_wrapper /** @brief Determine if a type `T` is an instantiation of `reference_wrapper`. The value static constant will be true if the type `T` is a specialization of `reference_wrapper`. */ template<typename T> struct is_reference_wrapper { BOOST_STATIC_CONSTANT( bool, value = false ); }; /** @cond */ template<typename T> struct is_reference_wrapper< reference_wrapper<T> > { BOOST_STATIC_CONSTANT( bool, value = true ); }; #if !defined(BOOST_NO_CV_SPECIALIZATIONS) template<typename T> struct is_reference_wrapper< reference_wrapper<T> const > { BOOST_STATIC_CONSTANT( bool, value = true ); }; template<typename T> struct is_reference_wrapper< reference_wrapper<T> volatile > { BOOST_STATIC_CONSTANT( bool, value = true ); }; template<typename T> struct is_reference_wrapper< reference_wrapper<T> const volatile > { BOOST_STATIC_CONSTANT( bool, value = true ); }; #endif // !defined(BOOST_NO_CV_SPECIALIZATIONS) /** @endcond */ // unwrap_reference /** @brief Find the type in a `reference_wrapper`. The `typedef` type is `T::type` if `T` is a `reference_wrapper`, `T` otherwise. */ template<typename T> struct unwrap_reference { typedef T type; }; /** @cond */ template<typename T> struct unwrap_reference< reference_wrapper<T> > { typedef T type; }; #if !defined(BOOST_NO_CV_SPECIALIZATIONS) template<typename T> struct unwrap_reference< reference_wrapper<T> const > { typedef T type; }; template<typename T> struct unwrap_reference< reference_wrapper<T> volatile > { typedef T type; }; template<typename T> struct unwrap_reference< reference_wrapper<T> const volatile > { typedef T type; }; #endif // !defined(BOOST_NO_CV_SPECIALIZATIONS) /** @endcond */ // unwrap_ref /** @return `unwrap_reference<T>::type&(t)` @remark Does not throw. */ template<class T> BOOST_FORCEINLINE typename unwrap_reference<T>::type& unwrap_ref( T & t ) { return t; } // get_pointer /** @cond */ template<class T> BOOST_FORCEINLINE T* get_pointer( reference_wrapper<T> const & r ) { return r.get_pointer(); } /** @endcond */ } // namespace lslboost #endif // #ifndef BOOST_CORE_REF_HPP
#include "pch.h" #include "RenderBuffer.h" #include <glad/glad.h> Xeno::RenderBuffer::RenderBuffer() { glGenRenderbuffers(1, &mObjectID); } Xeno::RenderBuffer::RenderBuffer(const uint32_t width, const uint32_t height, const FrameBuffer::DepthStencilFormat format) { glGenRenderbuffers(1, &mObjectID); SetStorage(width, height, format); } Xeno::RenderBuffer::~RenderBuffer() { glDeleteRenderbuffers(1, &mObjectID); } void Xeno::RenderBuffer::Bind() const { glBindRenderbuffer(GL_RENDERBUFFER, mObjectID); } void Xeno::RenderBuffer::Unbind() const { glBindRenderbuffer(GL_RENDERBUFFER, 0); } void Xeno::RenderBuffer::SetStorage(const uint32_t width, const uint32_t height, const FrameBuffer::DepthStencilFormat format, const int32_t numSamples) const { Bind(); if (numSamples > 1) glRenderbufferStorageMultisample(GL_RENDERBUFFER, numSamples, (GLenum)format, width, height); else glRenderbufferStorage(GL_RENDERBUFFER, (GLenum)format, width, height); Unbind(); } uint32_t Xeno::RenderBuffer::GetObjectID() const { return mObjectID; }
/// #ifndef BAULK_CDN_HPP #define BAULK_CDN_HPP #include <string_view> namespace baulk { // https://baulk.io/cdn/hash/filename?url=u constexpr std::wstring_view BaulkMirrorURL = L"X-Baulk-Mirror-URL"; constexpr std::wstring_view BaulkChecksumKey = L"X-Baulk-Mirror-Hash"; struct cdn {}; } // namespace baulk #endif
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "../../../include/fpdfapi/fpdf_page.h" #include "../../../include/fpdfapi/fpdf_module.h" #include "../../../include/fpdfapi/fpdf_serial.h" #include "pageint.h" #define REQUIRE_PARAMS(count) if (m_ParamCount != count) { m_bAbort = TRUE; return; } CPDF_StreamContentParser::CPDF_StreamContentParser() { m_DefFontSize = 0; m_pCurStates = NULL; m_pLastTextObject = NULL; m_pPathPoints = NULL; m_PathClipType = 0; m_PathPointCount = m_PathAllocSize = 0; m_PathCurrentX = m_PathCurrentY = 0.0f; m_bResourceMissing = FALSE; m_bColored = FALSE; FXSYS_memset32(m_Type3Data, 0, sizeof(FX_FLOAT) * 6); m_ParamCount = 0; m_ParamStartPos = 0; m_bAbort = FALSE; m_pLastImageDict = NULL; m_pLastCloneImageDict = NULL; m_pLastImage = NULL; m_bReleaseLastDict = TRUE; m_pParentResources = NULL; #ifdef _FPDFAPI_MINI_ m_pObjectState = NULL; m_pObjectStack = NULL; m_pWordBuf = NULL; m_pDictName = NULL; m_pStreamBuf = NULL; m_WordState = 0; m_ObjectSize = 0; #endif } FX_BOOL CPDF_StreamContentParser::Initialize() { #ifdef _FPDFAPI_MINI_ m_pObjectState = FX_Alloc(FX_BOOL, _FPDF_MAX_OBJECT_STACK_SIZE_); FXSYS_memset32(m_pObjectState, 0, _FPDF_MAX_OBJECT_STACK_SIZE_ * sizeof(FX_BOOL)); m_pObjectStack = FX_Alloc(CPDF_Object*, _FPDF_MAX_OBJECT_STACK_SIZE_); FXSYS_memset32(m_pObjectStack, 0, _FPDF_MAX_OBJECT_STACK_SIZE_ * sizeof(CPDF_Object*)); m_pWordBuf = FX_Alloc(FX_BYTE, 256); FXSYS_memset32(m_pWordBuf, 0, 256 * sizeof(FX_BYTE)); m_pDictName = FX_Alloc(FX_BYTE, 256); FXSYS_memset32(m_pDictName, 0, 256 * sizeof(FX_BYTE)); m_pStreamBuf = FX_Alloc(FX_BYTE, STREAM_PARSE_BUFSIZE); FXSYS_memset32(m_pStreamBuf, 0, STREAM_PARSE_BUFSIZE * sizeof(FX_BYTE)); m_StringBuf.EstimateSize(1024); m_ObjectSize = 0; m_ImageSrcBuf.EstimateSize(STREAM_PARSE_BUFSIZE); #endif return TRUE; } CPDF_StreamContentParser::~CPDF_StreamContentParser() { ClearAllParams(); int i = 0; for (i = 0; i < m_StateStack.GetSize(); i ++) { delete (CPDF_AllStates*)m_StateStack[i]; } if (m_pPathPoints) { FX_Free(m_pPathPoints); } if (m_pCurStates) { delete m_pCurStates; } if (m_pLastImageDict) { m_pLastImageDict->Release(); } if (m_pLastCloneImageDict) { m_pLastCloneImageDict->Release(); } #ifdef _FPDFAPI_MINI_ for (i = 0; i < (int)m_ObjectSize; ++i) { if (!m_pObjectState[i]) { m_pObjectStack[i]->Release(); } } FX_Free(m_pObjectStack); FX_Free(m_pObjectState); FX_Free(m_pStreamBuf); FX_Free(m_pWordBuf); FX_Free(m_pDictName); #endif } void CPDF_StreamContentParser::PrepareParse(CPDF_Document* pDocument, CPDF_Dictionary* pPageResources, CPDF_Dictionary* pParentResources, CFX_AffineMatrix* pmtContentToUser, CPDF_PageObjects* pObjList, CPDF_Dictionary* pResources, CPDF_Rect* pBBox, CPDF_ParseOptions* pOptions, CPDF_AllStates* pStates, int level) { for (int i = 0; i < 6; i ++) { m_Type3Data[i] = 0; } m_pDocument = pDocument; m_pPageResources = pPageResources; m_pParentResources = pParentResources; if (pmtContentToUser) { m_mtContentToUser = *pmtContentToUser; } if (pOptions) { m_Options = *pOptions; } m_pObjectList = pObjList; m_pResources = pResources; if (pResources == NULL) { m_pResources = m_pParentResources; } if (m_pResources == NULL) { m_pResources = pPageResources; } if (pBBox) { m_BBox = *pBBox; } m_Level = level; m_pCurStates = FX_NEW CPDF_AllStates; if (pStates) { m_pCurStates->Copy(*pStates); } else { m_pCurStates->m_GeneralState.New(); m_pCurStates->m_GraphState.New(); m_pCurStates->m_TextState.New(); m_pCurStates->m_ColorState.New(); } #ifdef _FPDFAPI_MINI_ FXSYS_memset32(m_pObjectState, 0, _FPDF_MAX_OBJECT_STACK_SIZE_ * sizeof(FX_BOOL)); #endif } int CPDF_StreamContentParser::GetNextParamPos() { if (m_ParamCount == PARAM_BUF_SIZE) { m_ParamStartPos ++; if (m_ParamStartPos == PARAM_BUF_SIZE) { m_ParamStartPos = 0; } if (m_ParamBuf1[m_ParamStartPos].m_Type == 0) { m_ParamBuf1[m_ParamStartPos].m_pObject->Release(); } return m_ParamStartPos; } int index = m_ParamStartPos + m_ParamCount; if (index >= PARAM_BUF_SIZE) { index -= PARAM_BUF_SIZE; } m_ParamCount ++; return index; } void CPDF_StreamContentParser::AddNameParam(FX_LPCSTR name, int len) { int index = GetNextParamPos(); if (len > 32) { m_ParamBuf1[index].m_Type = 0; m_ParamBuf1[index].m_pObject = CPDF_Name::Create(PDF_NameDecode(CFX_ByteStringC(name, len))); } else { m_ParamBuf1[index].m_Type = PDFOBJ_NAME; if (FXSYS_memchr(name, '#', len) == NULL) { FXSYS_memcpy32(m_ParamBuf1[index].m_Name.m_Buffer, name, len); m_ParamBuf1[index].m_Name.m_Len = len; } else { CFX_ByteString str = PDF_NameDecode(CFX_ByteStringC(name, len)); FXSYS_memcpy32(m_ParamBuf1[index].m_Name.m_Buffer, (FX_LPCSTR)str, str.GetLength()); m_ParamBuf1[index].m_Name.m_Len = str.GetLength(); } } } void CPDF_StreamContentParser::AddNumberParam(FX_LPCSTR str, int len) { int index = GetNextParamPos(); m_ParamBuf1[index].m_Type = PDFOBJ_NUMBER; FX_atonum(CFX_ByteStringC(str, len), m_ParamBuf1[index].m_Number.m_bInteger, &m_ParamBuf1[index].m_Number.m_Integer); } void CPDF_StreamContentParser::AddObjectParam(CPDF_Object* pObj) { int index = GetNextParamPos(); m_ParamBuf1[index].m_Type = 0; m_ParamBuf1[index].m_pObject = pObj; } void CPDF_StreamContentParser::ClearAllParams() { FX_DWORD index = m_ParamStartPos; for (FX_DWORD i = 0; i < m_ParamCount; i ++) { if (m_ParamBuf1[index].m_Type == 0) { m_ParamBuf1[index].m_pObject->Release(); } index ++; if (index == PARAM_BUF_SIZE) { index = 0; } } m_ParamStartPos = 0; m_ParamCount = 0; } CPDF_Object* CPDF_StreamContentParser::GetObject(FX_DWORD index) { if (index >= m_ParamCount) { return NULL; } int real_index = m_ParamStartPos + m_ParamCount - index - 1; if (real_index >= PARAM_BUF_SIZE) { real_index -= PARAM_BUF_SIZE; } _ContentParam& param = m_ParamBuf1[real_index]; if (param.m_Type == PDFOBJ_NUMBER) { CPDF_Number* pNumber = CPDF_Number::Create(param.m_Number.m_bInteger, &param.m_Number.m_Integer); param.m_Type = 0; param.m_pObject = pNumber; return pNumber; } if (param.m_Type == PDFOBJ_NAME) { CPDF_Name* pName = CPDF_Name::Create(CFX_ByteString(param.m_Name.m_Buffer, param.m_Name.m_Len)); param.m_Type = 0; param.m_pObject = pName; return pName; } if (param.m_Type == 0) { return param.m_pObject; } ASSERT(FALSE); return NULL; } CFX_ByteString CPDF_StreamContentParser::GetString(FX_DWORD index) { if (index >= m_ParamCount) { return CFX_ByteString(); } int real_index = m_ParamStartPos + m_ParamCount - index - 1; if (real_index >= PARAM_BUF_SIZE) { real_index -= PARAM_BUF_SIZE; } _ContentParam& param = m_ParamBuf1[real_index]; if (param.m_Type == PDFOBJ_NAME) { return CFX_ByteString(param.m_Name.m_Buffer, param.m_Name.m_Len); } if (param.m_Type == 0) { return param.m_pObject->GetString(); } return CFX_ByteString(); } FX_FLOAT CPDF_StreamContentParser::GetNumber(FX_DWORD index) { if (index >= m_ParamCount) { return 0; } int real_index = m_ParamStartPos + m_ParamCount - index - 1; if (real_index >= PARAM_BUF_SIZE) { real_index -= PARAM_BUF_SIZE; } _ContentParam& param = m_ParamBuf1[real_index]; if (param.m_Type == PDFOBJ_NUMBER) { return param.m_Number.m_bInteger ? (FX_FLOAT)param.m_Number.m_Integer : param.m_Number.m_Float; } if (param.m_Type == 0) { return param.m_pObject->GetNumber(); } return 0; } FX_FLOAT CPDF_StreamContentParser::GetNumber16(FX_DWORD index) { return GetNumber(index); } void CPDF_StreamContentParser::SetGraphicStates(CPDF_PageObject* pObj, FX_BOOL bColor, FX_BOOL bText, FX_BOOL bGraph) { pObj->m_GeneralState = m_pCurStates->m_GeneralState; pObj->m_ClipPath = m_pCurStates->m_ClipPath; pObj->m_ContentMark = m_CurContentMark; if (bColor) { pObj->m_ColorState = m_pCurStates->m_ColorState; } if (bGraph) { pObj->m_GraphState = m_pCurStates->m_GraphState; } if (bText) { pObj->m_TextState = m_pCurStates->m_TextState; } } const struct _OpCode { FX_DWORD m_OpId; void (CPDF_StreamContentParser::*m_OpHandler)(); } g_OpCodes[] = { {FXBSTR_ID('"', 0, 0, 0), &CPDF_StreamContentParser::Handle_NextLineShowText_Space}, {FXBSTR_ID('\'', 0, 0, 0), &CPDF_StreamContentParser::Handle_NextLineShowText}, {FXBSTR_ID('B', 0, 0, 0), &CPDF_StreamContentParser::Handle_FillStrokePath}, {FXBSTR_ID('B', '*', 0, 0), &CPDF_StreamContentParser::Handle_EOFillStrokePath}, {FXBSTR_ID('B', 'D', 'C', 0), &CPDF_StreamContentParser::Handle_BeginMarkedContent_Dictionary}, {FXBSTR_ID('B', 'I', 0, 0), &CPDF_StreamContentParser::Handle_BeginImage}, {FXBSTR_ID('B', 'M', 'C', 0), &CPDF_StreamContentParser::Handle_BeginMarkedContent}, {FXBSTR_ID('B', 'T', 0, 0), &CPDF_StreamContentParser::Handle_BeginText}, {FXBSTR_ID('B', 'X', 0, 0), &CPDF_StreamContentParser::Handle_BeginSectionUndefined}, {FXBSTR_ID('C', 'S', 0, 0), &CPDF_StreamContentParser::Handle_SetColorSpace_Stroke}, {FXBSTR_ID('D', 'P', 0, 0), &CPDF_StreamContentParser::Handle_MarkPlace_Dictionary}, {FXBSTR_ID('D', 'o', 0, 0), &CPDF_StreamContentParser::Handle_ExecuteXObject}, {FXBSTR_ID('E', 'I', 0, 0), &CPDF_StreamContentParser::Handle_EndImage}, {FXBSTR_ID('E', 'M', 'C', 0), &CPDF_StreamContentParser::Handle_EndMarkedContent}, {FXBSTR_ID('E', 'T', 0, 0), &CPDF_StreamContentParser::Handle_EndText}, {FXBSTR_ID('E', 'X', 0, 0), &CPDF_StreamContentParser::Handle_EndSectionUndefined}, {FXBSTR_ID('F', 0, 0, 0), &CPDF_StreamContentParser::Handle_FillPathOld}, {FXBSTR_ID('G', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetGray_Stroke}, {FXBSTR_ID('I', 'D', 0, 0), &CPDF_StreamContentParser::Handle_BeginImageData}, {FXBSTR_ID('J', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetLineCap}, {FXBSTR_ID('K', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetCMYKColor_Stroke}, {FXBSTR_ID('M', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetMiterLimit}, {FXBSTR_ID('M', 'P', 0, 0), &CPDF_StreamContentParser::Handle_MarkPlace}, {FXBSTR_ID('Q', 0, 0, 0), &CPDF_StreamContentParser::Handle_RestoreGraphState}, {FXBSTR_ID('R', 'G', 0, 0), &CPDF_StreamContentParser::Handle_SetRGBColor_Stroke}, {FXBSTR_ID('S', 0, 0, 0), &CPDF_StreamContentParser::Handle_StrokePath}, {FXBSTR_ID('S', 'C', 0, 0), &CPDF_StreamContentParser::Handle_SetColor_Stroke}, {FXBSTR_ID('S', 'C', 'N', 0), &CPDF_StreamContentParser::Handle_SetColorPS_Stroke}, {FXBSTR_ID('T', '*', 0, 0), &CPDF_StreamContentParser::Handle_MoveToNextLine}, {FXBSTR_ID('T', 'D', 0, 0), &CPDF_StreamContentParser::Handle_MoveTextPoint_SetLeading}, {FXBSTR_ID('T', 'J', 0, 0), &CPDF_StreamContentParser::Handle_ShowText_Positioning}, {FXBSTR_ID('T', 'L', 0, 0), &CPDF_StreamContentParser::Handle_SetTextLeading}, {FXBSTR_ID('T', 'c', 0, 0), &CPDF_StreamContentParser::Handle_SetCharSpace}, {FXBSTR_ID('T', 'd', 0, 0), &CPDF_StreamContentParser::Handle_MoveTextPoint}, {FXBSTR_ID('T', 'f', 0, 0), &CPDF_StreamContentParser::Handle_SetFont}, {FXBSTR_ID('T', 'j', 0, 0), &CPDF_StreamContentParser::Handle_ShowText}, {FXBSTR_ID('T', 'm', 0, 0), &CPDF_StreamContentParser::Handle_SetTextMatrix}, {FXBSTR_ID('T', 'r', 0, 0), &CPDF_StreamContentParser::Handle_SetTextRenderMode}, {FXBSTR_ID('T', 's', 0, 0), &CPDF_StreamContentParser::Handle_SetTextRise}, {FXBSTR_ID('T', 'w', 0, 0), &CPDF_StreamContentParser::Handle_SetWordSpace}, {FXBSTR_ID('T', 'z', 0, 0), &CPDF_StreamContentParser::Handle_SetHorzScale}, {FXBSTR_ID('W', 0, 0, 0), &CPDF_StreamContentParser::Handle_Clip}, {FXBSTR_ID('W', '*', 0, 0), &CPDF_StreamContentParser::Handle_EOClip}, {FXBSTR_ID('b', 0, 0, 0), &CPDF_StreamContentParser::Handle_CloseFillStrokePath}, {FXBSTR_ID('b', '*', 0, 0), &CPDF_StreamContentParser::Handle_CloseEOFillStrokePath}, {FXBSTR_ID('c', 0, 0, 0), &CPDF_StreamContentParser::Handle_CurveTo_123}, {FXBSTR_ID('c', 'm', 0, 0), &CPDF_StreamContentParser::Handle_ConcatMatrix}, {FXBSTR_ID('c', 's', 0, 0), &CPDF_StreamContentParser::Handle_SetColorSpace_Fill}, {FXBSTR_ID('d', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetDash}, {FXBSTR_ID('d', '0', 0, 0), &CPDF_StreamContentParser::Handle_SetCharWidth}, {FXBSTR_ID('d', '1', 0, 0), &CPDF_StreamContentParser::Handle_SetCachedDevice}, {FXBSTR_ID('f', 0, 0, 0), &CPDF_StreamContentParser::Handle_FillPath}, {FXBSTR_ID('f', '*', 0, 0), &CPDF_StreamContentParser::Handle_EOFillPath}, {FXBSTR_ID('g', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetGray_Fill}, {FXBSTR_ID('g', 's', 0, 0), &CPDF_StreamContentParser::Handle_SetExtendGraphState}, {FXBSTR_ID('h', 0, 0, 0), &CPDF_StreamContentParser::Handle_ClosePath}, {FXBSTR_ID('i', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetFlat}, {FXBSTR_ID('j', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetLineJoin}, {FXBSTR_ID('k', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetCMYKColor_Fill}, {FXBSTR_ID('l', 0, 0, 0), &CPDF_StreamContentParser::Handle_LineTo}, {FXBSTR_ID('m', 0, 0, 0), &CPDF_StreamContentParser::Handle_MoveTo}, {FXBSTR_ID('n', 0, 0, 0), &CPDF_StreamContentParser::Handle_EndPath}, {FXBSTR_ID('q', 0, 0, 0), &CPDF_StreamContentParser::Handle_SaveGraphState}, {FXBSTR_ID('r', 'e', 0, 0), &CPDF_StreamContentParser::Handle_Rectangle}, {FXBSTR_ID('r', 'g', 0, 0), &CPDF_StreamContentParser::Handle_SetRGBColor_Fill}, {FXBSTR_ID('r', 'i', 0, 0), &CPDF_StreamContentParser::Handle_SetRenderIntent}, {FXBSTR_ID('s', 0, 0, 0), &CPDF_StreamContentParser::Handle_CloseStrokePath}, {FXBSTR_ID('s', 'c', 0, 0), &CPDF_StreamContentParser::Handle_SetColor_Fill}, {FXBSTR_ID('s', 'c', 'n', 0), &CPDF_StreamContentParser::Handle_SetColorPS_Fill}, {FXBSTR_ID('s', 'h', 0, 0), &CPDF_StreamContentParser::Handle_ShadeFill}, {FXBSTR_ID('v', 0, 0, 0), &CPDF_StreamContentParser::Handle_CurveTo_23}, {FXBSTR_ID('w', 0, 0, 0), &CPDF_StreamContentParser::Handle_SetLineWidth}, {FXBSTR_ID('y', 0, 0, 0), &CPDF_StreamContentParser::Handle_CurveTo_13}, }; FX_BOOL CPDF_StreamContentParser::OnOperator(FX_LPCSTR op) { int i = 0; FX_DWORD opid = 0; while (i < 4 && op[i]) { opid = (opid << 8) + op[i]; i ++; } while (i < 4) { opid <<= 8; i ++; }; int low = 0, high = sizeof g_OpCodes / sizeof(struct _OpCode) - 1; while (low <= high) { int middle = (low + high) / 2; int compare = opid - g_OpCodes[middle].m_OpId; if (compare == 0) { (this->*g_OpCodes[middle].m_OpHandler)(); return TRUE; } else if (compare < 0) { high = middle - 1; } else { low = middle + 1; } } return m_CompatCount != 0; } void CPDF_StreamContentParser::Handle_CloseFillStrokePath() { if (m_Options.m_bTextOnly) { return; } Handle_ClosePath(); AddPathObject(FXFILL_WINDING, TRUE); } void CPDF_StreamContentParser::Handle_FillStrokePath() { if (m_Options.m_bTextOnly) { return; } AddPathObject(FXFILL_WINDING, TRUE); } void CPDF_StreamContentParser::Handle_CloseEOFillStrokePath() { if (m_Options.m_bTextOnly) { return; } AddPathPoint(m_PathStartX, m_PathStartY, FXPT_LINETO | FXPT_CLOSEFIGURE); AddPathObject(FXFILL_ALTERNATE, TRUE); } void CPDF_StreamContentParser::Handle_EOFillStrokePath() { if (m_Options.m_bTextOnly) { return; } AddPathObject(FXFILL_ALTERNATE, TRUE); } void CPDF_StreamContentParser::Handle_BeginMarkedContent_Dictionary() { if (!m_Options.m_bMarkedContent) { return; } CFX_ByteString tag = GetString(1); CPDF_Object* pProperty = GetObject(0); if (pProperty == NULL) { return; } FX_BOOL bDirect = TRUE; if (pProperty->GetType() == PDFOBJ_NAME) { pProperty = FindResourceObj(FX_BSTRC("Properties"), pProperty->GetString()); if (pProperty == NULL) { return; } bDirect = FALSE; } if (pProperty->GetType() != PDFOBJ_DICTIONARY) { return; } m_CurContentMark.GetModify()->AddMark(tag, (CPDF_Dictionary*)pProperty, bDirect); } void CPDF_StreamContentParser::Handle_BeginMarkedContent() { if (!m_Options.m_bMarkedContent) { return; } CFX_ByteString tag = GetString(0); m_CurContentMark.GetModify()->AddMark(tag, NULL, FALSE); } struct _FX_BSTR { FX_LPCSTR m_Ptr; int m_Size; }; #define _FX_BSTRC(str) {str, sizeof(str)-1} const _FX_BSTR _PDF_InlineKeyAbbr[] = { _FX_BSTRC("BitsPerComponent"), _FX_BSTRC("BPC"), _FX_BSTRC("ColorSpace"), _FX_BSTRC("CS"), _FX_BSTRC("Decode"), _FX_BSTRC("D"), _FX_BSTRC("DecodeParms"), _FX_BSTRC("DP"), _FX_BSTRC("Filter"), _FX_BSTRC("F"), _FX_BSTRC("Height"), _FX_BSTRC("H"), _FX_BSTRC("ImageMask"), _FX_BSTRC("IM"), _FX_BSTRC("Interpolate"), _FX_BSTRC("I"), _FX_BSTRC("Width"), _FX_BSTRC("W"), }; const _FX_BSTR _PDF_InlineValueAbbr[] = { _FX_BSTRC("DeviceGray"), _FX_BSTRC("G"), _FX_BSTRC("DeviceRGB"), _FX_BSTRC("RGB"), _FX_BSTRC("DeviceCMYK"), _FX_BSTRC("CMYK"), _FX_BSTRC("Indexed"), _FX_BSTRC("I"), _FX_BSTRC("ASCIIHexDecode"), _FX_BSTRC("AHx"), _FX_BSTRC("ASCII85Decode"), _FX_BSTRC("A85"), _FX_BSTRC("LZWDecode"), _FX_BSTRC("LZW"), _FX_BSTRC("FlateDecode"), _FX_BSTRC("Fl"), _FX_BSTRC("RunLengthDecode"), _FX_BSTRC("RL"), _FX_BSTRC("CCITTFaxDecode"), _FX_BSTRC("CCF"), _FX_BSTRC("DCTDecode"), _FX_BSTRC("DCT"), }; static CFX_ByteStringC _PDF_FindFullName(const _FX_BSTR* table, int count, FX_BSTR abbr) { int i = 0; while (i < count) { if (abbr.GetLength() == table[i + 1].m_Size && FXSYS_memcmp32(abbr.GetPtr(), table[i + 1].m_Ptr, abbr.GetLength()) == 0) { return CFX_ByteStringC(table[i].m_Ptr, table[i].m_Size); } i += 2; } return CFX_ByteStringC(); } void _PDF_ReplaceAbbr(CPDF_Object* pObj) { switch (pObj->GetType()) { case PDFOBJ_DICTIONARY: { CPDF_Dictionary* pDict = (CPDF_Dictionary*)pObj; FX_POSITION pos = pDict->GetStartPos(); while (pos) { CFX_ByteString key; CPDF_Object* value = pDict->GetNextElement(pos, key); CFX_ByteStringC fullname = _PDF_FindFullName(_PDF_InlineKeyAbbr, sizeof _PDF_InlineKeyAbbr / sizeof(_FX_BSTR), key); if (!fullname.IsEmpty()) { pDict->ReplaceKey(key, fullname); key = fullname; } if (value->GetType() == PDFOBJ_NAME) { CFX_ByteString name = value->GetString(); fullname = _PDF_FindFullName(_PDF_InlineValueAbbr, sizeof _PDF_InlineValueAbbr / sizeof(_FX_BSTR), name); if (!fullname.IsEmpty()) { pDict->SetAtName(key, fullname); } } else { _PDF_ReplaceAbbr(value); } } break; } case PDFOBJ_ARRAY: { CPDF_Array* pArray = (CPDF_Array*)pObj; for (FX_DWORD i = 0; i < pArray->GetCount(); i ++) { CPDF_Object* pElement = pArray->GetElement(i); if (pElement->GetType() == PDFOBJ_NAME) { CFX_ByteString name = pElement->GetString(); CFX_ByteStringC fullname = _PDF_FindFullName(_PDF_InlineValueAbbr, sizeof _PDF_InlineValueAbbr / sizeof(_FX_BSTR), name); if (!fullname.IsEmpty()) { pArray->SetAt(i, CPDF_Name::Create(fullname)); } } else { _PDF_ReplaceAbbr(pElement); } } break; } } } static CFX_ByteStringC _PDF_FindAbbrName(const _FX_BSTR* table, int count, FX_BSTR fullName) { int i = 0; while (i < count) { if (fullName.GetLength() == table[i].m_Size && FXSYS_memcmp32(fullName.GetPtr(), table[i].m_Ptr, fullName.GetLength()) == 0) { return CFX_ByteStringC(table[i + 1].m_Ptr, table[i + 1].m_Size); } i += 2; } return CFX_ByteStringC(); } void _PDF_ReplaceFull(CPDF_Object* pObj) { switch (pObj->GetType()) { case PDFOBJ_DICTIONARY: { CPDF_Dictionary* pDict = (CPDF_Dictionary*)pObj; FX_POSITION pos = pDict->GetStartPos(); while (pos) { CFX_ByteString key; CPDF_Object* value = pDict->GetNextElement(pos, key); CFX_ByteStringC abbrName = _PDF_FindAbbrName(_PDF_InlineKeyAbbr, sizeof(_PDF_InlineKeyAbbr) / sizeof(_FX_BSTR), key); if (!abbrName.IsEmpty()) { pDict->ReplaceKey(key, abbrName); key = abbrName; } if (value->GetType() == PDFOBJ_NAME) { CFX_ByteString name = value->GetString(); abbrName = _PDF_FindAbbrName(_PDF_InlineValueAbbr, sizeof(_PDF_InlineValueAbbr) / sizeof(_FX_BSTR), name); if (!abbrName.IsEmpty()) { pDict->SetAtName(key, abbrName); } } else { _PDF_ReplaceFull(value); } } break; } case PDFOBJ_ARRAY: { CPDF_Array* pArray = (CPDF_Array*)pObj; for (FX_DWORD i = 0; i < pArray->GetCount(); i ++) { CPDF_Object* pElement = pArray->GetElement(i); if (pElement->GetType() == PDFOBJ_NAME) { CFX_ByteString name = pElement->GetString(); CFX_ByteStringC abbrName = _PDF_FindAbbrName(_PDF_InlineValueAbbr, sizeof _PDF_InlineValueAbbr / sizeof(_FX_BSTR), name); if (!abbrName.IsEmpty()) { pArray->SetAt(i, CPDF_Name::Create(abbrName)); } } else { _PDF_ReplaceFull(pElement); } } break; } } } void CPDF_StreamContentParser::Handle_BeginText() { m_pCurStates->m_TextMatrix.Set(1.0f, 0, 0, 1.0f, 0, 0); OnChangeTextMatrix(); m_pCurStates->m_TextX = 0; m_pCurStates->m_TextY = 0; m_pCurStates->m_TextLineX = 0; m_pCurStates->m_TextLineY = 0; } void CPDF_StreamContentParser::Handle_BeginSectionUndefined() { m_CompatCount ++; } void CPDF_StreamContentParser::Handle_CurveTo_123() { if (m_Options.m_bTextOnly) { return; } AddPathPoint(GetNumber(5), GetNumber(4), FXPT_BEZIERTO); AddPathPoint(GetNumber(3), GetNumber(2), FXPT_BEZIERTO); AddPathPoint(GetNumber(1), GetNumber(0), FXPT_BEZIERTO); } void CPDF_StreamContentParser::Handle_ConcatMatrix() { FX_FLOAT a2 = GetNumber16(5), b2 = GetNumber16(4), c2 = GetNumber16(3), d2 = GetNumber16(2); FX_FLOAT e2 = GetNumber(1), f2 = GetNumber(0); FX_FLOAT old_width_scale = m_pCurStates->m_CTM.GetXUnit(); CFX_AffineMatrix new_matrix(a2, b2, c2, d2, e2, f2); new_matrix.Concat(m_pCurStates->m_CTM); m_pCurStates->m_CTM = new_matrix; FX_FLOAT new_width_scale = m_pCurStates->m_CTM.GetXUnit(); OnChangeTextMatrix(); } void CPDF_StreamContentParser::Handle_SetColorSpace_Fill() { if (m_Options.m_bTextOnly) { return; } CFX_ByteString csname = GetString(0); CPDF_ColorSpace* pCS = FindColorSpace(csname); if (pCS == NULL) { return; } m_pCurStates->m_ColorState.GetModify()->m_FillColor.SetColorSpace(pCS); } void CPDF_StreamContentParser::Handle_SetColorSpace_Stroke() { if (m_Options.m_bTextOnly) { return; } CFX_ByteString csname = GetString(0); CPDF_ColorSpace* pCS = FindColorSpace(csname); if (pCS == NULL) { return; } m_pCurStates->m_ColorState.GetModify()->m_StrokeColor.SetColorSpace(pCS); } void CPDF_StreamContentParser::Handle_SetDash() { if (m_Options.m_bTextOnly) { return; } CPDF_Array* pArray = GetObject(1)->GetArray(); if (pArray == NULL) { return; } m_pCurStates->SetLineDash(pArray, GetNumber(0), 1.0f); } void CPDF_StreamContentParser::Handle_SetCharWidth() { m_Type3Data[0] = GetNumber(1); m_Type3Data[1] = GetNumber(0); m_bColored = TRUE; } void CPDF_StreamContentParser::Handle_SetCachedDevice() { for (int i = 0; i < 6; i ++) { m_Type3Data[i] = GetNumber(5 - i); } m_bColored = FALSE; } void CPDF_StreamContentParser::Handle_ExecuteXObject() { CFX_ByteString name = GetString(0); if (name == m_LastImageName && m_pLastImage && m_pLastImage->GetStream() && m_pLastImage->GetStream()->GetObjNum()) { #if defined(_FPDFAPI_MINI_) && !defined(_FXCORE_FEATURE_ALL_) AddDuplicateImage(); #else AddImage(NULL, m_pLastImage, FALSE); #endif return; } if (m_Options.m_bTextOnly) { CPDF_Object* pRes = NULL; if (m_pResources == NULL) { return; } if (m_pResources == m_pPageResources) { CPDF_Dictionary* pList = m_pResources->GetDict(FX_BSTRC("XObject")); if (pList == NULL) { return; } pRes = pList->GetElement(name); if (pRes == NULL || pRes->GetType() != PDFOBJ_REFERENCE) { return; } } else { CPDF_Dictionary* pList = m_pResources->GetDict(FX_BSTRC("XObject")); if (pList == NULL) { if (m_pPageResources == NULL) { return; } CPDF_Dictionary* pList = m_pPageResources->GetDict(FX_BSTRC("XObject")); if (pList == NULL) { return; } pRes = pList->GetElement(name); if (pRes == NULL || pRes->GetType() != PDFOBJ_REFERENCE) { return; } } else { pRes = pList->GetElement(name); if (pRes == NULL || pRes->GetType() != PDFOBJ_REFERENCE) { return; } } } FX_BOOL bForm; if (m_pDocument->IsFormStream(((CPDF_Reference*)pRes)->GetRefObjNum(), bForm) && !bForm) { return; } } CPDF_Stream* pXObject = (CPDF_Stream*)FindResourceObj(FX_BSTRC("XObject"), name); if (pXObject == NULL || pXObject->GetType() != PDFOBJ_STREAM) { m_bResourceMissing = TRUE; return; } CFX_ByteStringC type = pXObject->GetDict()->GetConstString(FX_BSTRC("Subtype")); if (type == FX_BSTRC("Image")) { if (m_Options.m_bTextOnly) { return; } CPDF_ImageObject* pObj = AddImage(pXObject, NULL, FALSE); m_LastImageName = name; m_pLastImage = pObj->m_pImage; } else if (type == FX_BSTRC("Form")) { AddForm(pXObject); } else { return; } } void CPDF_StreamContentParser::AddForm(CPDF_Stream* pStream) { #if !defined(_FPDFAPI_MINI_) || defined(_FXCORE_FEATURE_ALL_) if (!m_Options.m_bSeparateForm) { CPDF_Dictionary* pResources = pStream->GetDict()->GetDict(FX_BSTRC("Resources")); CFX_AffineMatrix form_matrix = pStream->GetDict()->GetMatrix(FX_BSTRC("Matrix")); form_matrix.Concat(m_pCurStates->m_CTM); CPDF_Array* pBBox = pStream->GetDict()->GetArray(FX_BSTRC("BBox")); CFX_FloatRect form_bbox; CPDF_Path ClipPath; if (pBBox) { form_bbox = pStream->GetDict()->GetRect(FX_BSTRC("BBox")); ClipPath.New(); ClipPath.AppendRect(form_bbox.left, form_bbox.bottom, form_bbox.right, form_bbox.top); ClipPath.Transform(&form_matrix); form_bbox.Transform(&form_matrix); } CPDF_StreamContentParser parser; parser.Initialize(); parser.PrepareParse(m_pDocument, m_pPageResources, m_pResources, &m_mtContentToUser, m_pObjectList, pResources, &form_bbox, &m_Options, m_pCurStates, m_Level + 1); parser.m_pCurStates->m_CTM = form_matrix; if (ClipPath.NotNull()) { parser.m_pCurStates->m_ClipPath.AppendPath(ClipPath, FXFILL_WINDING, TRUE); } CPDF_StreamAcc stream; stream.LoadAllData(pStream, FALSE); if (stream.GetSize() == 0) { return; } #ifdef _FPDFAPI_MINI_ parser.InputData(stream.GetData(), stream.GetSize()); parser.Finish(); #else parser.Parse(stream.GetData(), stream.GetSize(), 0); #endif return; } #endif CPDF_FormObject* pFormObj = FX_NEW CPDF_FormObject; pFormObj->m_pForm = FX_NEW CPDF_Form(m_pDocument, m_pPageResources, pStream, m_pResources); pFormObj->m_FormMatrix = m_pCurStates->m_CTM; pFormObj->m_FormMatrix.Concat(m_mtContentToUser); CPDF_AllStates status; status.m_GeneralState = m_pCurStates->m_GeneralState; status.m_GraphState = m_pCurStates->m_GraphState; status.m_ColorState = m_pCurStates->m_ColorState; status.m_TextState = m_pCurStates->m_TextState; pFormObj->m_pForm->ParseContent(&status, NULL, NULL, &m_Options, m_Level + 1); if (!m_pObjectList->m_bBackgroundAlphaNeeded && pFormObj->m_pForm->m_bBackgroundAlphaNeeded) { m_pObjectList->m_bBackgroundAlphaNeeded = TRUE; } pFormObj->CalcBoundingBox(); SetGraphicStates(pFormObj, TRUE, TRUE, TRUE); m_pObjectList->m_ObjectList.AddTail(pFormObj); } #if defined(_FPDFAPI_MINI_) && !defined(_FXCORE_FEATURE_ALL_) void CPDF_StreamContentParser::AddDuplicateImage() { FX_POSITION tailpos = m_pObjectList->m_ObjectList.GetTailPosition(); CPDF_PageObject* pLastObj = (CPDF_PageObject*)m_pObjectList->m_ObjectList.GetAt(tailpos); if (pLastObj == NULL || (pLastObj->m_Type != PDFPAGE_INLINES && pLastObj->m_Type != PDFPAGE_IMAGE)) { AddImage(NULL, m_pLastImage, FALSE); return; } if (pLastObj->m_GeneralState != m_pCurStates->m_GeneralState || pLastObj->m_ClipPath != m_pCurStates->m_ClipPath || pLastObj->m_ColorState != m_pCurStates->m_ColorState) { AddImage(NULL, m_pLastImage, FALSE); return; } CFX_AffineMatrix ImageMatrix; ImageMatrix.Copy(m_pCurStates->m_CTM); ImageMatrix.Concat(m_mtContentToUser); if (pLastObj->m_Type == PDFPAGE_INLINES) { CPDF_InlineImages* pInlines = (CPDF_InlineImages*)pLastObj; if (pInlines->m_pStream != m_pLastImage->GetStream()) { AddImage(NULL, m_pLastImage, FALSE); return; } pInlines->AddMatrix(ImageMatrix); } else { CPDF_ImageObject* pImageObj = (CPDF_ImageObject*)pLastObj; CPDF_InlineImages* pInlines = FX_NEW CPDF_InlineImages; pInlines->m_pStream = m_pLastImage->GetStream(); SetGraphicStates(pInlines, !pInlines->m_pStream->GetDict()->KeyExist(FX_BSTRC("ColorSpace")), FALSE, FALSE); pInlines->AddMatrix(pImageObj->m_Matrix); pInlines->AddMatrix(ImageMatrix); m_pObjectList->m_ObjectList.RemoveAt(tailpos); m_pObjectList->m_ObjectList.AddTail(pInlines); pLastObj->Release(); } } #endif CPDF_ImageObject* CPDF_StreamContentParser::AddImage(CPDF_Stream* pStream, CPDF_Image* pImage, FX_BOOL bInline) { if (pStream == NULL && pImage == NULL) { return NULL; } CFX_AffineMatrix ImageMatrix; ImageMatrix.Copy(m_pCurStates->m_CTM); ImageMatrix.Concat(m_mtContentToUser); CPDF_ImageObject* pImageObj = FX_NEW CPDF_ImageObject; if (pImage) { pImageObj->m_pImage = m_pDocument->GetPageData()->GetImage(pImage->GetStream()); } else if (pStream->GetObjNum()) { pImageObj->m_pImage = m_pDocument->LoadImageF(pStream); } else { pImageObj->m_pImage = FX_NEW CPDF_Image(m_pDocument); pImageObj->m_pImage->LoadImageF(pStream, bInline); } SetGraphicStates(pImageObj, pImageObj->m_pImage->IsMask(), FALSE, FALSE); pImageObj->m_Matrix = ImageMatrix; pImageObj->CalcBoundingBox(); m_pObjectList->m_ObjectList.AddTail(pImageObj); return pImageObj; } void CPDF_StreamContentParser::Handle_MarkPlace_Dictionary() { } void CPDF_StreamContentParser::Handle_EndImage() { } void CPDF_StreamContentParser::Handle_EndMarkedContent() { if (!m_Options.m_bMarkedContent) { return; } if (m_CurContentMark.IsNull()) { return; } int count = m_CurContentMark.GetObject()->CountItems(); if (count == 1) { m_CurContentMark.SetNull(); return; } m_CurContentMark.GetModify()->DeleteLastMark(); } void CPDF_StreamContentParser::Handle_EndText() { int count = m_ClipTextList.GetSize(); if (count == 0) { return; } if (m_pCurStates->m_TextState.GetObject()->m_TextMode < 4) { for (int i = 0; i < count; i ++) { CPDF_TextObject* pText = (CPDF_TextObject*)m_ClipTextList.GetAt(i); if (pText) { delete pText; } } } else { m_pCurStates->m_ClipPath.AppendTexts((CPDF_TextObject**)m_ClipTextList.GetData(), count); } m_ClipTextList.RemoveAll(); } void CPDF_StreamContentParser::Handle_EndSectionUndefined() { if (m_CompatCount) { m_CompatCount --; } } void CPDF_StreamContentParser::Handle_FillPath() { if (m_Options.m_bTextOnly) { return; } AddPathObject(FXFILL_WINDING, FALSE); } void CPDF_StreamContentParser::Handle_FillPathOld() { if (m_Options.m_bTextOnly) { return; } AddPathObject(FXFILL_WINDING, FALSE); } void CPDF_StreamContentParser::Handle_EOFillPath() { if (m_Options.m_bTextOnly) { return; } AddPathObject(FXFILL_ALTERNATE, FALSE); } void CPDF_StreamContentParser::Handle_SetGray_Fill() { FX_FLOAT value = GetNumber(0); CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICEGRAY); m_pCurStates->m_ColorState.SetFillColor(pCS, &value, 1); } void CPDF_StreamContentParser::Handle_SetGray_Stroke() { FX_FLOAT value = GetNumber(0); CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICEGRAY); m_pCurStates->m_ColorState.SetStrokeColor(pCS, &value, 1); } void CPDF_StreamContentParser::Handle_SetExtendGraphState() { CFX_ByteString name = GetString(0); CPDF_Dictionary* pGS = (CPDF_Dictionary*)FindResourceObj(FX_BSTRC("ExtGState"), name); if (pGS == NULL || pGS->GetType() != PDFOBJ_DICTIONARY) { m_bResourceMissing = TRUE; return; } m_pCurStates->ProcessExtGS(pGS, this); } void CPDF_StreamContentParser::Handle_ClosePath() { if (m_Options.m_bTextOnly) { return; } if (m_PathPointCount == 0) { return; } if (m_PathStartX != m_PathCurrentX || m_PathStartY != m_PathCurrentY) { AddPathPoint(m_PathStartX, m_PathStartY, FXPT_LINETO | FXPT_CLOSEFIGURE); } else if (m_pPathPoints[m_PathPointCount - 1].m_Flag != FXPT_MOVETO) { m_pPathPoints[m_PathPointCount - 1].m_Flag |= FXPT_CLOSEFIGURE; } } void CPDF_StreamContentParser::Handle_SetFlat() { #if !defined(_FPDFAPI_MINI_) || defined(_FXCORE_FEATURE_ALL_) m_pCurStates->m_GeneralState.GetModify()->m_Flatness = GetNumber(0); #endif } void CPDF_StreamContentParser::Handle_BeginImageData() { } void CPDF_StreamContentParser::Handle_SetLineJoin() { m_pCurStates->m_GraphState.GetModify()->m_LineJoin = (CFX_GraphStateData::LineJoin)GetInteger(0); } void CPDF_StreamContentParser::Handle_SetLineCap() { m_pCurStates->m_GraphState.GetModify()->m_LineCap = (CFX_GraphStateData::LineCap)GetInteger(0); } void CPDF_StreamContentParser::Handle_SetCMYKColor_Fill() { REQUIRE_PARAMS(4); FX_FLOAT values[4]; for (int i = 0; i < 4; i ++) { values[i] = GetNumber(3 - i); } CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICECMYK); m_pCurStates->m_ColorState.SetFillColor(pCS, values, 4); } void CPDF_StreamContentParser::Handle_SetCMYKColor_Stroke() { REQUIRE_PARAMS(4); FX_FLOAT values[4]; for (int i = 0; i < 4; i ++) { values[i] = GetNumber(3 - i); } CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICECMYK); m_pCurStates->m_ColorState.SetStrokeColor(pCS, values, 4); } void CPDF_StreamContentParser::Handle_LineTo() { REQUIRE_PARAMS(2); if (m_Options.m_bTextOnly) { return; } AddPathPoint(GetNumber(1), GetNumber(0), FXPT_LINETO); } void CPDF_StreamContentParser::Handle_MoveTo() { REQUIRE_PARAMS(2); if (m_Options.m_bTextOnly) { #ifndef _FPDFAPI_MINI_ m_pSyntax->SkipPathObject(); #endif return; } AddPathPoint(GetNumber(1), GetNumber(0), FXPT_MOVETO); #ifndef _FPDFAPI_MINI_ ParsePathObject(); #endif } void CPDF_StreamContentParser::Handle_SetMiterLimit() { m_pCurStates->m_GraphState.GetModify()->m_MiterLimit = GetNumber(0); } void CPDF_StreamContentParser::Handle_MarkPlace() { } void CPDF_StreamContentParser::Handle_EndPath() { if (m_Options.m_bTextOnly) { return; } AddPathObject(0, FALSE); } void CPDF_StreamContentParser::Handle_SaveGraphState() { CPDF_AllStates* pStates = FX_NEW CPDF_AllStates; pStates->Copy(*m_pCurStates); m_StateStack.Add(pStates); } void CPDF_StreamContentParser::Handle_RestoreGraphState() { int size = m_StateStack.GetSize(); if (size == 0) { return; } CPDF_AllStates* pStates = (CPDF_AllStates*)m_StateStack.GetAt(size - 1); m_pCurStates->Copy(*pStates); delete pStates; m_StateStack.RemoveAt(size - 1); } void CPDF_StreamContentParser::Handle_Rectangle() { if (m_Options.m_bTextOnly) { return; } FX_FLOAT x = GetNumber(3), y = GetNumber(2); FX_FLOAT w = GetNumber(1), h = GetNumber(0); AddPathRect(x, y, w, h); } void CPDF_StreamContentParser::AddPathRect(FX_FLOAT x, FX_FLOAT y, FX_FLOAT w, FX_FLOAT h) { AddPathPoint(x, y, FXPT_MOVETO); AddPathPoint(x + w, y, FXPT_LINETO); AddPathPoint(x + w, y + h, FXPT_LINETO); AddPathPoint(x, y + h, FXPT_LINETO); AddPathPoint(x, y, FXPT_LINETO | FXPT_CLOSEFIGURE); } void CPDF_StreamContentParser::Handle_SetRGBColor_Fill() { REQUIRE_PARAMS(3); FX_FLOAT values[3]; for (int i = 0; i < 3; i ++) { values[i] = GetNumber(2 - i); } CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICERGB); m_pCurStates->m_ColorState.SetFillColor(pCS, values, 3); } void CPDF_StreamContentParser::Handle_SetRGBColor_Stroke() { REQUIRE_PARAMS(3); FX_FLOAT values[3]; for (int i = 0; i < 3; i ++) { values[i] = GetNumber(2 - i); } CPDF_ColorSpace* pCS = CPDF_ColorSpace::GetStockCS(PDFCS_DEVICERGB); m_pCurStates->m_ColorState.SetStrokeColor(pCS, values, 3); } void CPDF_StreamContentParser::Handle_SetRenderIntent() { } void CPDF_StreamContentParser::Handle_CloseStrokePath() { if (m_Options.m_bTextOnly) { return; } Handle_ClosePath(); AddPathObject(0, TRUE); } void CPDF_StreamContentParser::Handle_StrokePath() { if (m_Options.m_bTextOnly) { return; } AddPathObject(0, TRUE); } void CPDF_StreamContentParser::Handle_SetColor_Fill() { if (m_Options.m_bTextOnly) { return; } FX_FLOAT values[4]; int nargs = m_ParamCount; if (nargs > 4) { nargs = 4; } for (int i = 0; i < nargs; i ++) { values[i] = GetNumber(nargs - i - 1); } m_pCurStates->m_ColorState.SetFillColor(NULL, values, nargs); } void CPDF_StreamContentParser::Handle_SetColor_Stroke() { if (m_Options.m_bTextOnly) { return; } FX_FLOAT values[4]; int nargs = m_ParamCount; if (nargs > 4) { nargs = 4; } for (int i = 0; i < nargs; i ++) { values[i] = GetNumber(nargs - i - 1); } m_pCurStates->m_ColorState.SetStrokeColor(NULL, values, nargs); } void CPDF_StreamContentParser::Handle_SetColorPS_Fill() { if (m_Options.m_bTextOnly) { return; } CPDF_Object* pLastParam = GetObject(0); if (pLastParam == NULL) { return; } int nargs = m_ParamCount; int nvalues = nargs; if (pLastParam->GetType() == PDFOBJ_NAME) { nvalues --; } FX_FLOAT* values = NULL; if (nvalues) { values = FX_Alloc(FX_FLOAT, nvalues); for (int i = 0; i < nvalues; i ++) { values[i] = GetNumber(nargs - i - 1); } } if (nvalues != nargs) { CPDF_Pattern* pPattern = FindPattern(GetString(0), FALSE); if (pPattern) { m_pCurStates->m_ColorState.SetFillPattern(pPattern, values, nvalues); } } else { m_pCurStates->m_ColorState.SetFillColor(NULL, values, nvalues); } if (values) { FX_Free(values); } } void CPDF_StreamContentParser::Handle_SetColorPS_Stroke() { if (m_Options.m_bTextOnly) { return; } CPDF_Object* pLastParam = GetObject(0); if (pLastParam == NULL) { return; } int nargs = m_ParamCount; int nvalues = nargs; if (pLastParam->GetType() == PDFOBJ_NAME) { nvalues --; } FX_FLOAT* values = NULL; if (nvalues) { values = FX_Alloc(FX_FLOAT, nvalues); for (int i = 0; i < nvalues; i ++) { values[i] = GetNumber(nargs - i - 1); } } if (nvalues != nargs) { CPDF_Pattern* pPattern = FindPattern(GetString(0), FALSE); if (pPattern) { m_pCurStates->m_ColorState.SetStrokePattern(pPattern, values, nvalues); } } else { m_pCurStates->m_ColorState.SetStrokeColor(NULL, values, nvalues); } if (values) { FX_Free(values); } } CFX_FloatRect _GetShadingBBox(CPDF_Stream* pStream, int type, const CFX_AffineMatrix* pMatrix, CPDF_Function** pFuncs, int nFuncs, CPDF_ColorSpace* pCS); void CPDF_StreamContentParser::Handle_ShadeFill() { if (m_Options.m_bTextOnly) { return; } CPDF_Pattern* pPattern = FindPattern(GetString(0), TRUE); if (pPattern == NULL) { return; } if (pPattern->m_PatternType != PATTERN_SHADING) { return; } CPDF_ShadingPattern* pShading = (CPDF_ShadingPattern*)pPattern; if (!pShading->m_bShadingObj) { return; } if (!pShading->Load()) { return; } CPDF_ShadingObject* pObj = FX_NEW CPDF_ShadingObject; pObj->m_pShading = pShading; SetGraphicStates(pObj, FALSE, FALSE, FALSE); pObj->m_Matrix = m_pCurStates->m_CTM; pObj->m_Matrix.Concat(m_mtContentToUser); CFX_FloatRect bbox; if (!pObj->m_ClipPath.IsNull()) { bbox = pObj->m_ClipPath.GetClipBox(); } else { bbox = m_BBox; } if (pShading->m_ShadingType >= 4) { bbox.Intersect(_GetShadingBBox((CPDF_Stream*)pShading->m_pShadingObj, pShading->m_ShadingType, &pObj->m_Matrix, pShading->m_pFunctions, pShading->m_nFuncs, pShading->m_pCS)); } pObj->m_Left = bbox.left; pObj->m_Right = bbox.right; pObj->m_Top = bbox.top; pObj->m_Bottom = bbox.bottom; m_pObjectList->m_ObjectList.AddTail(pObj); } void CPDF_StreamContentParser::Handle_SetCharSpace() { m_pCurStates->m_TextState.GetModify()->m_CharSpace = GetNumber(0); } void CPDF_StreamContentParser::Handle_MoveTextPoint() { m_pCurStates->m_TextLineX += GetNumber(1); m_pCurStates->m_TextLineY += GetNumber(0); m_pCurStates->m_TextX = m_pCurStates->m_TextLineX; m_pCurStates->m_TextY = m_pCurStates->m_TextLineY; } void CPDF_StreamContentParser::Handle_MoveTextPoint_SetLeading() { Handle_MoveTextPoint(); m_pCurStates->m_TextLeading = -GetNumber(0); } void CPDF_StreamContentParser::Handle_SetFont() { FX_FLOAT fs = GetNumber(0); if (fs == 0) { fs = m_DefFontSize; } m_pCurStates->m_TextState.GetModify()->m_FontSize = fs; CPDF_Font* pFont = FindFont(GetString(1)); if (pFont) { m_pCurStates->m_TextState.SetFont(pFont); } } CPDF_Object* CPDF_StreamContentParser::FindResourceObj(FX_BSTR type, const CFX_ByteString& name) { if (m_pResources == NULL) { return NULL; } if (m_pResources == m_pPageResources) { CPDF_Dictionary* pList = m_pResources->GetDict(type); if (pList == NULL) { return NULL; } CPDF_Object* pRes = pList->GetElementValue(name); return pRes; } CPDF_Dictionary* pList = m_pResources->GetDict(type); if (pList == NULL) { if (m_pPageResources == NULL) { return NULL; } CPDF_Dictionary* pList = m_pPageResources->GetDict(type); if (pList == NULL) { return NULL; } CPDF_Object* pRes = pList->GetElementValue(name); return pRes; } CPDF_Object* pRes = pList->GetElementValue(name); return pRes; } CPDF_Font* CPDF_StreamContentParser::FindFont(const CFX_ByteString& name) { CPDF_Dictionary* pFontDict = (CPDF_Dictionary*)FindResourceObj(FX_BSTRC("Font"), name); if (pFontDict == NULL || pFontDict->GetType() != PDFOBJ_DICTIONARY) { m_bResourceMissing = TRUE; return CPDF_Font::GetStockFont(m_pDocument, FX_BSTRC("Helvetica")); } CPDF_Font* pFont = m_pDocument->LoadFont(pFontDict); if (pFont && pFont->GetType3Font()) { pFont->GetType3Font()->SetPageResources(m_pResources); pFont->GetType3Font()->CheckType3FontMetrics(); } return pFont; } CPDF_ColorSpace* CPDF_StreamContentParser::FindColorSpace(const CFX_ByteString& name) { if (name == FX_BSTRC("Pattern")) { return CPDF_ColorSpace::GetStockCS(PDFCS_PATTERN); } if (name == FX_BSTRC("DeviceGray") || name == FX_BSTRC("DeviceCMYK") || name == FX_BSTRC("DeviceRGB")) { CFX_ByteString defname = "Default"; defname += name.Mid(7); CPDF_Object* pDefObj = FindResourceObj(FX_BSTRC("ColorSpace"), defname); if (pDefObj == NULL) { if (name == FX_BSTRC("DeviceGray")) { return CPDF_ColorSpace::GetStockCS(PDFCS_DEVICEGRAY); } if (name == FX_BSTRC("DeviceRGB")) { return CPDF_ColorSpace::GetStockCS(PDFCS_DEVICERGB); } return CPDF_ColorSpace::GetStockCS(PDFCS_DEVICECMYK); } return m_pDocument->LoadColorSpace(pDefObj); } CPDF_Object* pCSObj = FindResourceObj(FX_BSTRC("ColorSpace"), name); if (pCSObj == NULL) { m_bResourceMissing = TRUE; return NULL; } return m_pDocument->LoadColorSpace(pCSObj); } CPDF_Pattern* CPDF_StreamContentParser::FindPattern(const CFX_ByteString& name, FX_BOOL bShading) { CPDF_Object* pPattern = FindResourceObj(bShading ? FX_BSTRC("Shading") : FX_BSTRC("Pattern"), name); if (pPattern == NULL || (pPattern->GetType() != PDFOBJ_DICTIONARY && pPattern->GetType() != PDFOBJ_STREAM)) { m_bResourceMissing = TRUE; return NULL; } return m_pDocument->LoadPattern(pPattern, bShading, &m_pCurStates->m_ParentMatrix); } void CPDF_StreamContentParser::ConvertTextSpace(FX_FLOAT& x, FX_FLOAT& y) { m_pCurStates->m_TextMatrix.Transform(x, y, x, y); ConvertUserSpace(x, y); } void CPDF_StreamContentParser::ConvertUserSpace(FX_FLOAT& x, FX_FLOAT& y) { m_pCurStates->m_CTM.Transform(x, y, x, y); m_mtContentToUser.Transform(x, y, x, y); } void CPDF_StreamContentParser::AddTextObject(CFX_ByteString* pStrs, FX_FLOAT fInitKerning, FX_FLOAT* pKerning, int nsegs) { CPDF_Font* pFont = m_pCurStates->m_TextState.GetFont(); if (pFont == NULL) { return; } if (fInitKerning != 0) { if (!pFont->IsVertWriting()) { m_pCurStates->m_TextX -= FXSYS_Mul(fInitKerning, m_pCurStates->m_TextState.GetFontSize()) / 1000; } else { m_pCurStates->m_TextY -= FXSYS_Mul(fInitKerning, m_pCurStates->m_TextState.GetFontSize()) / 1000; } } if (nsegs == 0) { return; } int textmode; if (pFont->GetFontType() == PDFFONT_TYPE3) { textmode = 0; } else { textmode = m_pCurStates->m_TextState.GetObject()->m_TextMode; } CPDF_TextObject* pText = FX_NEW CPDF_TextObject; m_pLastTextObject = pText; SetGraphicStates(pText, TRUE, TRUE, TRUE); if (textmode && textmode != 3 && textmode != 4 && textmode != 7) { FX_FLOAT* pCTM = pText->m_TextState.GetModify()->m_CTM; pCTM[0] = m_pCurStates->m_CTM.a; pCTM[1] = m_pCurStates->m_CTM.c; pCTM[2] = m_pCurStates->m_CTM.b; pCTM[3] = m_pCurStates->m_CTM.d; } pText->SetSegments(pStrs, pKerning, nsegs); pText->m_PosX = m_pCurStates->m_TextX; pText->m_PosY = m_pCurStates->m_TextY + m_pCurStates->m_TextRise; ConvertTextSpace(pText->m_PosX, pText->m_PosY); FX_FLOAT x_advance, y_advance; pText->CalcPositionData(&x_advance, &y_advance, m_pCurStates->m_TextHorzScale, m_Level); m_pCurStates->m_TextX += x_advance; m_pCurStates->m_TextY += y_advance; if (textmode > 3) { CPDF_TextObject* pCopy = FX_NEW CPDF_TextObject; pCopy->Copy(pText); m_ClipTextList.Add(pCopy); } m_pObjectList->m_ObjectList.AddTail(pText); if (pKerning && pKerning[nsegs - 1] != 0) { if (!pFont->IsVertWriting()) { m_pCurStates->m_TextX -= FXSYS_Mul(pKerning[nsegs - 1], m_pCurStates->m_TextState.GetFontSize()) / 1000; } else { m_pCurStates->m_TextY -= FXSYS_Mul(pKerning[nsegs - 1], m_pCurStates->m_TextState.GetFontSize()) / 1000; } } } void CPDF_StreamContentParser::Handle_ShowText() { CFX_ByteString str = GetString(0); if (str.IsEmpty()) { return; } AddTextObject(&str, 0, NULL, 1); } void CPDF_StreamContentParser::Handle_ShowText_Positioning() { CPDF_Array* pArray = GetObject(0)->GetArray(); if (pArray == NULL) { return; } int n = pArray->GetCount(), nsegs = 0, i; for (i = 0; i < n; i ++) { CPDF_Object* pObj = pArray->GetElementValue(i); if (pObj->GetType() == PDFOBJ_STRING) { nsegs ++; } } if (nsegs == 0) { for (i = 0; i < n; i ++) { m_pCurStates->m_TextX -= FXSYS_Mul(pArray->GetNumber(i), m_pCurStates->m_TextState.GetFontSize()) / 1000; }; return; } CFX_ByteString* pStrs; FX_NEW_VECTOR(pStrs, CFX_ByteString, nsegs); FX_FLOAT* pKerning = FX_Alloc(FX_FLOAT, nsegs); int iSegment = 0; FX_FLOAT fInitKerning = 0; for (i = 0; i < n; i ++) { CPDF_Object* pObj = pArray->GetElementValue(i); if (pObj->GetType() == PDFOBJ_STRING) { CFX_ByteString str = pObj->GetString(); if (str.IsEmpty()) { continue; } pStrs[iSegment] = str; pKerning[iSegment ++] = 0; } else { if (iSegment == 0) { fInitKerning += pObj->GetNumber(); } else { pKerning[iSegment - 1] += pObj->GetNumber(); } } } AddTextObject(pStrs, fInitKerning, pKerning, iSegment); FX_DELETE_VECTOR(pStrs, CFX_ByteString, nsegs); FX_Free(pKerning); } void CPDF_StreamContentParser::Handle_SetTextLeading() { m_pCurStates->m_TextLeading = GetNumber(0); } void CPDF_StreamContentParser::Handle_SetTextMatrix() { m_pCurStates->m_TextMatrix.Set(GetNumber16(5), GetNumber16(4), GetNumber16(3), GetNumber16(2), GetNumber(1), GetNumber(0)); OnChangeTextMatrix(); m_pCurStates->m_TextX = 0; m_pCurStates->m_TextY = 0; m_pCurStates->m_TextLineX = 0; m_pCurStates->m_TextLineY = 0; } void CPDF_StreamContentParser::OnChangeTextMatrix() { CFX_AffineMatrix text_matrix(m_pCurStates->m_TextHorzScale, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f); text_matrix.Concat(m_pCurStates->m_TextMatrix); text_matrix.Concat(m_pCurStates->m_CTM); text_matrix.Concat(m_mtContentToUser); FX_FLOAT* pTextMatrix = m_pCurStates->m_TextState.GetModify()->m_Matrix; pTextMatrix[0] = text_matrix.a; pTextMatrix[1] = text_matrix.c; pTextMatrix[2] = text_matrix.b; pTextMatrix[3] = text_matrix.d; } void CPDF_StreamContentParser::Handle_SetTextRenderMode() { int mode = GetInteger(0); if (mode < 0 || mode > 7) { return; } m_pCurStates->m_TextState.GetModify()->m_TextMode = mode; } void CPDF_StreamContentParser::Handle_SetTextRise() { m_pCurStates->m_TextRise = GetNumber(0); } void CPDF_StreamContentParser::Handle_SetWordSpace() { m_pCurStates->m_TextState.GetModify()->m_WordSpace = GetNumber(0); } void CPDF_StreamContentParser::Handle_SetHorzScale() { if (m_ParamCount != 1) { return; } m_pCurStates->m_TextHorzScale = GetNumber(0) / 100; OnChangeTextMatrix(); } void CPDF_StreamContentParser::Handle_MoveToNextLine() { m_pCurStates->m_TextLineY -= m_pCurStates->m_TextLeading; m_pCurStates->m_TextX = m_pCurStates->m_TextLineX; m_pCurStates->m_TextY = m_pCurStates->m_TextLineY; } void CPDF_StreamContentParser::Handle_CurveTo_23() { if (m_Options.m_bTextOnly) { return; } AddPathPoint(m_PathCurrentX, m_PathCurrentY, FXPT_BEZIERTO); AddPathPoint(GetNumber(3), GetNumber(2), FXPT_BEZIERTO); AddPathPoint(GetNumber(1), GetNumber(0), FXPT_BEZIERTO); } void CPDF_StreamContentParser::Handle_SetLineWidth() { FX_FLOAT width = GetNumber(0); m_pCurStates->m_GraphState.GetModify()->m_LineWidth = width; } void CPDF_StreamContentParser::Handle_Clip() { m_PathClipType = FXFILL_WINDING; } void CPDF_StreamContentParser::Handle_EOClip() { m_PathClipType = FXFILL_ALTERNATE; } void CPDF_StreamContentParser::Handle_CurveTo_13() { if (m_Options.m_bTextOnly) { return; } AddPathPoint(GetNumber(3), GetNumber(2), FXPT_BEZIERTO); AddPathPoint(GetNumber(1), GetNumber(0), FXPT_BEZIERTO); AddPathPoint(GetNumber(1), GetNumber(0), FXPT_BEZIERTO); } void CPDF_StreamContentParser::Handle_NextLineShowText() { Handle_MoveToNextLine(); Handle_ShowText(); } void CPDF_StreamContentParser::Handle_NextLineShowText_Space() { m_pCurStates->m_TextState.GetModify()->m_WordSpace = GetNumber(2); m_pCurStates->m_TextState.GetModify()->m_CharSpace = GetNumber(1); Handle_NextLineShowText(); } void CPDF_StreamContentParser::Handle_Invalid() { } void CPDF_StreamContentParser::AddPathPoint(FX_FLOAT x, FX_FLOAT y, int flag) { m_PathCurrentX = x; m_PathCurrentY = y; if (flag == FXPT_MOVETO) { m_PathStartX = x; m_PathStartY = y; if (m_PathPointCount && m_pPathPoints[m_PathPointCount - 1].m_Flag == FXPT_MOVETO) { m_pPathPoints[m_PathPointCount - 1].m_PointX = x; m_pPathPoints[m_PathPointCount - 1].m_PointY = y; return; } } else if (m_PathPointCount == 0) { return; } m_PathPointCount ++; if (m_PathPointCount > m_PathAllocSize) { int newsize = m_PathPointCount + 256; FX_PATHPOINT* pNewPoints = FX_Alloc(FX_PATHPOINT, newsize); if (m_PathAllocSize) { FXSYS_memcpy32(pNewPoints, m_pPathPoints, m_PathAllocSize * sizeof(FX_PATHPOINT)); FX_Free(m_pPathPoints); } m_pPathPoints = pNewPoints; m_PathAllocSize = newsize; } m_pPathPoints[m_PathPointCount - 1].m_Flag = flag; m_pPathPoints[m_PathPointCount - 1].m_PointX = x; m_pPathPoints[m_PathPointCount - 1].m_PointY = y; } void CPDF_StreamContentParser::AddPathObject(int FillType, FX_BOOL bStroke) { int PathPointCount = m_PathPointCount, PathClipType = m_PathClipType; m_PathPointCount = 0; m_PathClipType = 0; if (PathPointCount <= 1) { if (PathPointCount && PathClipType) { CPDF_Path path; path.New()->AppendRect(0, 0, 0, 0); m_pCurStates->m_ClipPath.AppendPath(path, FXFILL_WINDING, TRUE); } return; } if (PathPointCount && m_pPathPoints[PathPointCount - 1].m_Flag == FXPT_MOVETO) { PathPointCount --; } CPDF_Path Path; CFX_PathData* pPathData = Path.New(); pPathData->SetPointCount(PathPointCount); FXSYS_memcpy32(pPathData->GetPoints(), m_pPathPoints, sizeof(FX_PATHPOINT) * PathPointCount); CFX_AffineMatrix matrix = m_pCurStates->m_CTM; matrix.Concat(m_mtContentToUser); if (bStroke || FillType) { CPDF_PathObject* pPathObj = FX_NEW CPDF_PathObject; pPathObj->m_bStroke = bStroke; pPathObj->m_FillType = FillType; pPathObj->m_Path = Path; pPathObj->m_Matrix = matrix; SetGraphicStates(pPathObj, TRUE, FALSE, TRUE); pPathObj->CalcBoundingBox(); m_pObjectList->m_ObjectList.AddTail(pPathObj); } if (PathClipType) { if (!matrix.IsIdentity()) { Path.Transform(&matrix); matrix.SetIdentity(); } m_pCurStates->m_ClipPath.AppendPath(Path, PathClipType, TRUE); } } CFX_ByteString _FPDF_ByteStringFromHex(CFX_BinaryBuf& src_buf) { CFX_ByteTextBuf buf; FX_BOOL bFirst = TRUE; int code = 0; FX_LPCBYTE str = src_buf.GetBuffer(); FX_DWORD size = src_buf.GetSize(); for (FX_DWORD i = 0; i < size; i ++) { FX_BYTE ch = str[i]; if (ch >= '0' && ch <= '9') { if (bFirst) { code = (ch - '0') * 16; } else { code += ch - '0'; buf.AppendChar((char)code); } bFirst = !bFirst; } else if (ch >= 'A' && ch <= 'F') { if (bFirst) { code = (ch - 'A' + 10) * 16; } else { code += ch - 'A' + 10; buf.AppendChar((char)code); } bFirst = !bFirst; } else if (ch >= 'a' && ch <= 'f') { if (bFirst) { code = (ch - 'a' + 10) * 16; } else { code += ch - 'a' + 10; buf.AppendChar((char)code); } bFirst = !bFirst; } } if (!bFirst) { buf.AppendChar((char)code); } return buf.GetByteString(); }
/* * Copyright 2020 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/sksl/dsl/DSLVar.h" #include "src/sksl/SkSLUtil.h" #include "src/sksl/dsl/DSLModifiers.h" #include "src/sksl/dsl/DSLType.h" #include "src/sksl/dsl/priv/DSLWriter.h" #include "src/sksl/ir/SkSLBinaryExpression.h" #include "src/sksl/ir/SkSLSymbolTable.h" #include "src/sksl/ir/SkSLVariable.h" #include "src/sksl/ir/SkSLVariableReference.h" namespace SkSL { namespace dsl { DSLVar::DSLVar(const char* name) : fName(name) { const SkSL::Symbol* result = (*DSLWriter::SymbolTable())[fName]; SkASSERTF(result, "could not find '%s' in symbol table", fName); fVar = &result->as<SkSL::Variable>(); } DSLVar::DSLVar(DSLType type, const char* name) : DSLVar(DSLModifiers(), std::move(type), name) {} DSLVar::DSLVar(DSLModifiers modifiers, DSLType type, const char* name) : fName(DSLWriter::Name(name)) { Variable::Storage storage = Variable::Storage::kLocal; #if SK_SUPPORT_GPU && !defined(SKSL_STANDALONE) if (modifiers.fModifiers.fFlags & Modifiers::kUniform_Flag) { storage = Variable::Storage::kGlobal; if (DSLWriter::InFragmentProcessor()) { const SkSL::Type& skslType = type.skslType(); GrSLType grslType; int count; if (skslType.isArray()) { SkAssertResult(SkSL::type_to_grsltype(DSLWriter::Context(), skslType.componentType(), &grslType)); count = skslType.columns(); SkASSERT(count > 0); } else { SkAssertResult(SkSL::type_to_grsltype(DSLWriter::Context(), skslType, &grslType)); count = 0; } const char* name; SkASSERT(DSLWriter::CurrentEmitArgs()); fUniformHandle = DSLWriter::CurrentEmitArgs()->fUniformHandler->addUniformArray( &DSLWriter::CurrentEmitArgs()->fFp, kFragment_GrShaderFlag, grslType, this->name(), count, &name); fName = name; } } #endif // SK_SUPPORT_GPU && !defined(SKSL_STANDALONE) DSLWriter::IRGenerator().checkVarDeclaration(/*offset=*/-1, modifiers.fModifiers, &type.skslType(), storage); fDeclaration = DSLWriter::IRGenerator().convertVarDeclaration(/*offset=*/-1, modifiers.fModifiers, &type.skslType(), fName, /*isArray=*/false, /*arraySize=*/nullptr, /*value=*/nullptr, storage); fVar = &fDeclaration->as<SkSL::VarDeclaration>().var(); } #if !defined(SKSL_STANDALONE) && SK_SUPPORT_GPU GrGLSLUniformHandler::UniformHandle DSLVar::uniformHandle() const { SkASSERT(fVar->modifiers().fFlags & SkSL::Modifiers::kUniform_Flag); return fUniformHandle; } #endif DSLExpression DSLVar::operator[](DSLExpression&& index) { return DSLExpression(*this)[std::move(index)]; } DSLExpression DSLVar::operator=(DSLExpression expr) { return DSLWriter::ConvertBinary(DSLExpression(*this).release(), SkSL::Token::Kind::TK_EQ, expr.release()); } } // namespace dsl } // namespace SkSL
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// // Copyright (c) 2017-19, Lawrence Livermore National Security, LLC // and RAJA Performance Suite project contributors. // See the RAJAPerf/COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// #include "POLYBENCH_JACOBI_2D.hpp" #include "RAJA/RAJA.hpp" #include <iostream> namespace rajaperf { namespace polybench { void POLYBENCH_JACOBI_2D::runSeqVariant(VariantID vid) { const Index_type run_reps= getRunReps(); POLYBENCH_JACOBI_2D_DATA_SETUP; auto poly_jacobi2d_base_lam1 = [=](Index_type i, Index_type j) { POLYBENCH_JACOBI_2D_BODY1; }; auto poly_jacobi2d_base_lam2 = [=](Index_type i, Index_type j) { POLYBENCH_JACOBI_2D_BODY2; }; POLYBENCH_JACOBI_2D_VIEWS_RAJA; auto poly_jacobi2d_lam1 = [=](Index_type i, Index_type j) { POLYBENCH_JACOBI_2D_BODY1_RAJA; }; auto poly_jacobi2d_lam2 = [=](Index_type i, Index_type j) { POLYBENCH_JACOBI_2D_BODY2_RAJA; }; switch ( vid ) { case Base_Seq : { startTimer(); for (RepIndex_type irep = 0; irep < run_reps; ++irep) { for (Index_type t = 0; t < tsteps; ++t) { for (Index_type i = 1; i < N-1; ++i ) { for (Index_type j = 1; j < N-1; ++j ) { POLYBENCH_JACOBI_2D_BODY1; } } for (Index_type i = 1; i < N-1; ++i ) { for (Index_type j = 1; j < N-1; ++j ) { POLYBENCH_JACOBI_2D_BODY2; } } } } stopTimer(); POLYBENCH_JACOBI_2D_DATA_RESET; break; } #if defined(RUN_RAJA_SEQ) case Lambda_Seq : { startTimer(); for (RepIndex_type irep = 0; irep < run_reps; ++irep) { for (Index_type t = 0; t < tsteps; ++t) { for (Index_type i = 1; i < N-1; ++i ) { for (Index_type j = 1; j < N-1; ++j ) { poly_jacobi2d_base_lam1(i, j); } } for (Index_type i = 1; i < N-1; ++i ) { for (Index_type j = 1; j < N-1; ++j ) { poly_jacobi2d_base_lam2(i, j); } } } } stopTimer(); POLYBENCH_JACOBI_2D_DATA_RESET; break; } case RAJA_Seq : { using EXEC_POL = RAJA::KernelPolicy< RAJA::statement::For<0, RAJA::loop_exec, RAJA::statement::For<1, RAJA::loop_exec, RAJA::statement::Lambda<0> > >, RAJA::statement::For<0, RAJA::loop_exec, RAJA::statement::For<1, RAJA::loop_exec, RAJA::statement::Lambda<1> > > >; startTimer(); for (RepIndex_type irep = 0; irep < run_reps; ++irep) { for (Index_type t = 0; t < tsteps; ++t) { RAJA::kernel<EXEC_POL>( RAJA::make_tuple(RAJA::RangeSegment{1, N-1}, RAJA::RangeSegment{1, N-1}), poly_jacobi2d_lam1, poly_jacobi2d_lam2 ); } } stopTimer(); POLYBENCH_JACOBI_2D_DATA_RESET; break; } #endif // RUN_RAJA_SEQ default : { std::cout << "\n POLYBENCH_JACOBI_2D : Unknown variant id = " << vid << std::endl; } } } } // end namespace polybench } // end namespace rajaperf
//===--- Attr.cpp - Swift Language Attr ASTs ------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements routines relating to declaration attributes. // //===----------------------------------------------------------------------===// #include "swift/AST/Attr.h" #include "swift/AST/ASTContext.h" #include "swift/AST/ASTPrinter.h" #include "swift/AST/Decl.h" #include "swift/AST/GenericEnvironment.h" #include "swift/AST/Module.h" #include "swift/AST/Types.h" #include "swift/Basic/Defer.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/ADT/StringSwitch.h" using namespace swift; #define DECL_ATTR(_, Id, ...) \ static_assert(IsTriviallyDestructible<Id##Attr>::value, \ "Attrs are BumpPtrAllocated; the destructor is never called"); #include "swift/AST/Attr.def" static_assert(IsTriviallyDestructible<DeclAttributes>::value, "DeclAttributes are BumpPtrAllocated; the d'tor is never called"); static_assert(IsTriviallyDestructible<TypeAttributes>::value, "TypeAttributes are BumpPtrAllocated; the d'tor is never called"); // Only allow allocation of attributes using the allocator in ASTContext. void *AttributeBase::operator new(size_t Bytes, ASTContext &C, unsigned Alignment) { return C.Allocate(Bytes, Alignment); } StringRef swift::getAccessLevelSpelling(AccessLevel value) { switch (value) { case AccessLevel::Private: return "private"; case AccessLevel::FilePrivate: return "fileprivate"; case AccessLevel::Internal: return "internal"; case AccessLevel::Public: return "public"; case AccessLevel::Open: return "open"; } llvm_unreachable("Unhandled AccessLevel in switch."); } /// Given a name like "autoclosure", return the type attribute ID that /// corresponds to it. This returns TAK_Count on failure. /// TypeAttrKind TypeAttributes::getAttrKindFromString(StringRef Str) { return llvm::StringSwitch<TypeAttrKind>(Str) #define TYPE_ATTR(X) .Case(#X, TAK_##X) #include "swift/AST/Attr.def" .Default(TAK_Count); } /// Return the name (like "autoclosure") for an attribute ID. const char *TypeAttributes::getAttrName(TypeAttrKind kind) { switch (kind) { default: llvm_unreachable("Invalid attribute ID"); #define TYPE_ATTR(X) case TAK_##X: return #X; #include "swift/AST/Attr.def" } } /// Given a name like "inline", return the decl attribute ID that corresponds /// to it. Note that this is a many-to-one mapping, and that the identifier /// passed in may only be the first portion of the attribute (e.g. in the case /// of the 'unowned(unsafe)' attribute, the string passed in is 'unowned'. /// /// Also note that this recognizes both attributes like '@inline' (with no @) /// and decl modifiers like 'final'. This returns DAK_Count on failure. /// DeclAttrKind DeclAttribute::getAttrKindFromString(StringRef Str) { return llvm::StringSwitch<DeclAttrKind>(Str) #define DECL_ATTR(X, CLASS, ...) .Case(#X, DAK_##CLASS) #define DECL_ATTR_ALIAS(X, CLASS) .Case(#X, DAK_##CLASS) #include "swift/AST/Attr.def" .Default(DAK_Count); } /// Returns true if this attribute can appear on the specified decl. bool DeclAttribute::canAttributeAppearOnDecl(DeclAttrKind DK, const Decl *D) { return canAttributeAppearOnDeclKind(DK, D->getKind()); } bool DeclAttribute::canAttributeAppearOnDeclKind(DeclAttrKind DAK, DeclKind DK) { auto Options = getOptions(DAK); switch (DK) { #define DECL(Id, Parent) case DeclKind::Id: return (Options & On##Id) != 0; #include "swift/AST/DeclNodes.def" } llvm_unreachable("bad DeclKind"); } bool DeclAttributes::isUnavailableInSwiftVersion( const version::Version &effectiveVersion) const { llvm::VersionTuple vers = effectiveVersion; for (auto attr : *this) { if (auto available = dyn_cast<AvailableAttr>(attr)) { if (available->isInvalid()) continue; if (available->getPlatformAgnosticAvailability() == PlatformAgnosticAvailabilityKind::SwiftVersionSpecific) { if (available->Introduced.hasValue() && available->Introduced.getValue() > vers) return true; if (available->Obsoleted.hasValue() && available->Obsoleted.getValue() <= vers) return true; } } } return false; } const AvailableAttr *DeclAttributes::getUnavailable( const ASTContext &ctx) const { const AvailableAttr *conditional = nullptr; for (auto Attr : *this) if (auto AvAttr = dyn_cast<AvailableAttr>(Attr)) { if (AvAttr->isInvalid()) continue; // If this attribute doesn't apply to the active platform, we're done. if (!AvAttr->isActivePlatform(ctx) && !AvAttr->isLanguageVersionSpecific() && !AvAttr->isPackageDescriptionVersionSpecific()) continue; // Unconditional unavailable. if (AvAttr->isUnconditionallyUnavailable()) return AvAttr; switch (AvAttr->getVersionAvailability(ctx)) { case AvailableVersionComparison::Available: case AvailableVersionComparison::PotentiallyUnavailable: break; case AvailableVersionComparison::Obsoleted: case AvailableVersionComparison::Unavailable: conditional = AvAttr; break; } } return conditional; } const AvailableAttr * DeclAttributes::getDeprecated(const ASTContext &ctx) const { const AvailableAttr *conditional = nullptr; for (auto Attr : *this) { if (auto AvAttr = dyn_cast<AvailableAttr>(Attr)) { if (AvAttr->isInvalid()) continue; if (!AvAttr->isActivePlatform(ctx) && !AvAttr->isLanguageVersionSpecific() && !AvAttr->isPackageDescriptionVersionSpecific()) continue; // Unconditional deprecated. if (AvAttr->isUnconditionallyDeprecated()) return AvAttr; Optional<llvm::VersionTuple> DeprecatedVersion = AvAttr->Deprecated; if (!DeprecatedVersion.hasValue()) continue; llvm::VersionTuple MinVersion = AvAttr->getActiveVersion(ctx); // We treat the declaration as deprecated if it is deprecated on // all deployment targets. // Once availability checking is enabled by default, we should // query the type refinement context hierarchy to determine // whether a declaration is deprecated on all versions // allowed by the context containing the reference. if (DeprecatedVersion.getValue() <= MinVersion) { conditional = AvAttr; } } } return conditional; } void DeclAttributes::dump(const Decl *D) const { StreamPrinter P(llvm::errs()); PrintOptions PO = PrintOptions::printEverything(); print(P, PO, D); } /// Returns true if the attribute can be presented as a short form available /// attribute (e.g., as @available(iOS 8.0, *). The presentation requires an /// introduction version and does not support deprecation, obsoletion, or /// messages. LLVM_READONLY static bool isShortAvailable(const DeclAttribute *DA) { auto *AvailAttr = dyn_cast<AvailableAttr>(DA); if (!AvailAttr) return false; if (!AvailAttr->Introduced.hasValue()) return false; if (AvailAttr->Deprecated.hasValue()) return false; if (AvailAttr->Obsoleted.hasValue()) return false; if (!AvailAttr->Message.empty()) return false; if (!AvailAttr->Rename.empty()) return false; switch (AvailAttr->PlatformAgnostic) { case PlatformAgnosticAvailabilityKind::Deprecated: case PlatformAgnosticAvailabilityKind::Unavailable: case PlatformAgnosticAvailabilityKind::UnavailableInSwift: return false; case PlatformAgnosticAvailabilityKind::None: case PlatformAgnosticAvailabilityKind::SwiftVersionSpecific: case PlatformAgnosticAvailabilityKind::PackageDescriptionVersionSpecific: return true; } return true; } /// Print the short-form @available() attribute for an array of long-form /// AvailableAttrs that can be represented in the short form. /// For example, for: /// @available(OSX, introduced: 10.10) /// @available(iOS, introduced: 8.0) /// this will print: /// @available(OSX 10.10, iOS 8.0, *) static void printShortFormAvailable(ArrayRef<const DeclAttribute *> Attrs, ASTPrinter &Printer, const PrintOptions &Options) { assert(!Attrs.empty()); Printer << "@available("; auto FirstAvail = cast<AvailableAttr>(Attrs.front()); if (Attrs.size() == 1 && FirstAvail->getPlatformAgnosticAvailability() != PlatformAgnosticAvailabilityKind::None) { assert(FirstAvail->Introduced.hasValue()); if (FirstAvail->isLanguageVersionSpecific()) { Printer << "swift "; } else { assert(FirstAvail->isPackageDescriptionVersionSpecific()); Printer << "_PackageDescription "; } Printer << FirstAvail->Introduced.getValue().getAsString() << ")"; } else { for (auto *DA : Attrs) { auto *AvailAttr = cast<AvailableAttr>(DA); assert(AvailAttr->Introduced.hasValue()); Printer << platformString(AvailAttr->Platform) << " " << AvailAttr->Introduced.getValue().getAsString() << ", "; } Printer << "*)"; } Printer.printNewline(); } void DeclAttributes::print(ASTPrinter &Printer, const PrintOptions &Options, const Decl *D) const { if (!DeclAttrs) return; using AttributeVector = SmallVector<const DeclAttribute *, 8>; AttributeVector orderedAttributes(begin(), end()); std::reverse(orderedAttributes.begin(), orderedAttributes.end()); // Process attributes in passes. AttributeVector shortAvailableAttributes; const DeclAttribute *swiftVersionAvailableAttribute = nullptr; const DeclAttribute *packageDescriptionVersionAvailableAttribute = nullptr; AttributeVector longAttributes; AttributeVector attributes; AttributeVector modifiers; for (auto DA : orderedAttributes) { if (!Options.PrintImplicitAttrs && DA->isImplicit()) continue; if (!Options.PrintUserInaccessibleAttrs && DeclAttribute::isUserInaccessible(DA->getKind())) continue; if (Options.excludeAttrKind(DA->getKind())) continue; // Be careful not to coalesce `@available(swift 5)` with other short // `available' attributes. if (auto *availableAttr = dyn_cast<AvailableAttr>(DA)) { if (availableAttr->isLanguageVersionSpecific() && isShortAvailable(availableAttr)) { swiftVersionAvailableAttribute = availableAttr; continue; } if (availableAttr->isPackageDescriptionVersionSpecific() && isShortAvailable(availableAttr)) { packageDescriptionVersionAvailableAttribute = availableAttr; continue; } } AttributeVector &which = DA->isDeclModifier() ? modifiers : isShortAvailable(DA) ? shortAvailableAttributes : DA->isLongAttribute() ? longAttributes : attributes; which.push_back(DA); } if (swiftVersionAvailableAttribute) printShortFormAvailable(swiftVersionAvailableAttribute, Printer, Options); if (packageDescriptionVersionAvailableAttribute) printShortFormAvailable(packageDescriptionVersionAvailableAttribute, Printer, Options); if (!shortAvailableAttributes.empty()) printShortFormAvailable(shortAvailableAttributes, Printer, Options); for (auto DA : longAttributes) DA->print(Printer, Options, D); for (auto DA : attributes) DA->print(Printer, Options, D); for (auto DA : modifiers) DA->print(Printer, Options, D); } SourceLoc DeclAttributes::getStartLoc(bool forModifiers) const { if (isEmpty()) return SourceLoc(); const DeclAttribute *lastAttr = nullptr; for (auto attr : *this) { if (attr->getRangeWithAt().Start.isValid() && (!forModifiers || attr->isDeclModifier())) lastAttr = attr; } return lastAttr ? lastAttr->getRangeWithAt().Start : SourceLoc(); } bool DeclAttribute::printImpl(ASTPrinter &Printer, const PrintOptions &Options, const Decl *D) const { // Handle any attributes that are not printed at all before we make printer // callbacks. switch (getKind()) { case DAK_ObjC: if (Options.PrintForSIL && isImplicit()) return false; break; case DAK_RawDocComment: case DAK_ObjCBridged: case DAK_SynthesizedProtocol: case DAK_Rethrows: case DAK_Infix: return false; default: break; } // Handle any decl-modifiers. // FIXME: Ideally we would handle decl modifiers as a special kind of // attribute, but for now it's simpler to treat them as a keyword in the // printer. switch (getKind()) { // Handle all of the SIMPLE_DECL_ATTRs. #define SIMPLE_DECL_ATTR(X, CLASS, ...) case DAK_##CLASS: #include "swift/AST/Attr.def" case DAK_Inline: case DAK_AccessControl: case DAK_ReferenceOwnership: case DAK_Effects: case DAK_Optimize: if (DeclAttribute::isDeclModifier(getKind())) { Printer.printKeyword(getAttrName()); } else { Printer.printSimpleAttr(getAttrName(), /*needAt=*/true); } return true; case DAK_SetterAccess: Printer.printKeyword(getAttrName()); Printer << "(set)"; return true; default: break; } Printer.callPrintStructurePre(PrintStructureKind::BuiltinAttribute); SWIFT_DEFER { Printer.printStructurePost(PrintStructureKind::BuiltinAttribute); }; switch (getKind()) { case DAK_Semantics: Printer.printAttrName("@_semantics"); Printer << "(\"" << cast<SemanticsAttr>(this)->Value << "\")"; break; case DAK_Alignment: Printer.printAttrName("@_alignment"); Printer << "(" << cast<AlignmentAttr>(this)->getValue() << ")"; break; case DAK_SILGenName: Printer.printAttrName("@_silgen_name"); Printer << "(\"" << cast<SILGenNameAttr>(this)->Name << "\")"; break; case DAK_Available: { Printer.printAttrName("@available"); Printer << "("; auto Attr = cast<AvailableAttr>(this); if (Attr->isLanguageVersionSpecific()) Printer << "swift"; else if (Attr->isPackageDescriptionVersionSpecific()) Printer << "_PackageDescription"; else Printer << Attr->platformString(); if (Attr->isUnconditionallyUnavailable()) Printer << ", unavailable"; else if (Attr->isUnconditionallyDeprecated()) Printer << ", deprecated"; if (Attr->Introduced) Printer << ", introduced: " << Attr->Introduced.getValue().getAsString(); if (Attr->Deprecated) Printer << ", deprecated: " << Attr->Deprecated.getValue().getAsString(); if (Attr->Obsoleted) Printer << ", obsoleted: " << Attr->Obsoleted.getValue().getAsString(); if (!Attr->Rename.empty()) Printer << ", renamed: \"" << Attr->Rename << "\""; // If there's no message, but this is specifically an imported // "unavailable in Swift" attribute, synthesize a message to look good in // the generated interface. if (!Attr->Message.empty()) { Printer << ", message: "; Printer.printEscapedStringLiteral(Attr->Message); } else if (Attr->getPlatformAgnosticAvailability() == PlatformAgnosticAvailabilityKind::UnavailableInSwift) Printer << ", message: \"Not available in Swift\""; Printer << ")"; break; } case DAK_CDecl: Printer << "@_cdecl(\"" << cast<CDeclAttr>(this)->Name << "\")"; break; case DAK_ObjC: { Printer.printAttrName("@objc"); llvm::SmallString<32> scratch; if (auto Name = cast<ObjCAttr>(this)->getName()) { if (!cast<ObjCAttr>(this)->isNameImplicit()) Printer << "(" << Name->getString(scratch) << ")"; } break; } case DAK_PrivateImport: { Printer.printAttrName("@_private(sourceFile: \""); Printer << cast<PrivateImportAttr>(this)->getSourceFile() << "\")"; break; } case DAK_SwiftNativeObjCRuntimeBase: { auto *attr = cast<SwiftNativeObjCRuntimeBaseAttr>(this); Printer.printAttrName("@_swift_native_objc_runtime_base"); Printer << "(" << attr->BaseClassName.str() << ")"; break; } case DAK_Specialize: { Printer << "@" << getAttrName() << "("; auto *attr = cast<SpecializeAttr>(this); auto exported = attr->isExported() ? "true" : "false"; auto kind = attr->isPartialSpecialization() ? "partial" : "full"; Printer << "exported: "<< exported << ", "; Printer << "kind: " << kind << ", "; if (!attr->getRequirements().empty()) { Printer << "where "; } std::function<Type(Type)> GetInterfaceType; auto *FnDecl = dyn_cast_or_null<AbstractFunctionDecl>(D); if (!FnDecl || !FnDecl->getGenericEnvironment()) GetInterfaceType = [](Type Ty) -> Type { return Ty; }; else { // Use GenericEnvironment to produce user-friendly // names instead of something like t_0_0. auto *GenericEnv = FnDecl->getGenericEnvironment(); assert(GenericEnv); GetInterfaceType = [=](Type Ty) -> Type { return GenericEnv->getSugaredType(Ty); }; } interleave(attr->getRequirements(), [&](Requirement req) { auto FirstTy = GetInterfaceType(req.getFirstType()); if (req.getKind() != RequirementKind::Layout) { auto SecondTy = GetInterfaceType(req.getSecondType()); Requirement ReqWithDecls(req.getKind(), FirstTy, SecondTy); ReqWithDecls.print(Printer, Options); } else { Requirement ReqWithDecls(req.getKind(), FirstTy, req.getLayoutConstraint()); ReqWithDecls.print(Printer, Options); } }, [&] { Printer << ", "; }); Printer << ")"; break; } case DAK_Implements: { Printer.printAttrName("@_implements"); Printer << "("; auto *attr = cast<ImplementsAttr>(this); attr->getProtocolType().getType().print(Printer, Options); Printer << ", " << attr->getMemberName() << ")"; break; } case DAK_ObjCRuntimeName: { Printer.printAttrName("@_objcRuntimeName"); Printer << "("; auto *attr = cast<ObjCRuntimeNameAttr>(this); Printer << attr->Name; Printer << ")"; break; } case DAK_ClangImporterSynthesizedType: { Printer.printAttrName("@_clangImporterSynthesizedType"); auto *attr = cast<ClangImporterSynthesizedTypeAttr>(this); Printer << "(originalTypeName: \"" << attr->originalTypeName << "\", manglingForKind: \"" << attr->getManglingName() << "\")"; break; } case DAK_DynamicReplacement: { Printer.printAttrName("@_dynamicReplacement"); Printer << "(for: \""; auto *attr = cast<DynamicReplacementAttr>(this); Printer << attr->getReplacedFunctionName() << "\")"; break; } case DAK_Count: llvm_unreachable("exceed declaration attribute kinds"); #define SIMPLE_DECL_ATTR(X, CLASS, ...) case DAK_##CLASS: #include "swift/AST/Attr.def" llvm_unreachable("handled above"); default: assert(DeclAttribute::isDeclModifier(getKind()) && "handled above"); } return true; } void DeclAttribute::print(ASTPrinter &Printer, const PrintOptions &Options, const Decl *D) const { if (!printImpl(Printer, Options, D)) return; // Nothing printed. if (isLongAttribute() && Options.PrintLongAttrsOnSeparateLines) Printer.printNewline(); else Printer << " "; } void DeclAttribute::print(llvm::raw_ostream &OS, const Decl *D) const { StreamPrinter P(OS); print(P, PrintOptions(), D); } uint64_t DeclAttribute::getOptions(DeclAttrKind DK) { switch (DK) { case DAK_Count: llvm_unreachable("getOptions needs a valid attribute"); #define DECL_ATTR(_, CLASS, OPTIONS, ...)\ case DAK_##CLASS: return OPTIONS; #include "swift/AST/Attr.def" } llvm_unreachable("bad DeclAttrKind"); } StringRef DeclAttribute::getAttrName() const { switch (getKind()) { case DAK_Count: llvm_unreachable("getAttrName needs a valid attribute"); #define SIMPLE_DECL_ATTR(NAME, CLASS, ...) \ case DAK_##CLASS: \ return #NAME; #include "swift/AST/Attr.def" case DAK_SILGenName: return "_silgen_name"; case DAK_Alignment: return "_alignment"; case DAK_CDecl: return "_cdecl"; case DAK_SwiftNativeObjCRuntimeBase: return "_swift_native_objc_runtime_base"; case DAK_Semantics: return "_semantics"; case DAK_Available: return "availability"; case DAK_ObjC: case DAK_ObjCRuntimeName: return "objc"; case DAK_DynamicReplacement: return "_dynamicReplacement"; case DAK_PrivateImport: return "_private"; case DAK_RestatedObjCConformance: return "_restatedObjCConformance"; case DAK_Inline: { switch (cast<InlineAttr>(this)->getKind()) { case InlineKind::Never: return "inline(never)"; case InlineKind::Always: return "inline(__always)"; } llvm_unreachable("Invalid inline kind"); } case DAK_Optimize: { switch (cast<OptimizeAttr>(this)->getMode()) { case OptimizationMode::NoOptimization: return "_optimize(none)"; case OptimizationMode::ForSpeed: return "_optimize(speed)"; case OptimizationMode::ForSize: return "_optimize(size)"; default: llvm_unreachable("Invalid optimization kind"); } } case DAK_Effects: switch (cast<EffectsAttr>(this)->getKind()) { case EffectsKind::ReadNone: return "_effects(readnone)"; case EffectsKind::ReadOnly: return "_effects(readonly)"; case EffectsKind::ReleaseNone: return "_effects(releasenone)"; case EffectsKind::ReadWrite: return "_effects(readwrite)"; case EffectsKind::Unspecified: return "_effects(unspecified)"; } case DAK_AccessControl: case DAK_SetterAccess: { AccessLevel access = cast<AbstractAccessControlAttr>(this)->getAccess(); return getAccessLevelSpelling(access); } case DAK_ReferenceOwnership: return keywordOf(cast<ReferenceOwnershipAttr>(this)->get()); case DAK_RawDocComment: return "<<raw doc comment>>"; case DAK_ObjCBridged: return "<<ObjC bridged>>"; case DAK_SynthesizedProtocol: return "<<synthesized protocol>>"; case DAK_Specialize: return "_specialize"; case DAK_Implements: return "_implements"; case DAK_ClangImporterSynthesizedType: return "_clangImporterSynthesizedType"; } llvm_unreachable("bad DeclAttrKind"); } ObjCAttr::ObjCAttr(SourceLoc atLoc, SourceRange baseRange, Optional<ObjCSelector> name, SourceRange parenRange, ArrayRef<SourceLoc> nameLocs) : DeclAttribute(DAK_ObjC, atLoc, baseRange, /*Implicit=*/false), NameData(nullptr) { if (name) { // Store the name. assert(name->getNumSelectorPieces() == nameLocs.size()); NameData = name->getOpaqueValue(); // Store location information. Bits.ObjCAttr.HasTrailingLocationInfo = true; getTrailingLocations()[0] = parenRange.Start; getTrailingLocations()[1] = parenRange.End; std::memcpy(getTrailingLocations().slice(2).data(), nameLocs.data(), nameLocs.size() * sizeof(SourceLoc)); } else { Bits.ObjCAttr.HasTrailingLocationInfo = false; } Bits.ObjCAttr.ImplicitName = false; Bits.ObjCAttr.Swift3Inferred = false; } ObjCAttr *ObjCAttr::create(ASTContext &Ctx, Optional<ObjCSelector> name, bool isNameImplicit) { return new (Ctx) ObjCAttr(name, isNameImplicit); } ObjCAttr *ObjCAttr::createUnnamed(ASTContext &Ctx, SourceLoc AtLoc, SourceLoc ObjCLoc) { return new (Ctx) ObjCAttr(AtLoc, SourceRange(ObjCLoc), None, SourceRange(), { }); } ObjCAttr *ObjCAttr::createUnnamedImplicit(ASTContext &Ctx) { return new (Ctx) ObjCAttr(None, false); } ObjCAttr *ObjCAttr::createNullary(ASTContext &Ctx, SourceLoc AtLoc, SourceLoc ObjCLoc, SourceLoc LParenLoc, SourceLoc NameLoc, Identifier Name, SourceLoc RParenLoc) { void *mem = Ctx.Allocate(totalSizeToAlloc<SourceLoc>(3), alignof(ObjCAttr)); return new (mem) ObjCAttr(AtLoc, SourceRange(ObjCLoc, RParenLoc), ObjCSelector(Ctx, 0, Name), SourceRange(LParenLoc, RParenLoc), NameLoc); } ObjCAttr *ObjCAttr::createNullary(ASTContext &Ctx, Identifier Name, bool isNameImplicit) { return new (Ctx) ObjCAttr(ObjCSelector(Ctx, 0, Name), isNameImplicit); } ObjCAttr *ObjCAttr::createSelector(ASTContext &Ctx, SourceLoc AtLoc, SourceLoc ObjCLoc, SourceLoc LParenLoc, ArrayRef<SourceLoc> NameLocs, ArrayRef<Identifier> Names, SourceLoc RParenLoc) { assert(NameLocs.size() == Names.size()); void *mem = Ctx.Allocate(totalSizeToAlloc<SourceLoc>(NameLocs.size() + 2), alignof(ObjCAttr)); return new (mem) ObjCAttr(AtLoc, SourceRange(ObjCLoc, RParenLoc), ObjCSelector(Ctx, Names.size(), Names), SourceRange(LParenLoc, RParenLoc), NameLocs); } ObjCAttr *ObjCAttr::createSelector(ASTContext &Ctx, ArrayRef<Identifier> Names, bool isNameImplicit) { return new (Ctx) ObjCAttr(ObjCSelector(Ctx, Names.size(), Names), isNameImplicit); } ArrayRef<SourceLoc> ObjCAttr::getNameLocs() const { if (!hasTrailingLocationInfo()) return { }; return getTrailingLocations().slice(2); } SourceLoc ObjCAttr::getLParenLoc() const { if (!hasTrailingLocationInfo()) return SourceLoc(); return getTrailingLocations()[0]; } SourceLoc ObjCAttr::getRParenLoc() const { if (!hasTrailingLocationInfo()) return SourceLoc(); return getTrailingLocations()[1]; } ObjCAttr *ObjCAttr::clone(ASTContext &context) const { auto attr = new (context) ObjCAttr(getName(), isNameImplicit()); attr->setSwift3Inferred(isSwift3Inferred()); return attr; } PrivateImportAttr::PrivateImportAttr(SourceLoc atLoc, SourceRange baseRange, StringRef sourceFile, SourceRange parenRange) : DeclAttribute(DAK_PrivateImport, atLoc, baseRange, /*Implicit=*/false), SourceFile(sourceFile) {} PrivateImportAttr *PrivateImportAttr::create(ASTContext &Ctxt, SourceLoc AtLoc, SourceLoc PrivateLoc, SourceLoc LParenLoc, StringRef sourceFile, SourceLoc RParenLoc) { return new (Ctxt) PrivateImportAttr(AtLoc, SourceRange(PrivateLoc, RParenLoc), sourceFile, SourceRange(LParenLoc, RParenLoc)); } DynamicReplacementAttr::DynamicReplacementAttr(SourceLoc atLoc, SourceRange baseRange, DeclName name, SourceRange parenRange) : DeclAttribute(DAK_DynamicReplacement, atLoc, baseRange, /*Implicit=*/false), ReplacedFunctionName(name), ReplacedFunction(nullptr) { Bits.DynamicReplacementAttr.HasTrailingLocationInfo = true; getTrailingLocations()[0] = parenRange.Start; getTrailingLocations()[1] = parenRange.End; } DynamicReplacementAttr * DynamicReplacementAttr::create(ASTContext &Ctx, SourceLoc AtLoc, SourceLoc DynReplLoc, SourceLoc LParenLoc, DeclName ReplacedFunction, SourceLoc RParenLoc) { void *mem = Ctx.Allocate(totalSizeToAlloc<SourceLoc>(2), alignof(DynamicReplacementAttr)); return new (mem) DynamicReplacementAttr( AtLoc, SourceRange(DynReplLoc, RParenLoc), ReplacedFunction, SourceRange(LParenLoc, RParenLoc)); } DynamicReplacementAttr *DynamicReplacementAttr::create(ASTContext &Ctx, DeclName name) { return new (Ctx) DynamicReplacementAttr(name); } DynamicReplacementAttr * DynamicReplacementAttr::create(ASTContext &Ctx, DeclName name, AbstractFunctionDecl *f) { auto res = new (Ctx) DynamicReplacementAttr(name); res->setReplacedFunction(f); return res; } SourceLoc DynamicReplacementAttr::getLParenLoc() const { return getTrailingLocations()[0]; } SourceLoc DynamicReplacementAttr::getRParenLoc() const { return getTrailingLocations()[1]; } AvailableAttr * AvailableAttr::createPlatformAgnostic(ASTContext &C, StringRef Message, StringRef Rename, PlatformAgnosticAvailabilityKind Kind, llvm::VersionTuple Obsoleted) { assert(Kind != PlatformAgnosticAvailabilityKind::None); llvm::VersionTuple NoVersion; if (Kind == PlatformAgnosticAvailabilityKind::SwiftVersionSpecific) { assert(!Obsoleted.empty()); } return new (C) AvailableAttr( SourceLoc(), SourceRange(), PlatformKind::none, Message, Rename, NoVersion, SourceRange(), NoVersion, SourceRange(), Obsoleted, SourceRange(), Kind, /* isImplicit */ false); } bool AvailableAttr::isActivePlatform(const ASTContext &ctx) const { return isPlatformActive(Platform, ctx.LangOpts); } bool AvailableAttr::isLanguageVersionSpecific() const { if (PlatformAgnostic == PlatformAgnosticAvailabilityKind::SwiftVersionSpecific) { assert(Platform == PlatformKind::none && (Introduced.hasValue() || Deprecated.hasValue() || Obsoleted.hasValue())); return true; } return false; } bool AvailableAttr::isPackageDescriptionVersionSpecific() const { if (PlatformAgnostic == PlatformAgnosticAvailabilityKind::PackageDescriptionVersionSpecific) { assert(Platform == PlatformKind::none && (Introduced.hasValue() || Deprecated.hasValue() || Obsoleted.hasValue())); return true; } return false; } bool AvailableAttr::isUnconditionallyUnavailable() const { switch (PlatformAgnostic) { case PlatformAgnosticAvailabilityKind::None: case PlatformAgnosticAvailabilityKind::Deprecated: case PlatformAgnosticAvailabilityKind::SwiftVersionSpecific: case PlatformAgnosticAvailabilityKind::PackageDescriptionVersionSpecific: return false; case PlatformAgnosticAvailabilityKind::Unavailable: case PlatformAgnosticAvailabilityKind::UnavailableInSwift: return true; } llvm_unreachable("Unhandled PlatformAgnosticAvailabilityKind in switch."); } bool AvailableAttr::isUnconditionallyDeprecated() const { switch (PlatformAgnostic) { case PlatformAgnosticAvailabilityKind::None: case PlatformAgnosticAvailabilityKind::Unavailable: case PlatformAgnosticAvailabilityKind::UnavailableInSwift: case PlatformAgnosticAvailabilityKind::SwiftVersionSpecific: case PlatformAgnosticAvailabilityKind::PackageDescriptionVersionSpecific: return false; case PlatformAgnosticAvailabilityKind::Deprecated: return true; } llvm_unreachable("Unhandled PlatformAgnosticAvailabilityKind in switch."); } llvm::VersionTuple AvailableAttr::getActiveVersion(const ASTContext &ctx) const { if (isLanguageVersionSpecific()) { return ctx.LangOpts.EffectiveLanguageVersion; } else if (isPackageDescriptionVersionSpecific()) { return ctx.LangOpts.PackageDescriptionVersion; } else { return ctx.LangOpts.getMinPlatformVersion(); } } AvailableVersionComparison AvailableAttr::getVersionAvailability( const ASTContext &ctx) const { // Unconditional unavailability. if (isUnconditionallyUnavailable()) return AvailableVersionComparison::Unavailable; llvm::VersionTuple queryVersion = getActiveVersion(ctx); // If this entity was obsoleted before or at the query platform version, // consider it obsolete. if (Obsoleted && *Obsoleted <= queryVersion) return AvailableVersionComparison::Obsoleted; // If this entity was introduced after the query version and we're doing a // platform comparison, true availability can only be determined dynamically; // if we're doing a _language_ version check, the query version is a // static requirement, so we treat "introduced later" as just plain // unavailable. if (Introduced && *Introduced > queryVersion) { if (isLanguageVersionSpecific() || isPackageDescriptionVersionSpecific()) return AvailableVersionComparison::Unavailable; else return AvailableVersionComparison::PotentiallyUnavailable; } // The entity is available. return AvailableVersionComparison::Available; } const AvailableAttr *AvailableAttr::isUnavailable(const Decl *D) { ASTContext &ctx = D->getASTContext(); return D->getAttrs().getUnavailable(ctx); } SpecializeAttr::SpecializeAttr(SourceLoc atLoc, SourceRange range, TrailingWhereClause *clause, bool exported, SpecializationKind kind) : DeclAttribute(DAK_Specialize, atLoc, range, /*Implicit=*/false), trailingWhereClause(clause) { Bits.SpecializeAttr.exported = exported; Bits.SpecializeAttr.kind = unsigned(kind); Bits.SpecializeAttr.numRequirements = 0; } SpecializeAttr::SpecializeAttr(SourceLoc atLoc, SourceRange range, ArrayRef<Requirement> requirements, bool exported, SpecializationKind kind) : DeclAttribute(DAK_Specialize, atLoc, range, /*Implicit=*/false) { Bits.SpecializeAttr.exported = exported; Bits.SpecializeAttr.kind = unsigned(kind); Bits.SpecializeAttr.numRequirements = requirements.size(); std::copy(requirements.begin(), requirements.end(), getRequirementsData()); } void SpecializeAttr::setRequirements(ASTContext &Ctx, ArrayRef<Requirement> requirements) { unsigned numClauseRequirements = (trailingWhereClause) ? trailingWhereClause->getRequirements().size() : 0; assert(requirements.size() <= numClauseRequirements); if (!numClauseRequirements) return; Bits.SpecializeAttr.numRequirements = requirements.size(); std::copy(requirements.begin(), requirements.end(), getRequirementsData()); } ArrayRef<Requirement> SpecializeAttr::getRequirements() const { return const_cast<SpecializeAttr*>(this)->getRequirements(); } TrailingWhereClause *SpecializeAttr::getTrailingWhereClause() const { return trailingWhereClause; } SpecializeAttr *SpecializeAttr::create(ASTContext &Ctx, SourceLoc atLoc, SourceRange range, TrailingWhereClause *clause, bool exported, SpecializationKind kind) { unsigned numRequirements = (clause) ? clause->getRequirements().size() : 0; unsigned size = sizeof(SpecializeAttr) + (numRequirements * sizeof(Requirement)); void *mem = Ctx.Allocate(size, alignof(SpecializeAttr)); return new (mem) SpecializeAttr(atLoc, range, clause, exported, kind); } SpecializeAttr *SpecializeAttr::create(ASTContext &Ctx, SourceLoc atLoc, SourceRange range, ArrayRef<Requirement> requirements, bool exported, SpecializationKind kind) { unsigned numRequirements = requirements.size(); unsigned size = sizeof(SpecializeAttr) + (numRequirements * sizeof(Requirement)); void *mem = Ctx.Allocate(size, alignof(SpecializeAttr)); return new (mem) SpecializeAttr(atLoc, range, requirements, exported, kind); } ImplementsAttr::ImplementsAttr(SourceLoc atLoc, SourceRange range, TypeLoc ProtocolType, DeclName MemberName, DeclNameLoc MemberNameLoc) : DeclAttribute(DAK_Implements, atLoc, range, /*Implicit=*/false), ProtocolType(ProtocolType), MemberName(MemberName), MemberNameLoc(MemberNameLoc) { } ImplementsAttr *ImplementsAttr::create(ASTContext &Ctx, SourceLoc atLoc, SourceRange range, TypeLoc ProtocolType, DeclName MemberName, DeclNameLoc MemberNameLoc) { void *mem = Ctx.Allocate(sizeof(ImplementsAttr), alignof(ImplementsAttr)); return new (mem) ImplementsAttr(atLoc, range, ProtocolType, MemberName, MemberNameLoc); } TypeLoc ImplementsAttr::getProtocolType() const { return ProtocolType; } TypeLoc &ImplementsAttr::getProtocolType() { return ProtocolType; }
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/public/cpp/ash_typography.h" namespace ash { void ApplyAshFontStyles(int context, int style, int* size_delta, gfx::Font::Weight* font_weight) { switch (context) { case CONTEXT_LAUNCHER_BUTTON: *size_delta = 2; break; case CONTEXT_TOAST_OVERLAY: *size_delta = 3; break; } } } // namespace ash
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2012, 2013 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <ripple/unity/rocksdb.h> #if RIPPLE_ROCKSDB_AVAILABLE #include <ripple/basics/contract.h> #include <ripple/basics/ByteUtilities.h> #include <ripple/core/Config.h> // VFALCO Bad dependency #include <ripple/nodestore/Factory.h> #include <ripple/nodestore/Manager.h> #include <ripple/nodestore/impl/BatchWriter.h> #include <ripple/nodestore/impl/DecodedBlob.h> #include <ripple/nodestore/impl/EncodedBlob.h> #include <ripple/beast/core/CurrentThreadName.h> #include <atomic> #include <memory> namespace ripple { namespace NodeStore { class RocksDBEnv : public rocksdb::EnvWrapper { public: RocksDBEnv () : EnvWrapper (rocksdb::Env::Default()) { } struct ThreadParams { ThreadParams (void (*f_)(void*), void* a_) : f (f_) , a (a_) { } void (*f)(void*); void* a; }; static void thread_entry (void* ptr) { ThreadParams* const p (reinterpret_cast <ThreadParams*> (ptr)); void (*f)(void*) = p->f; void* a (p->a); delete p; static std::atomic <std::size_t> n; std::size_t const id (++n); std::stringstream ss; ss << "rocksdb #" << id; beast::setCurrentThreadName (ss.str()); (*f)(a); } void StartThread (void (*f)(void*), void* a) override { ThreadParams* const p (new ThreadParams (f, a)); EnvWrapper::StartThread (&RocksDBEnv::thread_entry, p); } }; //------------------------------------------------------------------------------ class RocksDBBackend : public Backend , public BatchWriter::Callback { private: std::atomic <bool> m_deletePath; public: beast::Journal m_journal; size_t const m_keyBytes; Scheduler& m_scheduler; BatchWriter m_batch; std::string m_name; std::unique_ptr <rocksdb::DB> m_db; int fdRequired_ = 2048; rocksdb::Options m_options; RocksDBBackend (int keyBytes, Section const& keyValues, Scheduler& scheduler, beast::Journal journal, RocksDBEnv* env) : m_deletePath (false) , m_journal (journal) , m_keyBytes (keyBytes) , m_scheduler (scheduler) , m_batch (*this, scheduler) { if (! get_if_exists(keyValues, "path", m_name)) Throw<std::runtime_error> ("Missing path in RocksDBFactory backend"); rocksdb::BlockBasedTableOptions table_options; m_options.env = env; if (keyValues.exists ("cache_mb")) table_options.block_cache = rocksdb::NewLRUCache ( get<int>(keyValues, "cache_mb") * megabytes(1)); if (auto const v = get<int>(keyValues, "filter_bits")) { bool const filter_blocks = !keyValues.exists ("filter_full") || (get<int>(keyValues, "filter_full") == 0); table_options.filter_policy.reset (rocksdb::NewBloomFilterPolicy (v, filter_blocks)); } if (get_if_exists (keyValues, "open_files", m_options.max_open_files)) fdRequired_ = m_options.max_open_files; if (keyValues.exists ("file_size_mb")) { m_options.target_file_size_base = megabytes(1) * get<int>(keyValues,"file_size_mb"); m_options.max_bytes_for_level_base = 5 * m_options.target_file_size_base; m_options.write_buffer_size = 2 * m_options.target_file_size_base; } get_if_exists (keyValues, "file_size_mult", m_options.target_file_size_multiplier); if (keyValues.exists ("bg_threads")) { m_options.env->SetBackgroundThreads (get<int>(keyValues, "bg_threads"), rocksdb::Env::LOW); } if (keyValues.exists ("high_threads")) { auto const highThreads = get<int>(keyValues, "high_threads"); m_options.env->SetBackgroundThreads (highThreads, rocksdb::Env::HIGH); // If we have high-priority threads, presumably we want to // use them for background flushes if (highThreads > 0) m_options.max_background_flushes = highThreads; } m_options.compression = rocksdb::kSnappyCompression; get_if_exists (keyValues, "block_size", table_options.block_size); if (keyValues.exists ("universal_compaction") && (get<int>(keyValues, "universal_compaction") != 0)) { m_options.compaction_style = rocksdb::kCompactionStyleUniversal; m_options.min_write_buffer_number_to_merge = 2; m_options.max_write_buffer_number = 6; m_options.write_buffer_size = 6 * m_options.target_file_size_base; } if (keyValues.exists("bbt_options")) { auto const s = rocksdb::GetBlockBasedTableOptionsFromString( table_options, get<std::string>(keyValues, "bbt_options"), &table_options); if (! s.ok()) Throw<std::runtime_error> ( std::string("Unable to set RocksDB bbt_options: ") + s.ToString()); } m_options.table_factory.reset(NewBlockBasedTableFactory(table_options)); if (keyValues.exists("options")) { auto const s = rocksdb::GetOptionsFromString( m_options, get<std::string>(keyValues, "options"), &m_options); if (! s.ok()) Throw<std::runtime_error> ( std::string("Unable to set RocksDB options: ") + s.ToString()); } std::string s1, s2; rocksdb::GetStringFromDBOptions(&s1, m_options, "; "); rocksdb::GetStringFromColumnFamilyOptions(&s2, m_options, "; "); JLOG(m_journal.debug()) << "RocksDB DBOptions: " << s1; JLOG(m_journal.debug()) << "RocksDB CFOptions: " << s2; } ~RocksDBBackend () override { close(); } void open(bool createIfMissing) override { if (m_db) { assert(false); JLOG(m_journal.error()) << "database is already open"; return; } rocksdb::DB* db = nullptr; m_options.create_if_missing = createIfMissing; rocksdb::Status status = rocksdb::DB::Open(m_options, m_name, &db); if (!status.ok() || !db) Throw<std::runtime_error>( std::string("Unable to open/create RocksDB: ") + status.ToString()); m_db.reset(db); } void close() override { if (m_db) { m_db.reset(); if (m_deletePath) { boost::filesystem::path dir = m_name; boost::filesystem::remove_all (dir); } } } std::string getName() override { return m_name; } //-------------------------------------------------------------------------- Status fetch (void const* key, std::shared_ptr<NodeObject>* pObject) override { assert(m_db); pObject->reset (); Status status (ok); rocksdb::ReadOptions const options; rocksdb::Slice const slice (static_cast <char const*> (key), m_keyBytes); std::string string; rocksdb::Status getStatus = m_db->Get (options, slice, &string); if (getStatus.ok ()) { DecodedBlob decoded (key, string.data (), string.size ()); if (decoded.wasOk ()) { *pObject = decoded.createObject (); } else { // Decoding failed, probably corrupted! // status = dataCorrupt; } } else { if (getStatus.IsCorruption ()) { status = dataCorrupt; } else if (getStatus.IsNotFound ()) { status = notFound; } else { status = Status (customCode + getStatus.code()); JLOG(m_journal.error()) << getStatus.ToString (); } } return status; } bool canFetchBatch() override { return false; } std::vector<std::shared_ptr<NodeObject>> fetchBatch (std::size_t n, void const* const* keys) override { Throw<std::runtime_error> ("pure virtual called"); return {}; } void store (std::shared_ptr<NodeObject> const& object) override { m_batch.store (object); } void storeBatch (Batch const& batch) override { assert(m_db); rocksdb::WriteBatch wb; EncodedBlob encoded; for (auto const& e : batch) { encoded.prepare (e); wb.Put ( rocksdb::Slice (reinterpret_cast <char const*> ( encoded.getKey ()), m_keyBytes), rocksdb::Slice (reinterpret_cast <char const*> ( encoded.getData ()), encoded.getSize ())); } rocksdb::WriteOptions const options; auto ret = m_db->Write (options, &wb); if (! ret.ok ()) Throw<std::runtime_error> ("storeBatch failed: " + ret.ToString()); } void for_each (std::function <void(std::shared_ptr<NodeObject>)> f) override { assert(m_db); rocksdb::ReadOptions const options; std::unique_ptr <rocksdb::Iterator> it (m_db->NewIterator (options)); for (it->SeekToFirst (); it->Valid (); it->Next ()) { if (it->key ().size () == m_keyBytes) { DecodedBlob decoded (it->key ().data (), it->value ().data (), it->value ().size ()); if (decoded.wasOk ()) { f (decoded.createObject ()); } else { // Uh oh, corrupted data! JLOG(m_journal.fatal()) << "Corrupt NodeObject #" << from_hex_text<uint256>(it->key ().data ()); } } else { // VFALCO NOTE What does it mean to find an // incorrectly sized key? Corruption? JLOG(m_journal.fatal()) << "Bad key size = " << it->key ().size (); } } } int getWriteLoad () override { return m_batch.getWriteLoad (); } void setDeletePath() override { m_deletePath = true; } //-------------------------------------------------------------------------- void writeBatch (Batch const& batch) override { storeBatch (batch); } void verify() override { } /** Returns the number of file descriptors the backend expects to need */ int fdRequired() const override { return fdRequired_; } }; //------------------------------------------------------------------------------ class RocksDBFactory : public Factory { public: RocksDBEnv m_env; RocksDBFactory () { Manager::instance().insert(*this); } ~RocksDBFactory () override { Manager::instance().erase(*this); } std::string getName () const override { return "RocksDB"; } std::unique_ptr <Backend> createInstance ( size_t keyBytes, Section const& keyValues, Scheduler& scheduler, beast::Journal journal) override { return std::make_unique <RocksDBBackend> ( keyBytes, keyValues, scheduler, journal, &m_env); } }; static RocksDBFactory rocksDBFactory; } } #endif
/* * Copyright 2012 Open Source Robotics Foundation * * 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. * */ /* Desc: * Author: Jonas Mellin & Zakiruz Zaman * Date: 6th December 2011 */ #ifndef _RFIDVISUAL_HH_ #define _RFIDVISUAL_HH_ #include <string> #include "rendering/Visual.hh" #include "msgs/MessageTypes.hh" #include "transport/TransportTypes.hh" namespace gazebo { namespace rendering { class DynamicLines; /// \addtogroup gazebo_rendering /// \{ /// \class RFIDVisual RFIDVisual.hh rendering/rendering.hh /// \brief Visualization for RFID sensor. class RFIDVisual : public Visual { /// \brief Constructor. /// \param[in] _name Name of the Visual. /// \param[in] _vis Parent Visual. /// \param[in] _topicName Name of the topic which publishes RFID data. public: RFIDVisual(const std::string &_name, VisualPtr _vis, const std::string &_topicName); /// \brief Destructor public: virtual ~RFIDVisual(); /// \brief Callback for the RFID sensor data. /// \param[in] _msg Message containing RFID data private: void OnScan(ConstPosePtr &_msg); /// \brief Pointer to the transport::Node for communication private: transport::NodePtr node; /// \brief Pointer to the transport::Subscriber for recieving data private: transport::SubscriberPtr rfidSub; }; /// \} } } #endif
/// Copyright (C) 2019 DG.C, DGCHOW, deguangchow /// deguangchow@qq.com /// /// \brief protobuf_demo : 定义控制台应用程序的入口点。 /// /// \author deguangchow /// \version 1.0 /// \2019/10/28 #include "stdafx.h" #include "addressbook_read.h" #include "addressbook_write.h" #include "item_read.h" #include "item_write.h" int main(int argc, char* argv[]) { #if 0 test_addressbook_write(argc, argv); test_addressbook_read(argc, argv); test_item_write(argc, argv); test_item_read(argc, argv); #endif test_item_read(argc, argv); return 0; }
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include <gtest/gtest.h> #include "hphp/runtime/base/array-data.h" #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/comparisons.h" #include "hphp/runtime/base/packed-array.h" #include "hphp/runtime/base/packed-array-defs.h" #include "hphp/runtime/base/repo-auth-type-array.h" namespace HPHP { TEST(ARRAY, Capacity) { EXPECT_TRUE(kPackedCapCodeThreshold == 0x10000); #define MP(a, b) std::make_pair(a, b) // Update the numbers if we change kPackedCapCodeThreshold #if (LG_SMART_SIZES_PER_DOUBLING == 1) std::pair<uint32_t, uint32_t> caps [] = { MP(3, 0), MP(4, 5), MP(5, 0), MP(6, 7), MP(7, 0), MP(8, 11), MP(12, 15), MP(127, 0), MP(128, 191), MP(0xFFFF, 0), MP(0x10000, 0x17F00), MP(0x10001, 0) }; #elif (LG_SMART_SIZES_PER_DOUBLING == 2) std::pair<uint32_t, uint32_t> caps [] = { MP(3, 0), MP(4, 0), MP(5, 0), MP(6, 0), MP(7, 0), MP(8, 9), MP(12, 13), MP(127, 0), MP(128, 159), MP(0xFFFF, 0), MP(0x10000, 0x13F00), MP(0x10001, 0) }; #else #error Unknown LG_SMART_SIZES_PER_DOUBLING #endif #undef MP for (size_t i = 0; i != sizeof(caps) / sizeof(caps[0]); ++i) { EXPECT_TRUE(PackedArray::getMaxCapInPlaceFast(caps[i].first) == caps[i].second); } } TEST(ARRAY, Constructors) { const String s_name("name"); Array arr; EXPECT_TRUE(arr.empty()); EXPECT_TRUE(arr.size() == 0); EXPECT_TRUE(arr.length() == 0); EXPECT_TRUE(arr.isNull()); arr = Array::Create(); EXPECT_TRUE(arr.empty()); EXPECT_TRUE(arr.size() == 0); EXPECT_TRUE(arr.length() == 0); EXPECT_TRUE(!arr.isNull()); arr = Array::Create(0); EXPECT_TRUE(!arr.empty()); EXPECT_TRUE(arr.size() == 1); EXPECT_TRUE(arr.length() == 1); EXPECT_TRUE(!arr.isNull()); EXPECT_TRUE(arr[0].toInt32() == 0); arr = Array::Create("test"); EXPECT_TRUE(!arr.empty()); EXPECT_TRUE(arr.size() == 1); EXPECT_TRUE(arr.length() == 1); EXPECT_TRUE(!arr.isNull()); EXPECT_TRUE(equal(arr[0], String("test"))); Array arrCopy = arr; arr = Array::Create(arr); EXPECT_TRUE(!arr.empty()); EXPECT_TRUE(arr.size() == 1); EXPECT_TRUE(arr.length() == 1); EXPECT_TRUE(!arr.isNull()); EXPECT_TRUE(arr[0].toArray().size() == 1); EXPECT_TRUE(equal(arr[0], arrCopy)); arr = Array::Create("name", 1); EXPECT_TRUE(!arr.empty()); EXPECT_TRUE(arr.size() == 1); EXPECT_TRUE(arr.length() == 1); EXPECT_TRUE(!arr.isNull()); EXPECT_TRUE(arr[s_name].toInt32() == 1); arr = Array::Create(s_name, "test"); EXPECT_TRUE(!arr.empty()); EXPECT_TRUE(arr.size() == 1); EXPECT_TRUE(arr.length() == 1); EXPECT_TRUE(!arr.isNull()); EXPECT_TRUE(equal(arr[s_name], String("test"))); arrCopy = arr; arr = Array::Create(s_name, arr); EXPECT_TRUE(!arr.empty()); EXPECT_TRUE(arr.size() == 1); EXPECT_TRUE(arr.length() == 1); EXPECT_TRUE(!arr.isNull()); EXPECT_TRUE(equal(arr[s_name], arrCopy)); EXPECT_TRUE(arr[s_name].toArray().size() == 1); } TEST(ARRAY, Iteration) { Array arr = make_map_array("n1", "v1", "n2", "v2"); int i = 0; for (ArrayIter iter = arr.begin(); iter; ++iter, ++i) { if (i == 0) { EXPECT_TRUE(equal(iter.first(), String("n1"))); EXPECT_TRUE(equal(iter.second(), String("v1"))); } else { EXPECT_TRUE(equal(iter.first(), String("n2"))); EXPECT_TRUE(equal(iter.second(), String("v2"))); } } EXPECT_TRUE(i == 2); } TEST(ARRAY, Conversions) { const String s_Array("Array"); Array arr0; EXPECT_TRUE(arr0.toBoolean() == false); EXPECT_TRUE(arr0.toByte() == 0); EXPECT_TRUE(arr0.toInt16() == 0); EXPECT_TRUE(arr0.toInt32() == 0); EXPECT_TRUE(arr0.toInt64() == 0); EXPECT_TRUE(arr0.toDouble() == 0.0); EXPECT_TRUE(arr0.toString().empty()); Array arr1 = Array::Create("test"); EXPECT_TRUE(arr1.toBoolean() == true); EXPECT_TRUE(arr1.toByte() == 1); EXPECT_TRUE(arr1.toInt16() == 1); EXPECT_TRUE(arr1.toInt32() == 1); EXPECT_TRUE(arr1.toInt64() == 1); EXPECT_TRUE(arr1.toDouble() == 1.0); EXPECT_TRUE(arr1.toString() == s_Array); } TEST(Array, Offsets) { const String s_n1("n1"); const String s_n2("n2"); const String s_1("1"); { Array arr; arr.set(0, "v1"); arr.set(1, "v2"); EXPECT_TRUE(equal(arr, make_packed_array("v1", "v2"))); } { Array arr; arr.set(s_n1, "v1"); arr.set(s_n2, "v2"); EXPECT_TRUE(equal(arr, make_map_array("n1", "v1", "n2", "v2"))); } { Array arr; arr.lvalAt(0) = String("v1"); arr.lvalAt(1) = String("v2"); EXPECT_TRUE(equal(arr, make_packed_array("v1", "v2"))); } { Array arr; arr.lvalAt(s_n1) = String("v1"); arr.lvalAt(s_n2) = String("v2"); EXPECT_TRUE(equal(arr, make_map_array("n1", "v1", "n2", "v2"))); } { Array arr; Variant name = "name"; arr.lvalAt(name) = String("value"); EXPECT_TRUE(equal(arr, make_map_array("name", "value"))); } { Array arr; arr.lvalAt(1) = 10; EXPECT_TRUE(equal(arr[1], 10)); EXPECT_TRUE(equal(arr[Variant(1.5)], 10)); EXPECT_TRUE(equal(arr[s_1], 10)); EXPECT_TRUE(equal(arr[Variant("1")], 10)); } { Array arr; arr.lvalAt(Variant(1.5)) = 10; EXPECT_TRUE(equal(arr[1], 10)); EXPECT_TRUE(equal(arr[Variant(1.5)], 10)); EXPECT_TRUE(equal(arr[s_1], 10)); EXPECT_TRUE(equal(arr[Variant("1")], 10)); } { Array arr; arr.lvalAt(s_1) = 10; EXPECT_TRUE(equal(arr[1], 10)); EXPECT_TRUE(equal(arr[Variant(1.5)], 10)); EXPECT_TRUE(equal(arr[s_1], 10)); EXPECT_TRUE(equal(arr[Variant("1")], 10)); } { Array arr; arr.lvalAt(Variant("1")) = 10; EXPECT_TRUE(equal(arr[1], 10)); EXPECT_TRUE(equal(arr[Variant(1.5)], 10)); EXPECT_TRUE(equal(arr[s_1], 10)); EXPECT_TRUE(equal(arr[Variant("1")], 10)); } } TEST(ARRAY, Membership) { const String s_n1("n1"); const String s_n2("n2"); const String s_name("name"); const String s_1("1"); { Array arr; arr.lvalAt(0) = String("v1"); arr.lvalAt(1) = String("v2"); EXPECT_TRUE(arr.exists(0)); arr.remove(0); EXPECT_TRUE(!arr.exists(0)); EXPECT_TRUE(equal(arr, Array::Create(1, "v2"))); arr.append("v3"); EXPECT_TRUE(equal(arr, make_map_array(1, "v2", 2, "v3"))); } { const String s_0("0"); Array arr; arr.lvalAt(0) = String("v1"); EXPECT_TRUE(arr.exists(0)); arr.remove(String(s_0)); EXPECT_TRUE(!arr.exists(0)); } { Array arr; arr.lvalAt(0) = String("v1"); EXPECT_TRUE(arr.exists(0)); arr.remove(Variant("0")); EXPECT_TRUE(!arr.exists(0)); } { Array arr; arr.lvalAt(0) = String("v1"); EXPECT_TRUE(arr.exists(0)); arr.remove(Variant(Variant("0"))); EXPECT_TRUE(!arr.exists(0)); } { Array arr; arr.lvalAt(0) = String("v1"); EXPECT_TRUE(arr.exists(0)); arr.remove(Variant(Variant(0.5))); EXPECT_TRUE(!arr.exists(0)); } { Array arr; arr.lvalAt(Variant()) = 123; EXPECT_TRUE(arr.exists(empty_string_ref)); arr.remove(Variant()); EXPECT_TRUE(!arr.exists(empty_string_ref)); } { Array arr; arr.lvalAt(s_n1) = String("v1"); arr.lvalAt(s_n2) = String("v2"); EXPECT_TRUE(arr.exists(s_n1)); arr.remove(s_n1); EXPECT_TRUE(!arr.exists(s_n1)); EXPECT_TRUE(equal(arr, Array::Create(s_n2, "v2"))); arr.append("v3"); EXPECT_TRUE(equal(arr, make_map_array("n2", "v2", 0, "v3"))); } { Array arr; arr.lvalAt() = String("test"); EXPECT_TRUE(equal(arr, make_packed_array("test"))); } { Array arr; arr.lvalAt(s_name) = String("value"); EXPECT_TRUE(arr.exists(s_name)); } { Array arr; arr.lvalAt(1) = String("value"); EXPECT_TRUE(arr.exists(1)); EXPECT_TRUE(arr.exists(s_1)); EXPECT_TRUE(arr.exists(Variant("1"))); EXPECT_TRUE(arr.exists(Variant(1))); EXPECT_TRUE(arr.exists(Variant(1.5))); } { Array arr; arr.lvalAt(s_1) = String("value"); EXPECT_TRUE(arr.exists(1)); EXPECT_TRUE(arr.exists(s_1)); EXPECT_TRUE(arr.exists(Variant("1"))); EXPECT_TRUE(arr.exists(Variant(1))); EXPECT_TRUE(arr.exists(Variant(1.5))); } { Array arr; arr.lvalAt(Variant(1.5)) = String("value"); EXPECT_TRUE(arr.exists(1)); EXPECT_TRUE(arr.exists(s_1)); EXPECT_TRUE(arr.exists(Variant("1"))); EXPECT_TRUE(arr.exists(Variant(1))); EXPECT_TRUE(arr.exists(Variant(1.5))); } { Array arr; arr.lvalAt(Variant("1")) = String("value"); EXPECT_TRUE(arr.exists(1)); EXPECT_TRUE(arr.exists(s_1)); EXPECT_TRUE(arr.exists(Variant("1"))); EXPECT_TRUE(arr.exists(Variant(1))); EXPECT_TRUE(arr.exists(Variant(1.5))); } } TEST(ARRAY, Merge) { { Array arr = Array::Create(0) + Array::Create(1); EXPECT_TRUE(equal(arr, Array::Create(0))); arr += make_packed_array(0, 1); EXPECT_TRUE(equal(arr, make_packed_array(0, 1))); arr = Array::Create(0).merge(Array::Create(1)); EXPECT_TRUE(equal(arr, make_packed_array(0, 1))); arr = arr.merge(make_packed_array(0, 1)); EXPECT_TRUE(equal(arr, make_packed_array(0, 1, 0, 1))); arr = Array::Create("s0").merge(Array::Create("s1")); EXPECT_TRUE(equal(arr, make_packed_array("s0", "s1"))); arr = Array::Create("n0", "s0") + Array::Create("n1", "s1"); EXPECT_TRUE(equal(arr, make_map_array("n0", "s0", "n1", "s1"))); arr += make_map_array("n0", "s0", "n1", "s1"); EXPECT_TRUE(equal(arr, make_map_array("n0", "s0", "n1", "s1"))); arr = Array::Create("n0", "s0").merge(Array::Create("n1", "s1")); EXPECT_TRUE(equal(arr, make_map_array("n0", "s0", "n1", "s1"))); Array arrX = make_map_array("n0", "s2", "n1", "s3"); arr = arr.merge(arrX); EXPECT_TRUE(equal(arr, make_map_array("n0", "s2", "n1", "s3"))); } { Array arr = make_map_array(0, "a", 1, "b"); EXPECT_TRUE(arr->isVectorData()); } { Array arr = make_map_array(1, "a", 0, "b"); EXPECT_TRUE(!arr->isVectorData()); } { Array arr = make_map_array(1, "a", 2, "b"); EXPECT_TRUE(!arr->isVectorData()); } { Array arr = make_map_array(1, "a"); arr.set(0, "b"); EXPECT_TRUE(!arr->isVectorData()); } } }
#include "CVertexBuffer.h" #include <glad/glad.h> namespace ion { namespace Graphics { namespace GL { CVertexBuffer::~CVertexBuffer() { CheckedGLCall(glDeleteBuffers(1, &Handle)); } void CVertexBuffer::UploadData(void const * const Data, size_t const DataSize, size_t const NumberOfElements) { CheckedGLCall(glBindBuffer(GL_ARRAY_BUFFER, Handle)); CheckedGLCall(glBufferData(GL_ARRAY_BUFFER, NumberOfElements * DataSize, Data, GL_STATIC_DRAW)); CheckedGLCall(glBindBuffer(GL_ARRAY_BUFFER, 0)); } void CVertexBuffer::UploadSubData(void const * const Data, size_t const DataSize, size_t const Offset, size_t const NumberOfElements) { CheckedGLCall(glBindBuffer(GL_ARRAY_BUFFER, Handle)); CheckedGLCall(glBufferSubData(GL_ARRAY_BUFFER, Offset * DataSize, NumberOfElements * DataSize, Data)); CheckedGLCall(glBindBuffer(GL_ARRAY_BUFFER, 0)); } void CVertexBuffer::SetInputLayout(SInputLayoutElement const * const InputLayoutArray, int const NumElements) { InputLayout.clear(); InputLayout.insert(InputLayout.begin(), InputLayoutArray, InputLayoutArray + NumElements); } void CVertexBuffer::SetInstancingEnabled(bool const Enabled) { Instancing = Enabled; } } } }
// YellowLISP (c) 2020 Stuart Riffle (MIT license) #include "Yellow.h" #include "Runtime.h" Runtime::Runtime(Console* console) : _console(console) { // Cell 0 is unused and invalid. Attempting to access it will assert. // Cell 1 is nil, the empty list. Its _next field is 0, to prevent walking through it. _cell.resize(2); _null = 1; _cell[_null]._type = TYPE_SYMBOL; StoreSymbol("nil", _null, SYMBOL_RESERVED); _cellFreeList = 0; _cellFreeCount = 0; _garbageCollectionNeeded = false; _dot = RegisterReserved("."); _true = RegisterReserved("#t"); _false = RegisterReserved("#f"); _quote = RegisterPrimitive("quote", nullptr, SYMBOLFLAG_DONT_EVAL_ARGS); _unquote = RegisterPrimitive("unquote", nullptr, SYMBOLFLAG_DONT_EVAL_ARGS); _quasiquote = RegisterPrimitive("quasiquote", nullptr, SYMBOLFLAG_DONT_EVAL_ARGS); // R5RS fundamental forms: define, lambda, quote, if, define-syntax, let-syntax, letrec-syntax, syntax-rules, set! // R5RS derived forms: do, let, let*, letrec, cond, case, and, or, begin, named let, delay, unquote, unquote-splicing, quasiquote // Language primitives RegisterPrimitive("apply", &Runtime::APPLY); RegisterPrimitive("atom", &Runtime::ATOM); RegisterPrimitive("begin", &Runtime::BEGIN, SYMBOLFLAG_DONT_EVAL_ARGS); RegisterPrimitive("car", &Runtime::CAR); RegisterPrimitive("cdr", &Runtime::CDR); RegisterPrimitive("cond", &Runtime::COND, SYMBOLFLAG_DONT_EVAL_ARGS); RegisterPrimitive("cons", &Runtime::CONS, SYMBOLFLAG_DONT_EVAL_ARGS); RegisterPrimitive("define", &Runtime::DEFINE, SYMBOLFLAG_DONT_EVAL_ARGS); RegisterPrimitive("eval", &Runtime::EVAL); RegisterPrimitive("lambda", &Runtime::LAMBDA, SYMBOLFLAG_DONT_EVAL_ARGS); RegisterPrimitive("let", &Runtime::LET, SYMBOLFLAG_DONT_EVAL_ARGS); RegisterPrimitive("letrec", &Runtime::LETREC, SYMBOLFLAG_DONT_EVAL_ARGS); RegisterPrimitive("let*", &Runtime::LETSTAR, SYMBOLFLAG_DONT_EVAL_ARGS); RegisterPrimitive("list", &Runtime::LIST, SYMBOLFLAG_DONT_EVAL_ARGS); RegisterPrimitive("set!", &Runtime::SETQ, SYMBOLFLAG_DONT_EVAL_ARGS); RegisterPrimitive("define-syntax", &Runtime::DEFINE, SYMBOLFLAG_DONT_EVAL_ARGS); RegisterPrimitive("let-syntax", &Runtime::LET, SYMBOLFLAG_DONT_EVAL_ARGS); RegisterPrimitive("letrec-syntax", &Runtime::LETREC, SYMBOLFLAG_DONT_EVAL_ARGS); RegisterPrimitive("syntax-rules", &Runtime::SETQ, SYMBOLFLAG_DONT_EVAL_ARGS); RegisterPrimitive("eq?", &Runtime::EQP); RegisterPrimitive("eqv?", &Runtime::EQVP); RegisterPrimitive("equal?", &Runtime::EQUALP); RegisterPrimitive("pair?", &Runtime::PAIRP); RegisterPrimitive("symbol?", &Runtime::SYMBOLP); RegisterPrimitive("procedure?", &Runtime::PROCEDUREP); RegisterPrimitive("boolean?", &Runtime::NUMBERP); RegisterPrimitive("char?", &Runtime::NUMBERP); RegisterPrimitive("string?", &Runtime::NUMBERP); RegisterPrimitive("port?", &Runtime::NUMBERP); RegisterPrimitive("procedure?", &Runtime::NUMBERP); RegisterPrimitive("number?", &Runtime::NUMBERP); RegisterPrimitive("complex?", &Runtime::NUMBERP); RegisterPrimitive("real?", &Runtime::NUMBERP); RegisterPrimitive("rational?", &Runtime::NUMBERP); RegisterPrimitive("integer?", &Runtime::NUMBERP); RegisterPrimitive("+", &Runtime::ADD); RegisterPrimitive("-", &Runtime::SUB); RegisterPrimitive("*", &Runtime::MUL); RegisterPrimitive("/", &Runtime::DIV); RegisterPrimitive("%", &Runtime::MOD); RegisterPrimitive("<", &Runtime::LESS); RegisterPrimitive("=", &Runtime::EQLOP); RegisterPrimitive("round", &Runtime::ROUND); RegisterPrimitive("trunc", &Runtime::TRUNCATE); RegisterPrimitive("floor", &Runtime::FLOOR); RegisterPrimitive("ceiling", &Runtime::CEILING); RegisterPrimitive("exp", &Runtime::EXP); RegisterPrimitive("log", &Runtime::LOG); RegisterPrimitive("sqrt", &Runtime::SQRT); RegisterPrimitive("abs", &Runtime::ABS ); RegisterPrimitive("sin", &Runtime::SIN); RegisterPrimitive("sinh", &Runtime::SINH); RegisterPrimitive("asin", &Runtime::ASIN); RegisterPrimitive("asinh", &Runtime::ASINH); RegisterPrimitive("cos", &Runtime::COS); RegisterPrimitive("cosh", &Runtime::COSH); RegisterPrimitive("acos", &Runtime::ACOS); RegisterPrimitive("acosh", &Runtime::ACOSH); RegisterPrimitive("tan", &Runtime::TAN); RegisterPrimitive("tanh", &Runtime::TANH); RegisterPrimitive("atan", &Runtime::ATAN); RegisterPrimitive("atanh", &Runtime::ATANH); // Interpreter/meta commands RegisterPrimitive("help", &Runtime::Help); RegisterPrimitive("exit", &Runtime::Exit); RegisterPrimitive("quit", &Runtime::Exit); RegisterPrimitive("run-gc", &Runtime::RunGC); } Runtime::~Runtime() { } CELLID Runtime::RegisterReserved(const char* ident) { SYMBOLIDX symbolIndex = GetSymbolIndex(ident); CELLID cellIndex = _symbol[symbolIndex]._symbolCell; _symbol[symbolIndex]._type = SYMBOL_RESERVED; return (cellIndex); } SYMBOLIDX Runtime::StoreSymbol(const char* ident, CELLID cellIndex, SymbolType symbolType, STRINGHASH hash) { if (!hash) hash = HashString(ident); SYMBOLIDX symbolIndex = (SYMBOLIDX)_symbol.Alloc(); _globalScope[hash] = symbolIndex; _cell[cellIndex]._data = symbolIndex; SymbolInfo& symbol = _symbol[symbolIndex]; symbol._type = symbolType; symbol._ident = ident; symbol._symbolCell = cellIndex; symbol._valueCell.SetInvalid(); return (symbolIndex); } SYMBOLIDX Runtime::GetSymbolIndex(const char* ident) { STRINGHASH hash = HashString(ident); auto iter = _globalScope.find(hash); if (iter != _globalScope.end()) return (iter->second); CELLID cellIndex = AllocateCell(TYPE_SYMBOL); SYMBOLIDX symbolIndex = StoreSymbol(ident, cellIndex, SYMBOL_INVALID, hash); return (symbolIndex); } CELLID Runtime::RegisterPrimitive(const char* ident, PrimitiveFunc func, SymbolFlags flags) { SYMBOLIDX symbolIndex = GetSymbolIndex(ident); SymbolInfo& symbol = _symbol[symbolIndex]; symbol._type = SYMBOL_PRIMITIVE; symbol._flags = flags; symbol._primIndex = (PRIMIDX) _primitive.size(); _primitive.emplace_back(); PrimitiveInfo& primInfo = _primitive.back(); primInfo._name = ident; primInfo._func = func; return (symbol._symbolCell); } bool Runtime::IsTruthy(CELLID index) { if (index == _false) return _false; return _true; } CELLID Runtime::EncodeSyntaxTree(const NodeRef& node) { DebugValidateCells(); CELLID result = EncodeTreeNode(node); //DumpCellGraph(result, true); DebugValidateCells(); return (result); } CELLID Runtime::EncodeTreeNode(const NodeRef& node) { switch (node->_type) { case AST_NODE_INT_LITERAL: { CELLID intCell = AllocateCell(TYPE_INT); StoreIntLiteral(intCell, node->_int); return (intCell); } case AST_NODE_FLOAT_LITERAL: { CELLID floatCell = AllocateCell(TYPE_FLOAT); StoreFloatLiteral(floatCell, node->_float); return (floatCell); } case AST_NODE_STRING_LITERAL: { CELLID stringCell = AllocateCell(TYPE_STRING); StoreStringLiteral(stringCell, node->_string.c_str()); return (stringCell); } case AST_NODE_IDENTIFIER: { SYMBOLIDX symbolIndex = GetSymbolIndex(node->_identifier.c_str()); SymbolInfo& symbol = _symbol[symbolIndex]; return (symbol._symbolCell); } case AST_NODE_LIST: { if (node->_list.empty()) return (_null); CELLID listHeadCell; CELLID listPrevCell; for (auto& elemNode : node->_list) { CELLID listCell = AllocateCell(TYPE_CONS); CELLID nodeCell = EncodeTreeNode(elemNode); _cell[listCell]._data = nodeCell; if (listPrevCell.IsValid()) _cell[listPrevCell]._next = listCell; else listHeadCell = listCell; listPrevCell = listCell; } return (listHeadCell); } default: break; } RAISE_ERROR(ERROR_RUNTIME_NOT_IMPLEMENTED, "unknown AST node type"); return 0; } string Runtime::GetPrintedValue(CELLID index) { assert(index.IsValid()); if (index == _null) return ("nil"); std::stringstream ss; switch (_cell[index]._type) { case TYPE_CONS: { if (_cell[index]._data == _quote) { ss << "'"; ss << GetPrintedValue(_cell[_cell[index]._next]._data); } else if (_cell[index]._data == _unquote) { ss << ","; ss << GetPrintedValue(_cell[_cell[index]._next]._data); } else if (_cell[index]._data == _quasiquote) { ss << "`"; ss << GetPrintedValue(_cell[_cell[index]._next]._data); } else { ss << '('; CELLID curr = index; while (curr != _null) { ss << GetPrintedValue(_cell[curr]._data); CELLID next = _cell[curr]._next; assert(next.IsValid()); if ((next != _null) && (_cell[next]._type != TYPE_CONS)) { ss << " . " << GetPrintedValue(next); break; } if (next != _null) ss << " "; curr = next; } ss << ')'; } break; } case TYPE_INT: ss << LoadIntLiteral(index); break; case TYPE_FLOAT: ss << LoadFloatLiteral(index); break; case TYPE_STRING: ss << '\"' << LoadStringLiteral(index) << '\"'; break; case TYPE_SYMBOL: ss << _symbol[_cell[index]._data]._ident; break; case TYPE_LAMBDA: ss << "<lambda " << index << ">"; break; default: RAISE_ERROR(ERROR_INTERNAL_CELL_TABLE_CORRUPT, "unrecognized cell type"); break; } return (ss.str()); }
#pragma once #include "base/macros.hpp" #include "base/assert.hpp" #include <cstring> #include <string> namespace strings { class UniString; } namespace feature { static int const g_arrWorldScales[] = { 3, 5, 7, 9 }; // 9 = scales::GetUpperWorldScale() static int const g_arrCountryScales[] = { 10, 12, 14, 17 }; // 17 = scales::GetUpperScale() inline std::string GetTagForIndex(char const * prefix, size_t ind) { std::string str; str.reserve(strlen(prefix) + 1); str = prefix; static char const arrChar[] = { '0', '1', '2', '3' }; static_assert(ARRAY_SIZE(arrChar) >= ARRAY_SIZE(g_arrWorldScales), ""); static_assert(ARRAY_SIZE(arrChar) >= ARRAY_SIZE(g_arrCountryScales), ""); ASSERT(ind >= 0 && ind < ARRAY_SIZE(arrChar), (ind)); str += arrChar[ind]; return str; } bool IsDigit(int c); bool IsNumber(strings::UniString const & s); bool IsHouseNumber(std::string const & s); bool IsHouseNumber(strings::UniString const & s); bool IsHouseNumberDeepCheck(strings::UniString const & s); uint8_t PopulationToRank(uint64_t p); uint64_t RankToPopulation(uint8_t r); } // namespace feature
#include <algorithm> #include <iostream> using namespace std; //背包容量 #define CAPACITY 10 // 物品数量 #define NUM 5 // 长度多除一个好处理 int optimal[NUM][CAPACITY] = { 0 }; int weight[NUM] = { 4, 5, 6, 2, 2 }; int value[NUM] = { 6, 4, 5, 3, 6 }; void echo() { for (int i = 0; i <= NUM; i++) { for (int j = 0; j <= CAPACITY; j++) { cout << optimal[i][j] << " "; } cout << endl; } } int main() { for (int i = 0; i < NUM; i++) { for (int j = 0; j < CAPACITY; j++) { if (weight[i] < j) { optimal[i][j] = max(optimal[i - 1][j], optimal[i - 1][j - weight[i]] + value[i]); } else { optimal[i][j] = optimal[i - 1][j]; } } } cout << endl; echo(); cout << "The optimal solution is: " << optimal[NUM - 1][CAPACITY - 1] << endl; return 0; }
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/mlir/xla/transforms/mhlo_to_lhlo_with_xla.h" #include <climits> #include <memory> #include <tuple> #include "absl/algorithm/container.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" // from @llvm-project #include "mlir/IR/AffineExpr.h" // from @llvm-project #include "mlir/IR/AffineMap.h" // from @llvm-project #include "mlir/IR/Attributes.h" // from @llvm-project #include "mlir/IR/Builders.h" // from @llvm-project #include "mlir/IR/BuiltinAttributes.h" // from @llvm-project #include "mlir/IR/BuiltinOps.h" // from @llvm-project #include "mlir/IR/BuiltinTypes.h" // from @llvm-project #include "mlir/IR/Dialect.h" // from @llvm-project #include "mlir/IR/Location.h" // from @llvm-project #include "mlir/IR/MLIRContext.h" // from @llvm-project #include "mlir/IR/OpDefinition.h" // from @llvm-project #include "mlir/IR/Operation.h" // from @llvm-project #include "mlir/IR/PatternMatch.h" // from @llvm-project #include "mlir/IR/SymbolTable.h" // from @llvm-project #include "mlir/Pass/Pass.h" // from @llvm-project #include "mlir/Pass/PassOptions.h" // from @llvm-project #include "mlir/Translation.h" // from @llvm-project #include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/hlo_ops.h" #include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/hlo_ops_base_enums.h" #include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/lhlo_gpu_ops.h" #include "tensorflow/compiler/mlir/hlo/include/mlir-hlo/Dialect/mhlo/IR/lhlo_ops.h" #include "tensorflow/compiler/mlir/xla/attribute_importer.h" #include "tensorflow/compiler/mlir/xla/hlo_function_importer.h" #include "tensorflow/compiler/mlir/xla/hlo_utils.h" #include "tensorflow/compiler/mlir/xla/mlir_hlo_to_hlo.h" #include "tensorflow/compiler/mlir/xla/xla_mlir_translate_cl.h" #include "tensorflow/compiler/xla/debug_options_flags.h" #include "tensorflow/compiler/xla/service/backend.h" #include "tensorflow/compiler/xla/service/buffer_assignment.h" #include "tensorflow/compiler/xla/service/gpu/backend_configs.pb.h" #include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h" #include "tensorflow/compiler/xla/service/hlo_casting_utils.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/service/hlo_instruction.h" #include "tensorflow/compiler/xla/service/hlo_instructions.h" #include "tensorflow/compiler/xla/service/hlo_module.h" #include "tensorflow/compiler/xla/service/hlo_parser.h" #include "tensorflow/compiler/xla/service/llvm_ir/buffer_assignment_util.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/compiler/xla/window_util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" using xla::BufferAllocation; using xla::BufferAssignment; using xla::HloComputation; using xla::HloCustomCallInstruction; using xla::HloInfeedInstruction; using xla::HloInstruction; using xla::HloModule; using xla::HloModuleProto; using xla::HloOutfeedInstruction; using xla::HloProto; using xla::Shape; using xla::StatusOr; namespace mlir { namespace { absl::string_view StringRefToView(llvm::StringRef ref) { return {ref.data(), ref.size()}; } StatusOr<std::unique_ptr<HloModule>> HloModuleFromProto( const HloProto& hlo_proto) { const HloModuleProto& module_proto = hlo_proto.hlo_module(); TF_ASSIGN_OR_RETURN(const xla::HloModuleConfig module_config, HloModule::CreateModuleConfigFromProto( module_proto, xla::GetDebugOptionsFromFlags())); return HloModule::CreateFromProto(module_proto, module_config); } // Convert the MLIR `module` from HLO dialect to LHLO dialect using XLA for the // given platform. Status ConvertModule(std::unique_ptr<HloModule> hlo_module, ModuleOp module, StringRef platform_name) { auto platform = xla::se::MultiPlatformManager::PlatformWithName( StringRefToView(platform_name)); if (!platform.ok()) { std::string error_msg; llvm::raw_string_ostream os(error_msg); os << "failed to get platform: " << platform.status().ToString() << " (available Platform: "; std::vector<std::string> available_platforms; (void)xla::se::MultiPlatformManager::PlatformsWithFilter( [&](const stream_executor::Platform* p) { available_platforms.push_back(p->Name()); return false; }); llvm::interleaveComma(available_platforms, os); os << ")"; return xla::InvalidArgument("%s", os.str().c_str()); } xla::BackendOptions backend_options; backend_options.set_platform(platform.ValueOrDie()); auto backend_or_err = xla::Backend::CreateBackend(backend_options); TF_RETURN_WITH_CONTEXT_IF_ERROR(backend_or_err.status(), "failed to create XLA Backend "); auto backend = std::move(backend_or_err.ValueOrDie()); // Run all HLO passes to produce an optimized module. auto result_or = backend->compiler()->RunHloPassesAndBufferAssignement( std::move(hlo_module), backend->default_stream_executor(), optimize_xla_hlo, {backend->memory_allocator()}); TF_RETURN_WITH_CONTEXT_IF_ERROR(result_or.status(), "running XLA pass pipeline"); std::unique_ptr<HloModule> optimized_hlo_module = std::move(std::get<0>(result_or.ValueOrDie())); std::unique_ptr<BufferAssignment> assignment = std::move(std::get<1>(result_or.ValueOrDie())); // Clear the module before populating it back with the result of the // conversion. module.getBody()->clear(); OpBuilder builder(module); module.ensureTerminator(module.getBodyRegion(), builder, module.getLoc()); TF_RETURN_WITH_CONTEXT_IF_ERROR( HloToLhloModule(*assignment, *optimized_hlo_module, module), "converting HLO to LHLO"); return Status::OK(); } // This pass takes an MLIR HLO module, converts it to XLA to perform the HLO // optimization pipeline for the required platform, and then converts it back to // MLIR LHLO. class XlaHloToLhloPass : public PassWrapper<XlaHloToLhloPass, OperationPass<ModuleOp>> { void getDependentDialects(DialectRegistry& registry) const override { registry .insert<mlir::StandardOpsDialect, mlir::mhlo::MhloDialect, mlir::lmhlo::LmhloDialect, mlir::lmhlo_gpu::LmhloGpuDialect>(); } public: XlaHloToLhloPass() = default; XlaHloToLhloPass(const XlaHloToLhloPass&) {} private: void runOnOperation() final { ModuleOp module = getOperation(); auto status = [&module, this]() -> Status { SymbolTable symbol_table(module); if (!symbol_table.lookup("main")) { return xla::InvalidArgument( "conversion to HLO module failed: missing main()"); } HloProto hlo_proto; TF_RETURN_WITH_CONTEXT_IF_ERROR( ConvertMlirHloToHlo(module, &hlo_proto, /*use_tuple_args=*/false, /*return_tuple=*/false, /*shape_representation_fn=*/nullptr), "conversion to XLA HLO proto failed"); auto statusOrHloModule = HloModuleFromProto(hlo_proto); TF_RETURN_WITH_CONTEXT_IF_ERROR(statusOrHloModule.status(), "parsing HLO proto to HLO module failed"); std::unique_ptr<HloModule> hlo_module = std::move(statusOrHloModule.ValueOrDie()); return ConvertModule(std::move(hlo_module), module, platform_); }(); if (!status.ok()) { module.emitError() << status.ToString(); return signalPassFailure(); } } Option<std::string> platform_{ *this, "platform", llvm::cl::desc("The platform to use for the XLA optimization pipeline."), llvm::cl::init("Host")}; }; } // namespace // Creates MLIR operands corresponding to operands and results of the XLA HLO // instruction. If `num_operands` is valid, then only the first `num_operands` // operands of the HLO instruction will be considered. Status LhloDialectEmitter::CreateOperands( const HloInstruction* instr, absl::optional<xla::int64> num_operands, llvm::SmallVectorImpl<Value>& operands, size_t& num_arguments, size_t& num_results) { if (num_operands.value_or(0) > instr->operand_count()) return xla::InvalidArgument("num_operands must be <= operand count"); for (xla::int64 i = 0; i < num_operands.value_or(instr->operand_count()); ++i) { TF_RETURN_IF_ERROR(GetOrCreateView(instr->operand(i), &operands)); } num_arguments = operands.size(); TF_RETURN_IF_ERROR(GetOrCreateView(instr, &operands)); num_results = operands.size() - num_arguments; return Status::OK(); } template <typename OpType> OpType LhloDialectEmitter::CreateOpWithoutAttrs(const HloInstruction* instr, ValueRange operands) { Location loc = getLocation(instr); return builder_.create<OpType>(loc, llvm::None, operands, llvm::ArrayRef<NamedAttribute>{}); } template <typename OpType> StatusOr<OpType> LhloDialectEmitter::CreateOpWithoutAttrs( const HloInstruction* instr, size_t& num_arguments, size_t& num_results, absl::optional<xla::int64> num_operands) { llvm::SmallVector<Value, 4> operands; TF_RETURN_IF_ERROR(CreateOperands(instr, num_operands, operands, num_arguments, num_results)); return CreateOpWithoutAttrs<OpType>(instr, operands); } StatusOr<mlir::Operation*> LhloDialectEmitter::EmitOp( const HloInstruction* instr) { using xla::HloOpcode; switch (instr->opcode()) { case HloOpcode::kAbs: return CreateOpWithoutAttrs<lmhlo::AbsOp>(instr); case HloOpcode::kAdd: return CreateOpWithoutAttrs<lmhlo::AddOp>(instr); case HloOpcode::kAllToAll: return EmitAllToAllOp(instr); case HloOpcode::kAllGather: return EmitAllGatherOp(instr); case HloOpcode::kAllReduce: return EmitAllReduceOp(instr); case HloOpcode::kAnd: return CreateOpWithoutAttrs<lmhlo::AndOp>(instr); case HloOpcode::kAtan2: return CreateOpWithoutAttrs<lmhlo::Atan2Op>(instr); case HloOpcode::kBitcast: return nullptr; case HloOpcode::kBitcastConvert: return CreateOpWithoutAttrs<lmhlo::BitcastConvertOp>(instr); case HloOpcode::kBroadcast: return EmitBroadcastOp(instr); case HloOpcode::kCeil: return CreateOpWithoutAttrs<lmhlo::CeilOp>(instr); case HloOpcode::kCbrt: return CreateOpWithoutAttrs<lmhlo::CbrtOp>(instr); case HloOpcode::kClamp: return CreateOpWithoutAttrs<lmhlo::ClampOp>(instr); case HloOpcode::kCollectivePermute: return EmitCollectivePermuteOp(instr); case HloOpcode::kClz: return CreateOpWithoutAttrs<lmhlo::ClzOp>(instr); case HloOpcode::kCompare: return EmitCompareOp(instr); case HloOpcode::kComplex: return CreateOpWithoutAttrs<lmhlo::ComplexOp>(instr); case HloOpcode::kConcatenate: return EmitConcatenateOp(instr); case HloOpcode::kConvert: return CreateOpWithoutAttrs<lmhlo::ConvertOp>(instr); case HloOpcode::kCopy: return CreateOpWithoutAttrs<lmhlo::CopyOp>(instr); case HloOpcode::kCos: return CreateOpWithoutAttrs<lmhlo::CosOp>(instr); case HloOpcode::kDivide: return CreateOpWithoutAttrs<lmhlo::DivOp>(instr); case HloOpcode::kDot: return EmitDotOp(instr); case HloOpcode::kDynamicSlice: return EmitDynamicSliceOp(instr); case HloOpcode::kDynamicUpdateSlice: return CreateOpWithoutAttrs<lmhlo::DynamicUpdateSliceOp>(instr); case HloOpcode::kFft: return EmitFftOp(instr); case HloOpcode::kExp: return CreateOpWithoutAttrs<lmhlo::ExpOp>(instr); case HloOpcode::kExpm1: return CreateOpWithoutAttrs<lmhlo::Expm1Op>(instr); case HloOpcode::kFloor: return CreateOpWithoutAttrs<lmhlo::FloorOp>(instr); case HloOpcode::kGather: return EmitGatherOp(instr); case HloOpcode::kImag: return CreateOpWithoutAttrs<lmhlo::ImagOp>(instr); case HloOpcode::kInfeed: return EmitInfeedOp(instr); case HloOpcode::kIota: return EmitIotaOp(instr); case HloOpcode::kIsFinite: return CreateOpWithoutAttrs<lmhlo::IsFiniteOp>(instr); case HloOpcode::kLog: return CreateOpWithoutAttrs<lmhlo::LogOp>(instr); case HloOpcode::kLog1p: return CreateOpWithoutAttrs<lmhlo::Log1pOp>(instr); case HloOpcode::kMap: return EmitMapOp(instr); case HloOpcode::kMaximum: return CreateOpWithoutAttrs<lmhlo::MaxOp>(instr); case HloOpcode::kMinimum: return CreateOpWithoutAttrs<lmhlo::MinOp>(instr); case HloOpcode::kMultiply: return CreateOpWithoutAttrs<lmhlo::MulOp>(instr); case HloOpcode::kNegate: return CreateOpWithoutAttrs<lmhlo::NegOp>(instr); case HloOpcode::kNot: return CreateOpWithoutAttrs<lmhlo::NotOp>(instr); case HloOpcode::kOr: return CreateOpWithoutAttrs<lmhlo::OrOp>(instr); case HloOpcode::kOutfeed: return EmitOutfeedOp(instr); case HloOpcode::kPartitionId: return CreateOpWithoutAttrs<lmhlo::PartitionIdOp>(instr); case HloOpcode::kPad: return EmitPadOp(instr); case HloOpcode::kPopulationCount: return CreateOpWithoutAttrs<lmhlo::PopulationCountOp>(instr); case HloOpcode::kPower: return CreateOpWithoutAttrs<lmhlo::PowOp>(instr); case HloOpcode::kReal: return CreateOpWithoutAttrs<lmhlo::RealOp>(instr); case HloOpcode::kReshape: return CreateOpWithoutAttrs<lmhlo::ReshapeOp>(instr); case HloOpcode::kReducePrecision: return EmitReducePrecisionOp(instr); case HloOpcode::kReduceWindow: return EmitReduceWindowOp(instr); case HloOpcode::kRemainder: return CreateOpWithoutAttrs<lmhlo::RemOp>(instr); case HloOpcode::kReplicaId: return CreateOpWithoutAttrs<lmhlo::ReplicaIdOp>(instr); case HloOpcode::kReverse: return EmitReverseOp(instr); case HloOpcode::kRoundNearestAfz: return CreateOpWithoutAttrs<lmhlo::RoundOp>(instr); case HloOpcode::kRsqrt: return CreateOpWithoutAttrs<lmhlo::RsqrtOp>(instr); case HloOpcode::kSelect: return CreateOpWithoutAttrs<lmhlo::SelectOp>(instr); case HloOpcode::kShiftLeft: return CreateOpWithoutAttrs<lmhlo::ShiftLeftOp>(instr); case HloOpcode::kShiftRightLogical: return CreateOpWithoutAttrs<lmhlo::ShiftRightLogicalOp>(instr); case HloOpcode::kShiftRightArithmetic: return CreateOpWithoutAttrs<lmhlo::ShiftRightArithmeticOp>(instr); case HloOpcode::kSign: return CreateOpWithoutAttrs<lmhlo::SignOp>(instr); case HloOpcode::kSin: return CreateOpWithoutAttrs<lmhlo::SinOp>(instr); case HloOpcode::kSlice: return EmitSliceOp(instr); case HloOpcode::kSqrt: return CreateOpWithoutAttrs<lmhlo::SqrtOp>(instr); case HloOpcode::kSubtract: return CreateOpWithoutAttrs<lmhlo::SubOp>(instr); case HloOpcode::kTanh: return CreateOpWithoutAttrs<lmhlo::TanhOp>(instr); case HloOpcode::kTranspose: return EmitTransposeOp(instr); case HloOpcode::kTriangularSolve: return EmitTriangularSolveOp(instr); case HloOpcode::kXor: return CreateOpWithoutAttrs<lmhlo::XorOp>(instr); case HloOpcode::kSort: return EmitSortOp(instr); case HloOpcode::kFusion: return EmitFusionOp(instr); case HloOpcode::kScatter: return EmitScatterOp(instr); case HloOpcode::kSelectAndScatter: return EmitSelectAndScatterOp(instr); case HloOpcode::kCustomCall: return EmitCustomCallOp(instr); case HloOpcode::kConstant: return EmitConstant(instr); case HloOpcode::kReduce: return EmitReduceOp(instr); case HloOpcode::kRngGetAndUpdateState: return EmitRngGetAndUpdateStateOp(instr); default: llvm::errs() << instr->ToString(); return tensorflow::errors::Internal( absl::StrCat("LHLO opcode ", xla::HloOpcodeString(instr->opcode()), " is not supported.")); } } Status LhloDialectEmitter::DefaultAction(const HloInstruction* instr) { return EmitOp(instr).status(); } StatusOr<lmhlo::SortOp> LhloDialectEmitter::EmitSortOp( const HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto sort, CreateOpWithoutAttrs<lmhlo::SortOp>(instr)); auto* sort_instr = xla::Cast<xla::HloSortInstruction>(instr); sort.dimensionAttr(builder_.getI64IntegerAttr(sort_instr->sort_dimension())); sort.is_stableAttr(builder_.getBoolAttr(sort_instr->is_stable())); TF_RETURN_IF_ERROR(xla::HloFunctionImporter::ImportAsRegion( *sort_instr->called_computations()[0], &sort.comparator(), &builder_)); return sort; } // Walks MHLO::TupleOp recursively. Status WalkTuplePostOrder(Value v, const std::function<Status(Value)>& visitor) { if (auto* op = v.getDefiningOp()) { if (auto tuple = dyn_cast<mhlo::TupleOp>(op)) { for (Value sub_v : tuple.val()) { TF_RETURN_IF_ERROR(WalkTuplePostOrder(sub_v, visitor)); } return Status::OK(); } } return visitor(v); } // This function removes all uses of a fused region argument, and rewire those // uses to a `tensor_load %memref`, where %memref is caller argument. // // It also flattens all input/output tuples into more region arguments / // results. StatusOr<Value> LhloDialectEmitter::RewriteFusionOperand( const HloInstruction* root, const Shape& shape, xla::ShapeIndex* shape_index, OpBuilder* b, Location loc) { if (shape.IsTuple()) { llvm::SmallVector<Value, 4> values; for (int i = 0; i < shape.tuple_shapes_size(); ++i) { shape_index->push_back(i); TF_ASSIGN_OR_RETURN( auto v, RewriteFusionOperand(root, shape.tuple_shapes(i), shape_index, b, loc)); values.push_back(v); shape_index->pop_back(); } return Value(b->create<mhlo::TupleOp>(loc, values)); } TF_ASSIGN_OR_RETURN(Value memref, GetOrCreateArrayView(root, shape, *shape_index)); auto load = b->create<TensorLoadOp>(loc, memref); if (shape.layout() != xla::LayoutUtil::MakeDescendingLayout(shape.dimensions().size())) { llvm::SmallVector<int64_t, 4> minor_to_major( shape.layout().minor_to_major().begin(), shape.layout().minor_to_major().end()); load->setAttr("minor_to_major", GetLayoutAttribute(shape.layout(), b)); } return load.getResult(); } StatusOr<lmhlo::FusionOp> LhloDialectEmitter::EmitFusionOp( const HloInstruction* instr) { Location loc = getLocation(instr); auto* fusion_instr = xla::Cast<xla::HloFusionInstruction>(instr); auto fusion = builder_.create<lmhlo::FusionOp>(getLocation(instr)); auto after_fusion = builder_.saveInsertionPoint(); builder_ = mlir::OpBuilder(fusion); auto region_builder = OpBuilder::atBlockBegin(&fusion.region().front()); llvm::SmallVector<Value, 8> arguments; for (int i = 0; i < instr->operands().size(); ++i) { const HloInstruction* operand = instr->operand(i); xla::ShapeIndex shape_index; TF_ASSIGN_OR_RETURN( auto arg, RewriteFusionOperand(operand, operand->shape(), &shape_index, &region_builder, loc)); arguments.push_back(arg); } TF_ASSIGN_OR_RETURN(Value result, xla::HloFunctionImporter::ImportInstructions( *fusion_instr->fused_instructions_computation(), arguments, &region_builder)); { int i = 0; llvm::SmallVector<Value, 4> output; TF_RETURN_IF_ERROR(GetOrCreateView(instr, &output)); TF_RETURN_IF_ERROR(WalkTuplePostOrder(result, [&](Value v) mutable { region_builder.create<TensorStoreOp>(loc, v, output[i++]); return Status::OK(); })); if (i != output.size()) { return xla::InternalError("output sizes don't match"); } } // Fold GTE/Tuple pairs. // // Since the fused region refers to values in its parent region, we can't // call applyPatternAndFoldGreedily. We optimize it manually. // // Only walk once, because post-ordering is exactly what we need for GTE // optimizations. fusion.region().walk([](mhlo::GetTupleElementOp gte) { SmallVector<Value, 4> folded_values; if (succeeded(OpBuilder(gte).tryFold(gte, folded_values))) { gte.replaceAllUsesWith(folded_values[0]); } }); // Effectively a DCE on the region. { llvm::SmallVector<mlir::Operation*, 4> ops; fusion.region().walk([&](mlir::Operation* op) { ops.push_back(op); }); // Visit the user first. std::reverse(ops.begin(), ops.end()); for (auto op : ops) { if (isOpTriviallyDead(op)) op->erase(); } } builder_.restoreInsertionPoint(after_fusion); return fusion; } StatusOr<mhlo::ScatterDimensionNumbers> LhloDialectEmitter::GetScatterDimensionNumbers(const HloInstruction* instr) { auto* scatter_instr = xla::Cast<xla::HloScatterInstruction>(instr); const xla::ScatterDimensionNumbers& xla_scatter_dim = scatter_instr->scatter_dimension_numbers(); auto scatter_dimension_numbers = mhlo::ScatterDimensionNumbers::get( GetI64DenseElementsAttr(xla_scatter_dim.update_window_dims()), GetI64DenseElementsAttr(xla_scatter_dim.inserted_window_dims()), GetI64DenseElementsAttr(xla_scatter_dim.scatter_dims_to_operand_dims()), builder_.getI64IntegerAttr(xla_scatter_dim.index_vector_dim()), module_.getContext()); return scatter_dimension_numbers; } StatusOr<lmhlo::ScatterOp> LhloDialectEmitter::EmitScatterOp( const HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto scatter, CreateOpWithoutAttrs<lmhlo::ScatterOp>(instr)); // copy attributes auto* scatter_instr = xla::Cast<xla::HloScatterInstruction>(instr); TF_ASSIGN_OR_RETURN(auto scatter_dimension_numbers, GetScatterDimensionNumbers(instr)); scatter.scatter_dimension_numbersAttr(scatter_dimension_numbers); scatter.indices_are_sortedAttr( builder_.getBoolAttr(scatter_instr->indices_are_sorted())); scatter.unique_indicesAttr( builder_.getBoolAttr(scatter_instr->unique_indices())); // import update computation as region TF_RETURN_IF_ERROR(xla::HloFunctionImporter::ImportAsRegion( *scatter_instr->called_computations()[0], &scatter.update_computation(), &builder_)); return scatter; } StatusOr<lmhlo::SelectAndScatterOp> LhloDialectEmitter::EmitSelectAndScatterOp( const HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto select_and_scatter, CreateOpWithoutAttrs<lmhlo::SelectAndScatterOp>(instr)); // copy attributes auto* select_and_scatter_instr = xla::Cast<xla::HloSelectAndScatterInstruction>(instr); const xla::Window& window = select_and_scatter_instr->window(); select_and_scatter.window_dimensionsAttr( GetWindowElements(window, [](const xla::WindowDimension& dim) { return static_cast<int64_t>(dim.size()); })); select_and_scatter.window_stridesAttr( GetWindowElements(window, [](const xla::WindowDimension& dim) { return static_cast<int64_t>(dim.stride()); })); select_and_scatter.paddingAttr( GetWindowElements(window, [](const xla::WindowDimension& dim) { return static_cast<int64_t>(dim.padding_low()); })); // import select and scatter computation as region TF_RETURN_IF_ERROR(xla::HloFunctionImporter::ImportAsRegion( *select_and_scatter_instr->select(), &select_and_scatter.select(), &builder_)); TF_RETURN_IF_ERROR(xla::HloFunctionImporter::ImportAsRegion( *select_and_scatter_instr->scatter(), &select_and_scatter.scatter(), &builder_)); return select_and_scatter; } StatusOr<mlir::Operation*> LhloDialectEmitter::EmitCustomCallOp( const HloInstruction* instr) { auto* custom_call_instr = xla::Cast<xla::HloCustomCallInstruction>(instr); if (xla::gpu::IsCustomCallToCusolver(*instr)) { return EmitCholesky(custom_call_instr); } if (xla::gpu::IsCublasGemm(*instr)) { return EmitGemm(custom_call_instr); } if (xla::gpu::IsCustomCallToDnnConvolution(*instr)) { return EmitDnnConvolution(custom_call_instr); } if (xla::gpu::IsCustomCallToDnnBatchNorm(*instr)) { return EmitDnnBatchNorm(custom_call_instr); } size_t num_arguments, num_results; TF_ASSIGN_OR_RETURN(auto custom_call, CreateOpWithoutAttrs<lmhlo::CustomCallOp>( instr, num_arguments, num_results)); custom_call.call_target_nameAttr( builder_.getStringAttr(custom_call_instr->custom_call_target())); custom_call.backend_configAttr( builder_.getStringAttr(custom_call_instr->opaque())); const int32_t segments[2] = {static_cast<int32_t>(num_arguments), static_cast<int32_t>(num_results)}; custom_call->setAttr(lmhlo::CustomCallOp::getOperandSegmentSizeAttr(), builder_.getI32VectorAttr(segments)); return custom_call.getOperation(); } StatusOr<lmhlo_gpu::CholeskyOp> LhloDialectEmitter::EmitCholesky( const HloCustomCallInstruction* custom_call) { TF_ASSIGN_OR_RETURN(auto cholesky_op, CreateOpWithoutAttrs<lmhlo_gpu::CholeskyOp>(custom_call)); TF_ASSIGN_OR_RETURN(xla::CholeskyOptions options, custom_call->backend_config<xla::CholeskyOptions>()); cholesky_op.is_lowerAttr(builder_.getBoolAttr(options.lower())); return cholesky_op; } StatusOr<Operation*> LhloDialectEmitter::EmitGemm( const HloCustomCallInstruction* custom_call) { TF_ASSIGN_OR_RETURN( auto const config, custom_call->backend_config<xla::gpu::GemmBackendConfig>()); auto set_common_attributes = [&](auto op) -> Operation* { auto hlo_dims = config.dot_dimension_numbers(); auto mlir_dims = mhlo::DotDimensionNumbers::get( GetI64DenseElementsAttr(hlo_dims.lhs_batch_dimensions()), GetI64DenseElementsAttr(hlo_dims.rhs_batch_dimensions()), GetI64DenseElementsAttr(hlo_dims.lhs_contracting_dimensions()), GetI64DenseElementsAttr(hlo_dims.rhs_contracting_dimensions()), builder_.getContext()); op.dot_dimension_numbersAttr(mlir_dims); op.alpha_realAttr(builder_.getF64FloatAttr(config.alpha_real())); op.alpha_imagAttr(builder_.getF64FloatAttr(config.alpha_imag())); op.batch_sizeAttr(builder_.getI64IntegerAttr(config.batch_size())); if (config.algorithm_case() == xla::gpu::GemmBackendConfig::kSelectedAlgorithm) { op.algorithmAttr(builder_.getI64IntegerAttr(config.selected_algorithm())); } return op.getOperation(); }; if (custom_call->operand_count() == 2) { TF_ASSIGN_OR_RETURN(auto gemm, CreateOpWithoutAttrs<lmhlo_gpu::GEMMOp>(custom_call)); return set_common_attributes(gemm); } if (custom_call->operand_count() == 3) { TF_ASSIGN_OR_RETURN( auto gemm_bias, CreateOpWithoutAttrs<lmhlo_gpu::GEMM_BiasOp>(custom_call)); gemm_bias.betaAttr(builder_.getF64FloatAttr(config.beta())); return set_common_attributes(gemm_bias); } return xla::InvalidArgument("GEMM custom call should have 2 or 3 operands"); } static StatusOr<mlir::lmhlo_gpu::Activation> GetLHLOActivation( stream_executor::dnn::ActivationMode activation) { switch (activation) { case stream_executor::dnn::kNone: return mlir::lmhlo_gpu::Activation::None; case stream_executor::dnn::kSigmoid: return mlir::lmhlo_gpu::Activation::Sigmoid; case stream_executor::dnn::kRelu: return mlir::lmhlo_gpu::Activation::Relu; case stream_executor::dnn::kRelu6: return mlir::lmhlo_gpu::Activation::Relu6; case stream_executor::dnn::kReluX: return mlir::lmhlo_gpu::Activation::ReluX; case stream_executor::dnn::kTanh: return mlir::lmhlo_gpu::Activation::Tanh; case stream_executor::dnn::kBandPass: return mlir::lmhlo_gpu::Activation::BandPass; default: return xla::InternalError("Unknown activation"); } } StatusOr<Operation*> LhloDialectEmitter::EmitDnnConvolution( const HloCustomCallInstruction* custom_call) { TF_ASSIGN_OR_RETURN( auto const backend_config, custom_call->backend_config<xla::gpu::CudnnConvBackendConfig>()); TF_ASSIGN_OR_RETURN(const xla::gpu::CudnnConvKind kind, xla::gpu::GetCudnnConvKind(custom_call)); auto get_layout_attribute = [&](const xla::Layout& layout) { std::vector<int64_t> minor_to_major(layout.minor_to_major_size()); absl::c_transform(layout.minor_to_major(), minor_to_major.begin(), [](xla::int64 x) { return static_cast<int64_t>(x); }); return builder_.getI64ArrayAttr(minor_to_major); }; auto set_common_conv_attributes = [&, this](auto op) -> Operation* { const xla::Window& window = custom_call->window(); // Window size for Cudnn Conv is same as the kernel size. op.window_stridesAttr( GetWindowElements(window, [](const xla::WindowDimension& dim) { return static_cast<int64_t>(dim.stride()); })); // Cudnn Conv requires low and high padding to be equal. op.paddingAttr( GetWindowElements(window, [](const xla::WindowDimension& dim) { return static_cast<int64_t>(dim.padding_low()); })); // LHS dilation is encoded in base_dilation of the backend config. // RHS dilation is encoded in window_dilation of the backend config. op.lhs_dilationAttr( GetWindowElements(window, [](const xla::WindowDimension& dim) { return static_cast<int64_t>(dim.base_dilation()); })); op.rhs_dilationAttr( GetWindowElements(window, [](const xla::WindowDimension& dim) { return static_cast<int64_t>(dim.window_dilation()); })); // Setup window reversal. auto window_reversal = llvm::to_vector<4>(llvm::map_range( window.dimensions(), [](const xla::WindowDimension& dim) { return dim.window_reversal(); })); auto type = RankedTensorType::get(op.window_strides()->getType().getShape(), builder_.getIntegerType(/*width=*/1)); op.window_reversalAttr(DenseElementsAttr::get(type, window_reversal)); op.dimension_numbersAttr(xla::ConvertConvDimensionNumbers( custom_call->convolution_dimension_numbers(), &builder_)); op.feature_group_countAttr( builder_.getI64IntegerAttr(custom_call->feature_group_count())); op.batch_group_countAttr( builder_.getI64IntegerAttr(custom_call->batch_group_count())); op.precision_configAttr(xla::ConvertPrecisionConfig( &custom_call->precision_config(), &builder_)); op.result_scaleAttr( builder_.getF64FloatAttr(backend_config.conv_result_scale())); auto config = mlir::lmhlo_gpu::ConvolutionBackendConfig::get( builder_.getI64IntegerAttr(backend_config.algorithm()), builder_.getBoolAttr(backend_config.tensor_ops_enabled()), get_layout_attribute(custom_call->operand(0)->shape().layout()), get_layout_attribute(custom_call->operand(1)->shape().layout()), get_layout_attribute(custom_call->shape().tuple_shapes(0).layout()), builder_.getContext()); op.backend_configAttr(config); return op.getOperation(); }; auto set_activation = [&, this](auto op) -> Status { auto se_activation = static_cast<stream_executor::dnn::ActivationMode>( backend_config.activation_mode()); TF_ASSIGN_OR_RETURN(mlir::lmhlo_gpu::Activation activation, GetLHLOActivation(se_activation)); StringAttr activation_attr = builder_.getStringAttr( mlir::lmhlo_gpu::stringifyActivation(activation)); op.activation_modeAttr(activation_attr); return Status::OK(); }; switch (kind) { case xla::gpu::CudnnConvKind::kForward: { TF_ASSIGN_OR_RETURN( auto cnn_forward, CreateOpWithoutAttrs<lmhlo_gpu::ConvForwardOp>(custom_call)); return set_common_conv_attributes(cnn_forward); } case xla::gpu::CudnnConvKind::kBackwardInput: { TF_ASSIGN_OR_RETURN( auto cnn_backward, CreateOpWithoutAttrs<lmhlo_gpu::ConvBackwardInputOp>(custom_call)); return set_common_conv_attributes(cnn_backward); } case xla::gpu::CudnnConvKind::kBackwardFilter: { TF_ASSIGN_OR_RETURN( auto cnn_backward, CreateOpWithoutAttrs<lmhlo_gpu::ConvBackwardFilterOp>(custom_call)); return set_common_conv_attributes(cnn_backward); } case xla::gpu::CudnnConvKind::kForwardActivation: { // Fused conv can be either with side input or without. if (custom_call->operand_count() == 3) { TF_ASSIGN_OR_RETURN( auto cnn_fused, CreateOpWithoutAttrs<lmhlo_gpu::ConvForwardFusedOp>(custom_call)); TF_RETURN_IF_ERROR(set_activation(cnn_fused)); return set_common_conv_attributes(cnn_fused); } TF_RET_CHECK(custom_call->operand_count() == 4); TF_ASSIGN_OR_RETURN( auto cnn_fused_side_input, CreateOpWithoutAttrs<lmhlo_gpu::ConvForwardFusedSideInputOp>( custom_call)); cnn_fused_side_input.side_input_scaleAttr( builder_.getF64FloatAttr(backend_config.side_input_scale())); TF_RETURN_IF_ERROR(set_activation(cnn_fused_side_input)); return set_common_conv_attributes(cnn_fused_side_input); } } } StatusOr<Operation*> LhloDialectEmitter::EmitDnnBatchNorm( const HloCustomCallInstruction* custom_call) { const xla::int64 num_operands = custom_call->operand_count(); auto set_batchnorm_attributes = [&](auto op) -> StatusOr<Operation*> { // The last 2 operands of a custom call for batch norm are the epsilon and // feature_index. const HloInstruction* epsilon = custom_call->operand(num_operands - 2); TF_RET_CHECK(epsilon->IsConstant()); float epsilon_value = epsilon->literal().Get<float>({}); const HloInstruction* feature_index = custom_call->operand(num_operands - 1); TF_RET_CHECK(feature_index->IsConstant()); xla::int64 feature_index_value = feature_index->literal().Get<xla::int64>({}); op.epsilonAttr(builder_.getF32FloatAttr(epsilon_value)); op.feature_indexAttr(builder_.getI64IntegerAttr(feature_index_value)); return op.getOperation(); }; const std::string& target = custom_call->custom_call_target(); if (target == xla::gpu::kCudnnBatchNormForwardTrainingCallTarget) { TF_ASSIGN_OR_RETURN(auto fwd_training, CreateOpWithoutAttrs<lmhlo_gpu::BatchNormTrainingOp>( custom_call, num_operands - 2)); return set_batchnorm_attributes(fwd_training); } if (target == xla::gpu::kCudnnBatchNormBackwardCallTarget) { TF_ASSIGN_OR_RETURN(auto backward, CreateOpWithoutAttrs<lmhlo_gpu::BatchNormGradOp>( custom_call, num_operands - 2)); return set_batchnorm_attributes(backward); } if (target == xla::gpu::kCudnnBatchNormForwardInferenceCallTarget) { TF_ASSIGN_OR_RETURN(auto fwd_inference, CreateOpWithoutAttrs<lmhlo_gpu::BatchNormInferenceOp>( custom_call, num_operands - 2)); return set_batchnorm_attributes(fwd_inference); } return xla::Unimplemented("Unsupported batch norm operation"); } // Convert an XLA HLO constant to a global_memref + get_global_memref pair. StatusOr<mlir::GetGlobalMemrefOp> LhloDialectEmitter::EmitConstant( const HloInstruction* instr) { // Insert a global_memref in the module. Location loc = getLocation(instr); auto const_instr = xla::Cast<xla::HloConstantInstruction>(instr); TF_RET_CHECK(const_instr->shape().IsArray() && const_instr->shape().is_static()); TF_ASSIGN_OR_RETURN(Type type, xla::ConvertShapeToType<MemRefType>( const_instr->shape(), builder_)); auto memref_type = type.dyn_cast<MemRefType>(); TF_RET_CHECK(memref_type != nullptr); TF_ASSIGN_OR_RETURN( DenseElementsAttr initial_value, CreateDenseElementsAttrFromLiteral(const_instr->literal(), builder_)); std::string constant_name = xla::llvm_ir::ConstantNameToGlobalName( xla::llvm_ir::SanitizeConstantName(instr->name())); // Insert the global memref at the top level. { OpBuilder::InsertionGuard guard(builder_); builder_.clearInsertionPoint(); auto global_var = builder_.create<GlobalMemrefOp>( loc, constant_name, builder_.getStringAttr("private"), TypeAttr::get(memref_type), initial_value, true); SymbolTable(module_).insert(global_var); global_var.getOperation()->moveBefore(&module_.front()); // For operations that do not fold this constant value in their codegen, we // still need to materialize it into a buffer. Since buffer allocation is // already done, annotate the global_memref with the information to get to // the allocated buffer slice for this constant if need be. TF_ASSIGN_OR_RETURN(BufferAllocation::Slice slice, assignment_.GetUniqueTopLevelSlice(instr)); global_var->setAttr("lmhlo.alloc", builder_.getIndexAttr(slice.index())); TF_RET_CHECK(slice.offset() == 0) << "Each constant should have its own allocation from BufferAssignment"; TF_RET_CHECK(slice.allocation()->size() == slice.size()) << "Each constant should have its own allocation from BufferAssignment"; } auto get_global_memref = builder_.create<GetGlobalMemrefOp>(loc, memref_type, constant_name); // Update the cache to remember this value. auto& cached_value = slices_[std::make_pair(instr, xla::ShapeIndex())]; TF_RET_CHECK(cached_value == nullptr); cached_value = get_global_memref; return get_global_memref; } StatusOr<lmhlo::ReduceOp> LhloDialectEmitter::EmitReduceOp( const HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto reduce_op, CreateOpWithoutAttrs<lmhlo::ReduceOp>(instr)); auto* reduce = xla::Cast<xla::HloReduceInstruction>(instr); std::vector<int64_t> dimensions(reduce->dimensions().begin(), reduce->dimensions().end()); reduce_op.dimensionsAttr(GetI64DenseElementsAttr(dimensions)); TF_RETURN_IF_ERROR(xla::HloFunctionImporter::ImportAsRegion( *instr->called_computations()[0], &reduce_op.body(), &builder_)); return reduce_op; } StatusOr<lmhlo::MapOp> LhloDialectEmitter::EmitMapOp( const HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto map_op, CreateOpWithoutAttrs<lmhlo::MapOp>(instr)); auto* map = xla::Cast<xla::HloMapInstruction>(instr); std::vector<int64_t> dimensions(map->dimensions().begin(), map->dimensions().end()); map_op.dimensionsAttr(GetI64DenseElementsAttr(dimensions)); TF_RETURN_IF_ERROR(xla::HloFunctionImporter::ImportAsRegion( *instr->called_computations()[0], &map_op.computation(), &builder_)); return map_op; } StatusOr<lmhlo::CompareOp> LhloDialectEmitter::EmitCompareOp( const HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto compare_op, CreateOpWithoutAttrs<lmhlo::CompareOp>(instr)); auto* compare = xla::Cast<xla::HloCompareInstruction>(instr); auto direction = [&]() { switch (compare->direction()) { case xla::ComparisonDirection::kEq: return mhlo::ComparisonDirection::EQ; case xla::ComparisonDirection::kNe: return mhlo::ComparisonDirection::NE; case xla::ComparisonDirection::kGe: return mhlo::ComparisonDirection::GE; case xla::ComparisonDirection::kGt: return mhlo::ComparisonDirection::GT; case xla::ComparisonDirection::kLe: return mhlo::ComparisonDirection::LE; case xla::ComparisonDirection::kLt: return mhlo::ComparisonDirection::LT; } }(); compare_op.comparison_directionAttr( builder_.getStringAttr(stringifyComparisonDirection(direction))); auto compare_type = [&]() { switch (compare->type()) { case xla::Comparison::Type::kFloat: return mhlo::ComparisonType::FLOAT; case xla::Comparison::Type::kFloatTotalOrder: return mhlo::ComparisonType::TOTALORDER; case xla::Comparison::Type::kSigned: return mhlo::ComparisonType::SIGNED; case xla::Comparison::Type::kUnsigned: return mhlo::ComparisonType::UNSIGNED; } }(); compare_op.compare_typeAttr( builder_.getStringAttr(stringifyComparisonType(compare_type))); return compare_op; } StatusOr<lmhlo::ReducePrecisionOp> LhloDialectEmitter::EmitReducePrecisionOp( const HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto reduce_precision_op, CreateOpWithoutAttrs<lmhlo::ReducePrecisionOp>(instr)); auto* reduce_precision = xla::Cast<xla::HloReducePrecisionInstruction>(instr); reduce_precision_op.exponent_bitsAttr( builder_.getI32IntegerAttr(reduce_precision->exponent_bits())); reduce_precision_op.mantissa_bitsAttr( builder_.getI32IntegerAttr(reduce_precision->mantissa_bits())); return reduce_precision_op; } namespace { template <typename OpT> void SetupChannelIdAttribute(OpT op, const xla::HloChannelInstruction* instr, mlir::Builder builder) { if (instr->channel_id().has_value()) { op.channel_idAttr(mlir::mhlo::ChannelHandle::get( builder.getI64IntegerAttr(*instr->channel_id()), builder.getI64IntegerAttr(0), builder.getContext())); } } template <typename OpT> Status SetupCommonCollectiveOpAttributes(OpT op, const HloInstruction* instr, mlir::OpBuilder& builder) { auto* collective = xla::Cast<xla::HloCollectiveInstruction>(instr); auto replica_groups_attr = xla::HloFunctionImporter::ConvertReplicaGroups( collective->replica_groups(), &builder); op->setAttr(replica_groups_attr.first, replica_groups_attr.second); op.constrain_layoutAttr(builder.getBoolAttr(collective->constrain_layout())); SetupChannelIdAttribute(op, collective, builder); return Status::OK(); } } // namespace StatusOr<lmhlo::AllToAllOp> LhloDialectEmitter::EmitAllToAllOp( const HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto all_to_all_op, CreateOpWithoutAttrs<lmhlo::AllToAllOp>(instr)); auto* all_to_all = xla::Cast<xla::HloAllToAllInstruction>(instr); TF_RETURN_IF_ERROR( SetupCommonCollectiveOpAttributes(all_to_all_op, instr, builder_)); if (all_to_all->split_dimension().has_value()) { all_to_all_op.split_dimensionAttr( builder_.getI64IntegerAttr(*all_to_all->split_dimension())); } return all_to_all_op; } StatusOr<lmhlo::AllGatherOp> LhloDialectEmitter::EmitAllGatherOp( const HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto all_gather_op, CreateOpWithoutAttrs<lmhlo::AllGatherOp>(instr)); auto* all_gather = xla::Cast<xla::HloAllGatherInstruction>(instr); TF_RETURN_IF_ERROR( SetupCommonCollectiveOpAttributes(all_gather_op, instr, builder_)); all_gather_op.use_global_device_idsAttr( builder_.getBoolAttr(all_gather->use_global_device_ids())); all_gather_op.all_gather_dimensionAttr( builder_.getI64IntegerAttr(all_gather->all_gather_dimension())); return all_gather_op; } StatusOr<lmhlo::AllReduceOp> LhloDialectEmitter::EmitAllReduceOp( const HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto all_reduce_op, CreateOpWithoutAttrs<lmhlo::AllReduceOp>(instr)); auto* all_reduce = xla::Cast<xla::HloAllReduceInstruction>(instr); TF_RETURN_IF_ERROR( SetupCommonCollectiveOpAttributes(all_reduce_op, instr, builder_)); all_reduce_op.use_global_device_idsAttr( builder_.getBoolAttr(all_reduce->use_global_device_ids())); TF_RETURN_IF_ERROR(xla::HloFunctionImporter::ImportAsRegion( *instr->called_computations()[0], &all_reduce_op.computation(), &builder_)); return all_reduce_op; } StatusOr<lmhlo::CollectivePermuteOp> LhloDialectEmitter::EmitCollectivePermuteOp(const HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto permute_op, CreateOpWithoutAttrs<lmhlo::CollectivePermuteOp>(instr)); auto* permute = xla::Cast<xla::HloCollectivePermuteInstruction>(instr); SetupChannelIdAttribute(permute_op, permute, builder_); mlir::NamedAttribute source_target_pairs_attr = xla::HloFunctionImporter::ConvertSourceTargetPairs( permute->source_target_pairs(), &builder_); permute_op->setAttr(source_target_pairs_attr.first, source_target_pairs_attr.second); return permute_op; } StatusOr<lmhlo::InfeedOp> LhloDialectEmitter::EmitInfeedOp( const HloInstruction* instr) { const HloInfeedInstruction* infeed = xla::Cast<HloInfeedInstruction>(instr); // HLO Infeed instruction has a single operand of token type and a tuple // with buffers and a token as its output. LMHLO Infeed operation does not // need the token operand or result, so drop it. SmallVector<Value, 2> operands; TF_RETURN_IF_ERROR(GetOrCreateView(instr, &operands, /*result_subset=*/{0})); auto infeed_op = CreateOpWithoutAttrs<lmhlo::InfeedOp>(instr, operands); infeed_op.configAttr(builder_.getStringAttr(infeed->infeed_config())); return infeed_op; } StatusOr<lmhlo::OutfeedOp> LhloDialectEmitter::EmitOutfeedOp( const HloInstruction* instr) { const HloOutfeedInstruction* outfeed = xla::Cast<HloOutfeedInstruction>(instr); // HLO outfeed instruction has 2 operands, the source and a token, and a // single token output. LMHLO Outfeed does not need the token operand and // result, do drop it. SmallVector<Value, 2> operands; TF_RETURN_IF_ERROR(GetOrCreateView(instr->operand(0), &operands)); auto outfeed_op = CreateOpWithoutAttrs<lmhlo::OutfeedOp>(instr, operands); outfeed_op.configAttr(builder_.getStringAttr(outfeed->outfeed_config())); return outfeed_op; } xla::StatusOr<lmhlo::BroadcastInDimOp> LhloDialectEmitter::EmitBroadcastOp( const xla::HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto broadcast, CreateOpWithoutAttrs<lmhlo::BroadcastInDimOp>(instr)); broadcast.broadcast_dimensionsAttr( builder_.getI64TensorAttr(instr->dimensions())); return broadcast; } xla::StatusOr<lmhlo::ConcatenateOp> LhloDialectEmitter::EmitConcatenateOp( const xla::HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto concat, CreateOpWithoutAttrs<lmhlo::ConcatenateOp>(instr)); auto hlo_concat = xla::Cast<xla::HloConcatenateInstruction>(instr); concat.dimensionAttr( builder_.getI64IntegerAttr(hlo_concat->concatenate_dimension())); return concat; } xla::StatusOr<lmhlo::IotaOp> LhloDialectEmitter::EmitIotaOp( const xla::HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto iota, CreateOpWithoutAttrs<lmhlo::IotaOp>(instr)); auto hlo_iota = xla::Cast<xla::HloIotaInstruction>(instr); iota.iota_dimensionAttr( builder_.getI64IntegerAttr(hlo_iota->iota_dimension())); return iota; } xla::StatusOr<lmhlo::ReverseOp> LhloDialectEmitter::EmitReverseOp( const xla::HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto reverse, CreateOpWithoutAttrs<lmhlo::ReverseOp>(instr)); reverse.dimensionsAttr(builder_.getI64TensorAttr(instr->dimensions())); return reverse; } xla::StatusOr<lmhlo::TransposeOp> LhloDialectEmitter::EmitTransposeOp( const xla::HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto transpose, CreateOpWithoutAttrs<lmhlo::TransposeOp>(instr)); transpose.permutationAttr(builder_.getI64TensorAttr(instr->dimensions())); return transpose; } xla::StatusOr<lmhlo::PadOp> LhloDialectEmitter::EmitPadOp( const xla::HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto pad, CreateOpWithoutAttrs<lmhlo::PadOp>(instr)); auto hlo_pad = xla::Cast<xla::HloPadInstruction>(instr); std::vector<xla::int64> low, high, interior; for (const auto& dim : hlo_pad->padding_config().dimensions()) { low.push_back(dim.edge_padding_low()); high.push_back(dim.edge_padding_high()); interior.push_back(dim.interior_padding()); } pad.edge_padding_lowAttr(builder_.getI64TensorAttr(low)); pad.edge_padding_highAttr(builder_.getI64TensorAttr(high)); pad.interior_paddingAttr(builder_.getI64TensorAttr(interior)); return pad; } xla::StatusOr<lmhlo::ReduceWindowOp> LhloDialectEmitter::EmitReduceWindowOp( const xla::HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto reduce_window, CreateOpWithoutAttrs<lmhlo::ReduceWindowOp>(instr)); auto hlo_reduce_window = xla::Cast<xla::HloReduceWindowInstruction>(instr); std::vector<xla::int64> dims, strides, base_dilations, window_dilations, paddings; for (const auto& dim : hlo_reduce_window->window().dimensions()) { dims.push_back(dim.size()); strides.push_back(dim.stride()); base_dilations.push_back(dim.base_dilation()); window_dilations.push_back(dim.window_dilation()); paddings.push_back(dim.padding_low()); paddings.push_back(dim.padding_high()); } reduce_window.window_dimensionsAttr(builder_.getI64TensorAttr(dims)); if (xla::window_util::HasStride(hlo_reduce_window->window())) { reduce_window.window_stridesAttr(builder_.getI64TensorAttr(strides)); } if (xla::window_util::HasBaseDilation(hlo_reduce_window->window())) { reduce_window.base_dilationsAttr(builder_.getI64TensorAttr(base_dilations)); } if (xla::window_util::HasWindowDilation(hlo_reduce_window->window())) { reduce_window.window_dilationsAttr( builder_.getI64TensorAttr(window_dilations)); } CHECK_EQ(0, paddings.size() % 2); if (xla::window_util::HasPadding(hlo_reduce_window->window())) { reduce_window.paddingAttr(DenseIntElementsAttr::get( RankedTensorType::get({static_cast<int64_t>(paddings.size() / 2), 2}, builder_.getIntegerType(64)), paddings)); } TF_RETURN_IF_ERROR(xla::HloFunctionImporter::ImportAsRegion( *hlo_reduce_window->called_computations()[0], &reduce_window.body(), &builder_)); return reduce_window; } xla::StatusOr<lmhlo::SliceOp> LhloDialectEmitter::EmitSliceOp( const xla::HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto slice, CreateOpWithoutAttrs<lmhlo::SliceOp>(instr)); auto hlo_slice = xla::Cast<xla::HloSliceInstruction>(instr); slice.start_indicesAttr(builder_.getI64TensorAttr(hlo_slice->slice_starts())); slice.limit_indicesAttr(builder_.getI64TensorAttr(hlo_slice->slice_limits())); slice.stridesAttr(builder_.getI64TensorAttr(hlo_slice->slice_strides())); return slice; } xla::StatusOr<lmhlo::GatherOp> LhloDialectEmitter::EmitGatherOp( const xla::HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto gather, CreateOpWithoutAttrs<lmhlo::GatherOp>(instr)); auto hlo_gather = xla::Cast<xla::HloGatherInstruction>(instr); gather.dimension_numbersAttr(xla::ConvertGatherDimensionNumbers( hlo_gather->gather_dimension_numbers(), &builder_)); gather.slice_sizesAttr(builder_.getI64TensorAttr( std::vector<int64_t>(hlo_gather->gather_slice_sizes().begin(), hlo_gather->gather_slice_sizes().end()))); return gather; } xla::StatusOr<lmhlo::DynamicSliceOp> LhloDialectEmitter::EmitDynamicSliceOp( const xla::HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto dynamic_slice, CreateOpWithoutAttrs<lmhlo::DynamicSliceOp>(instr)); auto hlo_dynamic_slice = xla::Cast<xla::HloDynamicSliceInstruction>(instr); dynamic_slice.slice_sizesAttr( builder_.getI64TensorAttr(hlo_dynamic_slice->dynamic_slice_sizes())); return dynamic_slice; } xla::StatusOr<lmhlo::DotOp> LhloDialectEmitter::EmitDotOp( const xla::HloInstruction* instr) { TF_ASSIGN_OR_RETURN(auto dot, CreateOpWithoutAttrs<lmhlo::DotOp>(instr)); auto hlo_dot = xla::Cast<xla::HloDotInstruction>(instr); dot.dot_dimension_numbersAttr(xla::ConvertDotDimensionNumbers( hlo_dot->dot_dimension_numbers(), &builder_)); dot.precision_configAttr( xla::ConvertPrecisionConfig(&hlo_dot->precision_config(), &builder_)); return dot; } xla::StatusOr<lmhlo::RngGetAndUpdateStateOp> LhloDialectEmitter::EmitRngGetAndUpdateStateOp( const xla::HloInstruction* instr) { TF_ASSIGN_OR_RETURN( auto rng, CreateOpWithoutAttrs<lmhlo::RngGetAndUpdateStateOp>(instr)); auto hlo_rng = xla::Cast<xla::HloRngGetAndUpdateStateInstruction>(instr); rng.deltaAttr(builder_.getI64IntegerAttr(hlo_rng->delta())); return rng; } xla::StatusOr<lmhlo::FftOp> LhloDialectEmitter::EmitFftOp( const HloInstruction* instr) { auto hlo_fft = xla::Cast<xla::HloFftInstruction>(instr); TF_ASSIGN_OR_RETURN(auto fft, CreateOpWithoutAttrs<lmhlo::FftOp>(instr)); TF_ASSIGN_OR_RETURN(mlir::mhlo::FftType fft_type, xla::ConvertFftType(hlo_fft->fft_type())); StringAttr fft_type_attr = builder_.getStringAttr(mlir::mhlo::stringifyFftType(fft_type)); fft.fft_typeAttr(fft_type_attr); fft.fft_lengthAttr(GetI64DenseElementsAttr(instr->fft_length())); return fft; } xla::StatusOr<lmhlo::TriangularSolveOp> LhloDialectEmitter::EmitTriangularSolveOp(const xla::HloInstruction* instr) { auto hlo_triangular_solve = xla::Cast<xla::HloTriangularSolveInstruction>(instr); TF_ASSIGN_OR_RETURN(auto triangular_solve, CreateOpWithoutAttrs<lmhlo::TriangularSolveOp>(instr)); const xla::TriangularSolveOptions& options = hlo_triangular_solve->triangular_solve_options(); triangular_solve.left_sideAttr(builder_.getBoolAttr(options.left_side())); triangular_solve.lowerAttr(builder_.getBoolAttr(options.lower())); triangular_solve.unit_diagonalAttr( builder_.getBoolAttr(options.unit_diagonal())); TF_ASSIGN_OR_RETURN(mlir::mhlo::Transpose transpose, xla::ConvertTranspose(options.transpose_a())); triangular_solve.transpose_aAttr( builder_.getStringAttr(mlir::mhlo::stringifyTranspose(transpose))); triangular_solve.layout_aAttr( GetLayoutAttribute(instr->operand(0)->shape().layout(), &builder_)); triangular_solve.layout_bAttr( GetLayoutAttribute(instr->operand(1)->shape().layout(), &builder_)); triangular_solve.layout_outputAttr( GetLayoutAttribute(instr->shape().layout(), &builder_)); return triangular_solve; } mlir::DenseIntElementsAttr LhloDialectEmitter::GetLayoutAttribute( const xla::Layout& layout, Builder* builder) { llvm::SmallVector<int64_t, 4> minor_to_major(layout.minor_to_major().begin(), layout.minor_to_major().end()); return builder->getIndexTensorAttr(minor_to_major); } StatusOr<Value> LhloDialectEmitter::GetOrCreateArrayView( const xla::HloInstruction* instr, const xla::Shape& current_shape, const xla::ShapeIndex& shape_index) { // Cache generated ViewOp and StaticMemRefCastOp by (instruction, // shape_index). auto& cached_value = slices_[std::make_pair(instr, shape_index)]; if (cached_value) { return cached_value; } if (instr->IsConstant() && shape_index.empty()) { TF_ASSIGN_OR_RETURN(Value constant_memref, EmitConstant(instr)); return cached_value = constant_memref; } // If the shape happens to have dynamic dimensions, create the memref using // the underlying static shape. // TODO(jurahul): Revisit this when we can model memrefs with dynamic shape // but static bounds in MLIR. const Shape static_shape = xla::ShapeUtil::MakeStaticShape(current_shape); TF_ASSIGN_OR_RETURN(Type out_type, xla::ConvertShapeToType<MemRefType>( static_shape, builder_)); TF_ASSIGN_OR_RETURN(BufferAllocation::Slice slice, assignment_.GetUniqueSlice(instr, shape_index)); Value alloc = allocations_[slice.allocation()]; if (alloc.getType() == out_type && slice.offset() == 0) { return cached_value = alloc; } auto out_memref_type = out_type.dyn_cast<MemRefType>(); if (!out_memref_type) return tensorflow::errors::Internal( "Expected memref type when creating a view for leaf type of a " "tuple."); Value byte_shift = builder_.create<ConstantIndexOp>(alloc.getLoc(), slice.offset()); xla::Shape physical_shape = xla::ShapeUtil::MakeShapeWithDescendingLayoutAndSamePhysicalLayout( static_shape); TF_ASSIGN_OR_RETURN( Type physical_out_type, xla::ConvertShapeToType<MemRefType>(physical_shape, builder_)); // TODO(timshen): revisit location handling. Location loc = builder_.getUnknownLoc(); // ViewOp only takes memrefs without affine maps (layouts). Let ViewOp produce // the physical shape (where dimensions are ordered in major to minor) first, // then follow up with a MemRefReinterpretCast to cast the resulting memref to // the original layout. Value result = builder_.create<ViewOp>(loc, physical_out_type, alloc, byte_shift, /*sizes=*/ValueRange{}); if (physical_out_type != out_type) { int64_t out_offset; SmallVector<int64_t, 4> out_strides; if (failed(getStridesAndOffset(out_memref_type, out_strides, out_offset))) return tensorflow::errors::Internal( "Failed to get strides and offset from the output type."); result = builder_.create<MemRefReinterpretCastOp>( loc, out_memref_type, result, out_offset, out_memref_type.getShape(), out_strides); } return cached_value = result; } Status LhloDialectEmitter::GetOrCreateViewImpl( const HloInstruction* instr, const Shape& current_shape, xla::ShapeIndex* current_shape_index, SmallVectorImpl<Value>* values) { if (current_shape.IsTuple()) { for (int i = 0; i < current_shape.tuple_shapes().size(); ++i) { current_shape_index->push_back(i); TF_RETURN_IF_ERROR(GetOrCreateViewImpl( instr, current_shape.tuple_shapes(i), current_shape_index, values)); current_shape_index->pop_back(); } return Status::OK(); } if (current_shape.IsArray()) { TF_ASSIGN_OR_RETURN(auto v, GetOrCreateArrayView(instr, current_shape, *current_shape_index)); values->push_back(v); return Status::OK(); } return xla::InternalError("Unexpected shape kind for %s and shape index %s", instr->ToString(), current_shape_index->ToString()); } // Returns a view for the result of an instruction. // We first get a view for the slice in the allocation, and then may need to // create another view to adjust the slice for the shape of the instruction. Status LhloDialectEmitter::GetOrCreateView( const HloInstruction* instr, SmallVectorImpl<Value>* values, const xla::ShapeIndex& result_subset) { xla::ShapeIndex shape_index = result_subset; const Shape& sub_shape = xla::ShapeUtil::GetSubshape(instr->shape(), shape_index); return GetOrCreateViewImpl(instr, sub_shape, &shape_index, values); } Status LhloDialectEmitter::Initialize() { mlir::IntegerAttr unique_id = builder_.getI32IntegerAttr(computation_.parent()->unique_id()); module_->setAttr("hlo.unique_id", unique_id); std::string function_name = computation_.name().empty() ? "__compute" : computation_.name(); // Create the function as () -> (), we'll compute the arguments from the // buffer allocation and update the type then. auto func_op = FuncOp::create(builder_.getUnknownLoc(), function_name, builder_.getFunctionType({}, {})); Block* block = func_op.addEntryBlock(); llvm::SmallVector<const BufferAllocation*, 8> ordered_allocations; for (const BufferAllocation& alloc : assignment_.Allocations()) ordered_allocations.push_back(&alloc); if (computation_.IsEntryComputation()) { // Sort the rather arbitrarily ordered allocations to match the input/output // parameters. Specifically we want to sort buffer allocations in the // following order: // * Parameters always order before non-parameters. // * Different parameters order by parameter number. // * Different allocations for the same parameter order by the shape index. // // TODO(timshen): there should be only one non-parameter buffer, the temp // buffer. Check on that. const auto allocation_comparator = [](const BufferAllocation* lhs, const BufferAllocation* rhs) { if (lhs->is_entry_computation_parameter() != rhs->is_entry_computation_parameter()) { return lhs->is_entry_computation_parameter() > rhs->is_entry_computation_parameter(); } if (lhs->is_entry_computation_parameter()) { return std::tuple<int, const xla::ShapeIndex&>( lhs->parameter_number(), lhs->param_shape_index()) < std::tuple<int, const xla::ShapeIndex&>( rhs->parameter_number(), rhs->param_shape_index()); } return false; }; std::stable_sort(ordered_allocations.begin(), ordered_allocations.end(), allocation_comparator); } // The function signature will be composed of: // - one memref for each of the parameters. // - one memref for each other buffer allocation. llvm::SmallVector<DictionaryAttr, 8> args_attrs; for (const BufferAllocation* alloc : ordered_allocations) { if (computation_.IsEntryComputation() && alloc->is_entry_computation_parameter()) { const xla::Shape& buffer_shape = xla::ShapeUtil::GetSubshape( computation_.parameter_instruction(alloc->parameter_number()) ->shape(), alloc->param_shape_index()); TF_ASSIGN_OR_RETURN(auto arg_type, xla::ConvertShapeToType<MemRefType>( buffer_shape, builder_)); // First map parameters to memrefs on the operation. block->addArgument(arg_type); allocations_[alloc] = block->getArguments().back(); NamedAttrList arg_attr_list; arg_attr_list.set("lmhlo.alloc", builder_.getIndexAttr(alloc->index())); arg_attr_list.set("lmhlo.params", builder_.getIndexAttr(alloc->parameter_number())); args_attrs.push_back(arg_attr_list.getDictionary(builder_.getContext())); } else { block->addArgument(MemRefType::get({alloc->size()}, i8_type_)); allocations_[alloc] = block->getArguments().back(); NamedAttrList arg_attr_list; arg_attr_list.set("lmhlo.alloc", builder_.getIndexAttr(alloc->index())); arg_attr_list.set("lmhlo.liveout", builder_.getBoolAttr(true)); args_attrs.push_back(arg_attr_list.getDictionary(builder_.getContext())); } } FunctionType function_type = builder_.getFunctionType(block->getArgumentTypes(), {}); func_op.setType(function_type); func_op.setAllArgAttrs(args_attrs); SymbolTable symbol_table(module_); symbol_table.insert(func_op); builder_.setInsertionPointToEnd(block); auto return_op = builder_.create<ReturnOp>(builder_.getUnknownLoc()); builder_ = OpBuilder(return_op); return Status::OK(); } std::unique_ptr<OperationPass<ModuleOp>> createXlaHloToLhloWithXlaPass() { return std::make_unique<XlaHloToLhloPass>(); } Status HloToLhloModule(const BufferAssignment& assignment, const HloModule& hlo_module, ModuleOp module) { module.getContext() ->loadDialect<StandardOpsDialect, mhlo::MhloDialect, lmhlo::LmhloDialect, lmhlo_gpu::LmhloGpuDialect>(); const HloComputation* computation = hlo_module.entry_computation(); LhloDialectEmitter emitter(assignment, *computation, module); TF_RETURN_IF_ERROR(emitter.Initialize()); const xla::HloInstructionSequence* schedule = assignment.hlo_ordering().SequentialOrder(*computation); if (!schedule) return xla::Unimplemented("Missing sequential order for the computation"); const std::vector<HloInstruction*>& ordering = schedule->instructions(); return computation->AcceptOrdered(&emitter, ordering); } OwningModuleRef HloTextToLhloTranslateFunction(llvm::StringRef input, MLIRContext* context) { StatusOr<std::unique_ptr<HloModule>> maybe_module = xla::ParseAndReturnUnverifiedModule( absl::string_view(input.data(), input.size())); TF_CHECK_OK(maybe_module.status()); OwningModuleRef module = ModuleOp::create(UnknownLoc::get(context)); TF_CHECK_OK( ConvertModule(maybe_module.ConsumeValueOrDie(), module.get(), "Host")); return module; } static PassRegistration<XlaHloToLhloPass> registration( "xla-hlo-to-lhlo-with-xla", "Emit LHLO from HLO using the existing XLA implementation"); } // namespace mlir
/* Copyright 2016 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "StdAfx.h" #include "TinToPoint.h" int main(int argc, char** argv) { CoInitialize(0); ESRI_SET_VERSION(esriArcGISEngine); std::cerr << "Tin to Point: ArcGIS Engine Developer Sample" << std::endl; if (argc != 3) { std::cerr << "Usage: TinToPoint " << "[Input Tin] " << "[Output Shapefile]" << std::endl; return 0; } char* tinFullPath = argv[1]; char* outputFile = argv[2]; // data location variables CComBSTR shapePath; CComBSTR shapeFile; // Parse the input and output paths HRESULT hr = GetParentDirFromFullPath(outputFile, &shapePath); if (FAILED(hr) || shapePath.Length() <= 0) { std::cerr << "Couldn't get output path." << std::endl; } hr = GetFileFromFullPath(outputFile, &shapeFile); if (FAILED(hr) || shapeFile.Length() <= 0) { std::cerr << "Couldn't get output file name." << std::endl; } if (!InitializeApp(esriLicenseExtensionCode3DAnalyst)) { return 0; } hr = ConvertTin2Point(tinFullPath, shapePath, shapeFile); if (FAILED(hr)) std::cerr << "Failed!" << std::endl; else std::cerr << "Tin to point - Done" << std::endl; ShutdownApp(); CoUninitialize(); return 0; } HRESULT ConvertTin2Point(char* tinFullPath, BSTR shapePath, BSTR shapeFile) { // Get tin from tin file ITinPtr ipTin(CLSID_Tin); ITinAdvancedPtr ipTinAdv(ipTin); ipTinAdv->Init(CComBSTR(tinFullPath)); printf("Calculating...\n"); ISpatialReferencePtr ipTinSpatialRef; ((IGeoDatasetPtr) ipTin)->get_SpatialReference(&ipTinSpatialRef); IFieldsPtr ipFields; CreateBasicFields(esriGeometryPoint, VARIANT_FALSE, VARIANT_TRUE, ipTinSpatialRef, &ipFields); // Create output shapefile IWorkspaceFactoryPtr ipWkspFac(CLSID_ShapefileWorkspaceFactory); IWorkspacePtr ipWksp; HRESULT hr = ipWkspFac->OpenFromFile(shapePath, 0, &ipWksp); if (FAILED(hr) || ipWksp == 0) { std::cerr << "Couldn't open workspace." << std::endl; return hr; } IFeatureWorkspacePtr ipFeatureWksp(ipWksp); IFeatureClassPtr ipOutFeatureClass; ipFeatureWksp->CreateFeatureClass(shapeFile, ipFields, NULL, NULL, esriFTSimple, CComBSTR(L"Shape"), CComBSTR(L""), &ipOutFeatureClass); // Get Tin node enum IEnumTinNodePtr ipTinEnum; IEnvelopePtr ipTinEnv; ipTin->get_Extent(&ipTinEnv); ipTinAdv->MakeNodeEnumerator(ipTinEnv, esriTinInsideDataArea, NULL, &ipTinEnum); // Store node to shapefile IFeatureCursorPtr ipOutCursor; ipOutFeatureClass->Insert(VARIANT_TRUE, &ipOutCursor); IFeatureBufferPtr ipOutBuffer; ipOutFeatureClass->CreateFeatureBuffer(&ipOutBuffer); IPointPtr ipPoint(CLSID_Point); ITinNodePtr ipTinNode; ipTinEnum->Next(&ipTinNode); while (ipTinNode != 0) { ipTinNode->QueryAsPoint(ipPoint); ipOutBuffer->putref_Shape((IGeometryPtr) ipPoint); CComVariant id; ipOutCursor->InsertFeature(ipOutBuffer, &id); ipTinEnum->Next(&ipTinNode); } std::wcerr << "Generated shapefile is named " << shapeFile << " and in " << shapePath << std::endl; return S_OK; } HRESULT CreateBasicFields(esriGeometryType shapeType, VARIANT_BOOL hasM, VARIANT_BOOL hasZ, ISpatialReference* pSpatialRef, IFields** ppFields) { HRESULT hr; VARIANT_BOOL vbXYPres; pSpatialRef->HasXYPrecision(&vbXYPres); double dGridSize; if (vbXYPres) { double xmin; double ymin; double xmax; double ymax; pSpatialRef->GetDomain(&xmin, &xmax, &ymin, &ymax); double dArea = (xmax - xmin) * (ymax - ymin); dGridSize = sqrt(dArea); } else dGridSize = 1000; IGeometryDefPtr ipGeomDef(CLSID_GeometryDef); IGeometryDefEditPtr ipGeomDefEdit(ipGeomDef); ipGeomDefEdit->put_GeometryType(shapeType); ipGeomDefEdit->put_HasM(hasM); ipGeomDefEdit->put_HasZ(hasZ); ipGeomDefEdit->putref_SpatialReference(pSpatialRef); ipGeomDefEdit->put_GridCount(1); ipGeomDefEdit->put_GridSize(0, dGridSize); // Add OID field (must come before geometry field) IFieldsPtr ipFields(CLSID_Fields); *ppFields = ipFields; if (*ppFields) (*ppFields)->AddRef(); IFieldsEditPtr ipFieldsEdit(ipFields); IFieldPtr ipField(CLSID_Field); IFieldEditPtr ipFieldEdit(ipField); ipFieldEdit->put_Name(CComBSTR(L"OBJECTID")); ipFieldEdit->put_AliasName(CComBSTR(L"OBJECTID")); ipFieldEdit->put_Type(esriFieldTypeOID); hr = ipFieldsEdit->AddField(ipField); // Add geometry field ipField = IFieldPtr(CLSID_Field); ipFieldEdit = ipField; ipFieldEdit->put_Name(CComBSTR(L"SHAPE")); ipFieldEdit->put_IsNullable(VARIANT_TRUE); ipFieldEdit->put_Type(esriFieldTypeGeometry); ipFieldEdit->putref_GeometryDef(ipGeomDef); ipFieldEdit->put_Required(true); ipFieldsEdit->AddField(ipField); return S_OK; }
// Copyright 2009 The Android Open Source Project #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <time.h> #include <dirent.h> #include <errno.h> #include <assert.h> #include <ctype.h> #include <utime.h> #include <sys/stat.h> #include <sys/types.h> #include <stdint.h> #include <cutils/properties.h> #include <private/android_filesystem_config.h> #ifndef PATH_MAX #define PATH_MAX 4096 #endif // First version. #define FILE_VERSION_1 0xffff0001 // Introduces backup all option to header. #define FILE_VERSION_2 0xffff0002 #define FILE_VERSION FILE_VERSION_2 namespace android { static char nameBuffer[PATH_MAX]; static struct stat statBuffer; static char copyBuffer[8192]; static char *backupFilePath = NULL; static uint32_t inputFileVersion; static int opt_backupAll; #define SPECIAL_NO_TOUCH 0 #define SPECIAL_NO_BACKUP 1 struct special_dir { const char* path; int type; }; /* Directory paths that we will not backup/restore */ static const struct special_dir SKIP_PATHS[] = { { "/data/misc", SPECIAL_NO_TOUCH }, { "/data/system/batterystats.bin", SPECIAL_NO_TOUCH }, { "/data/system/location", SPECIAL_NO_TOUCH }, { "/data/dalvik-cache", SPECIAL_NO_BACKUP }, { NULL, 0 }, }; /* This is just copied from the shell's built-in wipe command. */ static int wipe (const char *path) { DIR *dir; struct dirent *de; int ret; int i; dir = opendir(path); if (dir == NULL) { fprintf (stderr, "Error opendir'ing %s: %s\n", path, strerror(errno)); return 0; } char *filenameOffset; strcpy(nameBuffer, path); strcat(nameBuffer, "/"); filenameOffset = nameBuffer + strlen(nameBuffer); for (;;) { de = readdir(dir); if (de == NULL) { break; } if (0 == strcmp(de->d_name, ".") || 0 == strcmp(de->d_name, "..") || 0 == strcmp(de->d_name, "lost+found") ) { continue; } strcpy(filenameOffset, de->d_name); bool noBackup = false; /* See if this is a path we should skip. */ for (i = 0; SKIP_PATHS[i].path; i++) { if (strcmp(SKIP_PATHS[i].path, nameBuffer) == 0) { if (opt_backupAll || SKIP_PATHS[i].type == SPECIAL_NO_BACKUP) { // In this case we didn't back up the directory -- // we do want to wipe its contents, but not the // directory itself, since the restore file won't // contain the directory. noBackup = true; } break; } } if (!noBackup && SKIP_PATHS[i].path != NULL) { // This is a SPECIAL_NO_TOUCH directory. continue; } ret = lstat (nameBuffer, &statBuffer); if (ret != 0) { fprintf(stderr, "warning -- stat() error on '%s': %s\n", nameBuffer, strerror(errno)); continue; } if(S_ISDIR(statBuffer.st_mode)) { int i; char *newpath; newpath = strdup(nameBuffer); if (wipe(newpath) == 0) { free(newpath); closedir(dir); return 0; } if (!noBackup) { ret = rmdir(newpath); if (ret != 0) { fprintf(stderr, "warning -- rmdir() error on '%s': %s\n", newpath, strerror(errno)); } } free(newpath); strcpy(nameBuffer, path); strcat(nameBuffer, "/"); } else { // Don't delete the backup file if (backupFilePath && strcmp(backupFilePath, nameBuffer) == 0) { continue; } ret = unlink(nameBuffer); if (ret != 0) { fprintf(stderr, "warning -- unlink() error on '%s': %s\n", nameBuffer, strerror(errno)); } } } closedir(dir); return 1; } static int write_int32(FILE* fh, int32_t val) { int res = fwrite(&val, 1, sizeof(val), fh); if (res != sizeof(val)) { fprintf(stderr, "unable to write int32 (%d bytes): %s\n", res, strerror(errno)); return 0; } return 1; } static int write_int64(FILE* fh, int64_t val) { int res = fwrite(&val, 1, sizeof(val), fh); if (res != sizeof(val)) { fprintf(stderr, "unable to write int64 (%d bytes): %s\n", res, strerror(errno)); return 0; } return 1; } static int copy_file(FILE* dest, FILE* src, off_t size, const char* destName, const char* srcName) { errno = 0; off_t origSize = size; while (size > 0) { int amt = size > (off_t)sizeof(copyBuffer) ? sizeof(copyBuffer) : (int)size; int readLen = fread(copyBuffer, 1, amt, src); if (readLen <= 0) { if (srcName != NULL) { fprintf(stderr, "unable to read source (%d of %ld bytes) file '%s': %s\n", amt, origSize, srcName, errno != 0 ? strerror(errno) : "unexpected EOF"); } else { fprintf(stderr, "unable to read buffer (%d of %ld bytes): %s\n", amt, origSize, errno != 0 ? strerror(errno) : "unexpected EOF"); } return 0; } int writeLen = fwrite(copyBuffer, 1, readLen, dest); if (writeLen != readLen) { if (destName != NULL) { fprintf(stderr, "unable to write file (%d of %d bytes) '%s': '%s'\n", writeLen, readLen, destName, strerror(errno)); } else { fprintf(stderr, "unable to write buffer (%d of %d bytes): '%s'\n", writeLen, readLen, strerror(errno)); } return 0; } size -= readLen; } return 1; } #define TYPE_END 0 #define TYPE_DIR 1 #define TYPE_FILE 2 static int write_header(FILE* fh, int type, const char* path, const struct stat* st) { int pathLen = strlen(path); if (!write_int32(fh, type)) return 0; if (!write_int32(fh, pathLen)) return 0; if (fwrite(path, 1, pathLen, fh) != (size_t)pathLen) { fprintf(stderr, "unable to write: %s\n", strerror(errno)); return 0; } if (!write_int32(fh, st->st_uid)) return 0; if (!write_int32(fh, st->st_gid)) return 0; if (!write_int32(fh, st->st_mode)) return 0; if (!write_int64(fh, ((int64_t)st->st_atime)*1000*1000*1000)) return 0; if (!write_int64(fh, ((int64_t)st->st_mtime)*1000*1000*1000)) return 0; if (!write_int64(fh, ((int64_t)st->st_ctime)*1000*1000*1000)) return 0; return 1; } static int backup_dir(FILE* fh, const char* srcPath) { DIR *dir; struct dirent *de; char* fullPath = NULL; int srcLen = strlen(srcPath); int result = 1; int i; dir = opendir(srcPath); if (dir == NULL) { fprintf (stderr, "error opendir'ing '%s': %s\n", srcPath, strerror(errno)); return 0; } for (;;) { de = readdir(dir); if (de == NULL) { break; } if (0 == strcmp(de->d_name, ".") || 0 == strcmp(de->d_name, "..") || 0 == strcmp(de->d_name, "lost+found") ) { continue; } if (fullPath != NULL) { free(fullPath); } fullPath = (char*)malloc(srcLen + strlen(de->d_name) + 2); strcpy(fullPath, srcPath); fullPath[srcLen] = '/'; strcpy(fullPath+srcLen+1, de->d_name); /* See if this is a path we should skip. */ if (!opt_backupAll) { for (i = 0; SKIP_PATHS[i].path; i++) { if (strcmp(SKIP_PATHS[i].path, fullPath) == 0) { break; } } if (SKIP_PATHS[i].path != NULL) { continue; } } int ret = lstat(fullPath, &statBuffer); if (ret != 0) { fprintf(stderr, "stat() error on '%s': %s\n", fullPath, strerror(errno)); result = 0; goto done; } if(S_ISDIR(statBuffer.st_mode)) { printf("Saving dir %s...\n", fullPath); if (write_header(fh, TYPE_DIR, fullPath, &statBuffer) == 0) { result = 0; goto done; } if (backup_dir(fh, fullPath) == 0) { result = 0; goto done; } } else if (S_ISREG(statBuffer.st_mode)) { // Skip the backup file if (backupFilePath && strcmp(fullPath, backupFilePath) == 0) { printf("Skipping backup file %s...\n", backupFilePath); continue; } else { printf("Saving file %s...\n", fullPath); } if (write_header(fh, TYPE_FILE, fullPath, &statBuffer) == 0) { result = 0; goto done; } off_t size = statBuffer.st_size; if (!write_int64(fh, size)) { result = 0; goto done; } FILE* src = fopen(fullPath, "r"); if (src == NULL) { fprintf(stderr, "unable to open source file '%s': %s\n", fullPath, strerror(errno)); result = 0; goto done; } int copyres = copy_file(fh, src, size, NULL, fullPath); fclose(src); if (!copyres) { result = 0; goto done; } } } done: if (fullPath != NULL) { free(fullPath); } closedir(dir); return result; } static int backup_data(const char* destPath) { int res = -1; FILE* fh = fopen(destPath, "w"); if (fh == NULL) { fprintf(stderr, "unable to open destination '%s': %s\n", destPath, strerror(errno)); return -1; } printf("Backing up /data to %s...\n", destPath); // The path that shouldn't be backed up backupFilePath = strdup(destPath); if (!write_int32(fh, FILE_VERSION)) goto done; if (!write_int32(fh, opt_backupAll)) goto done; if (!backup_dir(fh, "/data")) goto done; if (!write_int32(fh, 0)) goto done; res = 0; done: if (fflush(fh) != 0) { fprintf(stderr, "error flushing destination '%s': %s\n", destPath, strerror(errno)); res = -1; goto donedone; } if (fsync(fileno(fh)) != 0) { fprintf(stderr, "error syncing destination '%s': %s\n", destPath, strerror(errno)); res = -1; goto donedone; } fclose(fh); sync(); donedone: return res; } static int32_t read_int32(FILE* fh, int32_t defVal) { int32_t val; if (fread(&val, 1, sizeof(val), fh) != sizeof(val)) { fprintf(stderr, "unable to read: %s\n", strerror(errno)); return defVal; } return val; } static int64_t read_int64(FILE* fh, int64_t defVal) { int64_t val; if (fread(&val, 1, sizeof(val), fh) != sizeof(val)) { fprintf(stderr, "unable to read: %s\n", strerror(errno)); return defVal; } return val; } static int read_header(FILE* fh, int* type, char** path, struct stat* st) { *type = read_int32(fh, -1); if (*type == TYPE_END) { return 1; } if (*type < 0) { fprintf(stderr, "bad token %d in restore file\n", *type); return 0; } int32_t pathLen = read_int32(fh, -1); if (pathLen <= 0) { fprintf(stderr, "bad path length %d in restore file\n", pathLen); return 0; } char* readPath = (char*)malloc(pathLen+1); if (fread(readPath, 1, pathLen, fh) != (size_t)pathLen) { fprintf(stderr, "truncated path in restore file\n"); free(readPath); return 0; } readPath[pathLen] = 0; *path = readPath; st->st_uid = read_int32(fh, -1); if (st->st_uid == (uid_t)-1) { fprintf(stderr, "bad uid in restore file at '%s'\n", readPath); return 0; } st->st_gid = read_int32(fh, -1); if (st->st_gid == (gid_t)-1) { fprintf(stderr, "bad gid in restore file at '%s'\n", readPath); return 0; } st->st_mode = read_int32(fh, -1); if (st->st_mode == (mode_t)-1) { fprintf(stderr, "bad mode in restore file at '%s'\n", readPath); return 0; } int64_t ltime = read_int64(fh, -1); if (ltime < 0) { fprintf(stderr, "bad atime in restore file at '%s'\n", readPath); return 0; } st->st_atime = (time_t)(ltime/1000/1000/1000); ltime = read_int64(fh, -1); if (ltime < 0) { fprintf(stderr, "bad mtime in restore file at '%s'\n", readPath); return 0; } st->st_mtime = (time_t)(ltime/1000/1000/1000); ltime = read_int64(fh, -1); if (ltime < 0) { fprintf(stderr, "bad ctime in restore file at '%s'\n", readPath); return 0; } st->st_ctime = (time_t)(ltime/1000/1000/1000); st->st_mode &= (S_IRWXU|S_IRWXG|S_IRWXO); return 1; } static int restore_data(const char* srcPath) { int res = -1; FILE* fh = fopen(srcPath, "r"); if (fh == NULL) { fprintf(stderr, "Unable to open source '%s': %s\n", srcPath, strerror(errno)); return -1; } inputFileVersion = read_int32(fh, 0); if (inputFileVersion < FILE_VERSION_1 || inputFileVersion > FILE_VERSION) { fprintf(stderr, "Restore file has bad version: 0x%x\n", inputFileVersion); goto done; } if (inputFileVersion >= FILE_VERSION_2) { opt_backupAll = read_int32(fh, 0); } else { opt_backupAll = 0; } // The path that shouldn't be deleted backupFilePath = strdup(srcPath); printf("Wiping contents of /data...\n"); if (!wipe("/data")) { goto done; } printf("Restoring from %s to /data...\n", srcPath); while (1) { int type; char* path = NULL; if (read_header(fh, &type, &path, &statBuffer) == 0) { goto done; } if (type == 0) { break; } const char* typeName = "?"; if (type == TYPE_DIR) { typeName = "dir"; printf("Restoring dir %s...\n", path); if (mkdir(path, statBuffer.st_mode) != 0) { if (errno != EEXIST) { fprintf(stderr, "unable to create directory '%s': %s\n", path, strerror(errno)); free(path); goto done; } } } else if (type == TYPE_FILE) { typeName = "file"; off_t size = read_int64(fh, -1); if (size < 0) { fprintf(stderr, "bad file size %ld in restore file\n", size); free(path); goto done; } printf("Restoring file %s...\n", path); FILE* dest = fopen(path, "w"); if (dest == NULL) { fprintf(stderr, "unable to open destination file '%s': %s\n", path, strerror(errno)); free(path); goto done; } int copyres = copy_file(dest, fh, size, path, NULL); fclose(dest); if (!copyres) { free(path); goto done; } } else { fprintf(stderr, "unknown node type %d\n", type); goto done; } // Do this even for directories, since the dir may have already existed // so we need to make sure it gets the correct mode. if (chmod(path, statBuffer.st_mode&(S_IRWXU|S_IRWXG|S_IRWXO)) != 0) { fprintf(stderr, "unable to chmod destination %s '%s' to 0x%x: %s\n", typeName, path, statBuffer.st_mode, strerror(errno)); free(path); goto done; } if (chown(path, statBuffer.st_uid, statBuffer.st_gid) != 0) { fprintf(stderr, "unable to chown destination %s '%s' to uid %d / gid %d: %s\n", typeName, path, (int)statBuffer.st_uid, (int)statBuffer.st_gid, strerror(errno)); free(path); goto done; } struct utimbuf timbuf; timbuf.actime = statBuffer.st_atime; timbuf.modtime = statBuffer.st_mtime; if (utime(path, &timbuf) != 0) { fprintf(stderr, "unable to utime destination %s '%s': %s\n", typeName, path, strerror(errno)); free(path); goto done; } free(path); } res = 0; done: fclose(fh); return res; } static void show_help(const char *cmd) { fprintf(stderr,"Usage: %s COMMAND [options] [backup-file-path]\n", cmd); fprintf(stderr, "commands are:\n" " help Show this help text.\n" " backup Perform a backup of /data.\n" " restore Perform a restore of /data.\n"); fprintf(stderr, "options include:\n" " -h Show this help text.\n" " -a Backup all files.\n"); fprintf(stderr, "\n backup-file-path Defaults to /sdcard/backup.dat .\n" " On devices that emulate the sdcard, you will need to\n" " explicitly specify the directory it is mapped to,\n" " to avoid recursive backup or deletion of the backup file\n" " during restore.\n\n" " Eg. /data/media/0/backup.dat\n"); fprintf(stderr, "\nThe %s command allows you to perform low-level\n" "backup and restore of the /data partition. This is\n" "where all user data is kept, allowing for a fairly\n" "complete restore of a device's state. Note that\n" "because this is low-level, it will only work across\n" "builds of the same (or very similar) device software.\n", cmd); } } /* namespace android */ int main (int argc, char **argv) { int restore = 0; if (getuid() != AID_ROOT) { fprintf(stderr, "error -- %s must run as root\n", argv[0]); exit(-1); } if (argc < 2) { fprintf(stderr, "No command specified.\n"); android::show_help(argv[0]); exit(-1); } if (0 == strcmp(argv[1], "restore")) { restore = 1; } else if (0 == strcmp(argv[1], "help")) { android::show_help(argv[0]); exit(0); } else if (0 != strcmp(argv[1], "backup")) { fprintf(stderr, "Unknown command: %s\n", argv[1]); android::show_help(argv[0]); exit(-1); } android::opt_backupAll = 0; optind = 2; for (;;) { int ret; ret = getopt(argc, argv, "ah"); if (ret < 0) { break; } switch(ret) { case 'a': android::opt_backupAll = 1; if (restore) fprintf(stderr, "Warning: -a option ignored on restore\n"); break; case 'h': android::show_help(argv[0]); exit(0); break; default: fprintf(stderr,"Unrecognized Option\n"); android::show_help(argv[0]); exit(-1); break; } } const char* backupFile = "/sdcard/backup.dat"; if (argc > optind) { backupFile = argv[optind]; optind++; if (argc != optind) { fprintf(stderr, "Too many arguments\n"); android::show_help(argv[0]); exit(-1); } } printf("Stopping system...\n"); property_set("ctl.stop", "runtime"); property_set("ctl.stop", "zygote"); sleep(1); int res; if (restore) { res = android::restore_data(backupFile); if (res != 0) { // Don't restart system, since the data partition is hosed. return res; } printf("Restore complete! Restarting system, cross your fingers...\n"); } else { res = android::backup_data(backupFile); if (res == 0) { printf("Backup complete! Restarting system...\n"); } else { printf("Restarting system...\n"); } } property_set("ctl.start", "zygote"); property_set("ctl.start", "runtime"); }
// Copyright (c) 2018, The TurtleCoin Developers // Copyright (c) 2018-2019, The Urbancash Developers // // Please see the included LICENSE file for more information. ///////////////////////////////////////////// #include <GreenWallet/CommandImplementations.h> ///////////////////////////////////////////// #include <atomic> #include <initializer_list> #include "Common/Base58.h" #include "Common/StringTools.h" #include "Common/FormatTools.h" #include "Tools.h" #include "CryptoNoteCore/Account.h" #include "CryptoNoteCore/CryptoNoteBasicImpl.h" #ifndef MSVC #include <fstream> #endif #include "Mnemonics/electrum-words.h" #include <GreenWallet/AddressBook.h> #include <Common/ColouredMsg.h> #include <GreenWallet/Commands.h> #include <GreenWallet/Fusion.h> #include <GreenWallet/Menu.h> #include <GreenWallet/Open.h> #include <GreenWallet/Sync.h> #include <GreenWallet/Tools.h> #include <GreenWallet/Transfer.h> #include <GreenWallet/Types.h> #include <GreenWallet/WalletConfig.h> void changePassword(std::shared_ptr<WalletInfo> walletInfo) { /* Check the user knows the current password */ confirmPassword(walletInfo->walletPass, "Confirm your current password: "); /* Get a new password for the wallet */ const std::string newPassword = getWalletPassword(true, "Enter your new password: "); /* Change the wallet password */ walletInfo->wallet.changePassword(walletInfo->walletPass, newPassword); /* Change the stored wallet metadata */ walletInfo->walletPass = newPassword; /* Make sure we save with the new password */ walletInfo->wallet.save(); std::cout << SuccessMsg("Your password has been changed!") << std::endl; } void exportKeys(std::shared_ptr<WalletInfo> walletInfo) { confirmPassword(walletInfo->walletPass); printPrivateKeys(walletInfo->wallet, walletInfo->viewWallet); } std::string getGUIPrivateKey(CryptoNote::WalletGreen &wallet) { auto viewKey = wallet.getViewKey(); auto spendKey = wallet.getAddressSpendKey(0); CryptoNote::AccountPublicAddress addr { spendKey.publicKey, viewKey.publicKey, }; CryptoNote::AccountKeys keys { addr, spendKey.secretKey, viewKey.secretKey, }; return Tools::Base58::encode_addr ( CryptoNote::parameters::CRYPTONOTE_PUBLIC_ADDRESS_BASE58_PREFIX, std::string(reinterpret_cast<char*>(&keys), sizeof(keys)) ); } void printPrivateKeys(CryptoNote::WalletGreen &wallet, bool viewWallet) { auto privateViewKey = wallet.getViewKey().secretKey; if (viewWallet) { std::cout << SuccessMsg("Private view key:") << std::endl << SuccessMsg(Common::podToHex(privateViewKey)) << std::endl; return; } auto privateSpendKey = wallet.getAddressSpendKey(0).secretKey; Crypto::SecretKey derivedPrivateViewKey; CryptoNote::AccountBase::generateViewFromSpend(privateSpendKey, derivedPrivateViewKey); const bool deterministicPrivateKeys = derivedPrivateViewKey == privateViewKey; std::cout << SuccessMsg("Private spend key:") << std::endl << SuccessMsg(Common::podToHex(privateSpendKey)) << std::endl << std::endl << SuccessMsg("Private view key:") << std::endl << SuccessMsg(Common::podToHex(privateViewKey)) << std::endl; if (deterministicPrivateKeys) { std::string mnemonicSeed; Crypto::ElectrumWords::bytes_to_words(privateSpendKey, mnemonicSeed, "English"); std::cout << std::endl << SuccessMsg("Mnemonic seed:") << std::endl << SuccessMsg(mnemonicSeed) << std::endl; } std::cout << std::endl << SuccessMsg("GUI Importable Private Key:") << std::endl << SuccessMsg(getGUIPrivateKey(wallet)) << std::endl; } void balance(CryptoNote::INode &node, CryptoNote::WalletGreen &wallet, bool viewWallet) { const uint64_t unconfirmedBalance = wallet.getPendingBalance(); const uint64_t confirmedBalance = wallet.getActualBalance(); const uint64_t totalBalance = unconfirmedBalance + confirmedBalance; const uint32_t localHeight = node.getLastLocalBlockHeight(); const uint32_t remoteHeight = node.getLastKnownBlockHeight(); const uint32_t walletHeight = wallet.getBlockCount(); std::cout << "Available balance: " << SuccessMsg(formatAmount(confirmedBalance)) << std::endl << "Locked (unconfirmed) balance: " << WarningMsg(formatAmount(unconfirmedBalance)) << std::endl << "Total balance: " << InformationMsg(formatAmount(totalBalance)) << std::endl; if (viewWallet) { std::cout << std::endl << InformationMsg("Please note that view only wallets " "can only track incoming transactions,") << std::endl << InformationMsg("and so your wallet balance may appear " "inflated.") << std::endl; } if (localHeight < remoteHeight) { std::cout << std::endl << InformationMsg("Your daemon is not fully synced with " "the network!") << std::endl << "Your balance may be incorrect until you are fully " << "synced!" << std::endl; } /* Small buffer because wallet height doesn't update instantly like node height does */ else if (walletHeight + 1000 < remoteHeight) { std::cout << std::endl << InformationMsg("The blockchain is still being scanned for " "your transactions.") << std::endl << "Balances might be incorrect whilst this is ongoing." << std::endl; } } void blockchainHeight(CryptoNote::INode &node, CryptoNote::WalletGreen &wallet) { const uint32_t localHeight = node.getLastLocalBlockHeight(); const uint32_t remoteHeight = node.getLastKnownBlockHeight(); const uint32_t walletHeight = wallet.getBlockCount() - 1; /* This is the height that the wallet has been scanned to. The blockchain can be fully updated, but we have to walk the chain to find our transactions, and this number indicates that progress. */ std::cout << "Wallet blockchain height: "; /* Small buffer because wallet height doesn't update instantly like node height does */ if (walletHeight + 1000 > remoteHeight) { std::cout << SuccessMsg(std::to_string(walletHeight)); } else { std::cout << WarningMsg(std::to_string(walletHeight)); } std::cout << std::endl << "Local blockchain height: "; if (localHeight == remoteHeight) { std::cout << SuccessMsg(std::to_string(localHeight)); } else { std::cout << WarningMsg(std::to_string(localHeight)); } std::cout << std::endl << "Network blockchain height: " << SuccessMsg(std::to_string(remoteHeight)) << std::endl; if (localHeight == 0 && remoteHeight == 0) { std::cout << WarningMsg("Uh oh, it looks like you don't have ") << WarningMsg(WalletConfig::daemonName) << WarningMsg(" open!") << std::endl; } else if (walletHeight + 1000 < remoteHeight && localHeight == remoteHeight) { std::cout << InformationMsg("You are synced with the network, but the " "blockchain is still being scanned for " "your transactions.") << std::endl << "Balances might be incorrect whilst this is ongoing." << std::endl; } else if (localHeight == remoteHeight) { std::cout << SuccessMsg("Yay! You are synced!") << std::endl; } else { std::cout << WarningMsg("Be patient, you are still syncing with the " "network!") << std::endl; } } void printHeights(uint32_t localHeight, uint32_t remoteHeight, uint32_t walletHeight) { /* This is the height that the wallet has been scanned to. The blockchain can be fully updated, but we have to walk the chain to find our transactions, and this number indicates that progress. */ std::cout << "Wallet blockchain height: "; /* Small buffer because wallet height doesn't update instantly like node height does */ if (walletHeight + 1000 > remoteHeight) { std::cout << SuccessMsg(std::to_string(walletHeight)); } else { std::cout << WarningMsg(std::to_string(walletHeight)); } std::cout << std::endl << "Local blockchain height: "; if (localHeight == remoteHeight) { std::cout << SuccessMsg(std::to_string(localHeight)); } else { std::cout << WarningMsg(std::to_string(localHeight)); } std::cout << std::endl << "Network blockchain height: " << SuccessMsg(std::to_string(remoteHeight)) << std::endl; } void printSyncStatus(uint32_t localHeight, uint32_t remoteHeight, uint32_t walletHeight) { std::string networkSyncPercentage = Common::Format::get_sync_percentage(localHeight, remoteHeight) + "%"; std::string walletSyncPercentage = Common::Format::get_sync_percentage(walletHeight, remoteHeight) + "%"; std::cout << "Network sync status: "; if (localHeight == remoteHeight) { std::cout << SuccessMsg(networkSyncPercentage) << std::endl; } else { std::cout << WarningMsg(networkSyncPercentage) << std::endl; } std::cout << "Wallet sync status: "; /* Small buffer because wallet height is not always completely accurate */ if (walletHeight + 1000 > remoteHeight) { std::cout << SuccessMsg(walletSyncPercentage) << std::endl; } else { std::cout << WarningMsg(walletSyncPercentage) << std::endl; } } void printSyncSummary(uint32_t localHeight, uint32_t remoteHeight, uint32_t walletHeight) { if (localHeight == 0 && remoteHeight == 0) { std::cout << WarningMsg("Uh oh, it looks like you don't have ") << WarningMsg(WalletConfig::daemonName) << WarningMsg(" open!") << std::endl; } else if (walletHeight + 1000 < remoteHeight && localHeight == remoteHeight) { std::cout << InformationMsg("You are synced with the network, but the " "blockchain is still being scanned for " "your transactions.") << std::endl << "Balances might be incorrect whilst this is ongoing." << std::endl; } else if (localHeight == remoteHeight) { std::cout << SuccessMsg("Yay! You are synced!") << std::endl; } else { std::cout << WarningMsg("Be patient, you are still syncing with the " "network!") << std::endl; } } void printPeerCount(size_t peerCount) { std::cout << "Peers: " << SuccessMsg(std::to_string(peerCount)) << std::endl; } void printHashrate(uint64_t difficulty) { /* Offline node / not responding */ if (difficulty == 0) { return; } /* Hashrate is difficulty divided by block target time */ uint32_t hashrate = static_cast<uint32_t>( round(difficulty / CryptoNote::parameters::DIFFICULTY_TARGET) ); std::cout << "Network hashrate: " << SuccessMsg(Common::Format::get_mining_speed(hashrate)) << " (Based on the last local block)" << std::endl; } /* This makes sure to call functions on the node which only return cached data. This ensures it returns promptly, and doesn't hang waiting for a response when the node is having issues. */ void status(CryptoNote::INode &node, CryptoNote::WalletGreen &wallet) { uint32_t localHeight = node.getLastLocalBlockHeight(); uint32_t remoteHeight = node.getLastKnownBlockHeight(); uint32_t walletHeight = wallet.getBlockCount() - 1; /* Print the heights of local, remote, and wallet */ printHeights(localHeight, remoteHeight, walletHeight); std::cout << std::endl; /* Print the network and wallet sync status in percentage */ printSyncStatus(localHeight, remoteHeight, walletHeight); std::cout << std::endl; /* Print the network hashrate, based on the last local block */ printHashrate(node.getLastLocalBlockHeaderInfo().difficulty); /* Print the amount of peers we have */ printPeerCount(node.getPeerCount()); std::cout << std::endl; /* Print a summary of the sync status */ printSyncSummary(localHeight, remoteHeight, walletHeight); } void reset(CryptoNote::INode &node, std::shared_ptr<WalletInfo> walletInfo) { uint64_t scanHeight = getScanHeight(); std::cout << std::endl << InformationMsg("This process may take some time to complete.") << std::endl << InformationMsg("You can't make any transactions during the ") << InformationMsg("process.") << std::endl << std::endl; if (!confirm("Are you sure?")) { return; } std::cout << InformationMsg("Resetting wallet...") << std::endl; walletInfo->wallet.reset(scanHeight); syncWallet(node, walletInfo); } void saveCSV(CryptoNote::WalletGreen &wallet, CryptoNote::INode &node) { const size_t numTransactions = wallet.getTransactionCount(); std::ofstream csv; csv.open(WalletConfig::csvFilename); if (!csv) { std::cout << WarningMsg("Couldn't open transactions.csv file for " "saving!") << std::endl << WarningMsg("Ensure it is not open in any other " "application.") << std::endl; return; } std::cout << InformationMsg("Saving CSV file...") << std::endl; /* Create CSV header */ csv << "Timestamp,Block Height,Hash,Amount,In/Out" << std::endl; /* Loop through transactions */ for (size_t i = 0; i < numTransactions; i++) { const CryptoNote::WalletTransaction t = wallet.getTransaction(i); /* Ignore fusion transactions */ if (t.totalAmount == 0) { continue; } const std::string amount = formatAmountBasic(std::abs(t.totalAmount)); const std::string direction = t.totalAmount > 0 ? "IN" : "OUT"; csv << unixTimeToDate(t.timestamp) << "," /* Timestamp */ << t.blockHeight << "," /* Block Height */ << Common::podToHex(t.hash) << "," /* Hash */ << amount << "," /* Amount */ << direction /* In/Out */ << std::endl; } csv.close(); std::cout << SuccessMsg("CSV successfully written to ") << SuccessMsg(WalletConfig::csvFilename) << SuccessMsg("!") << std::endl; } void printOutgoingTransfer(CryptoNote::WalletTransaction t, CryptoNote::INode &node) { std::cout << WarningMsg("Outgoing transfer:") << std::endl << WarningMsg("Hash: " + Common::podToHex(t.hash)) << std::endl; /* Block height will be garbage from memory if not confirmed yet */ if (t.timestamp != 0) { std::cout << WarningMsg("Block height: ") << WarningMsg(std::to_string(t.blockHeight)) << std::endl << WarningMsg("Timestamp: ") << WarningMsg(unixTimeToDate(t.timestamp)) << std::endl; } std::cout << WarningMsg("Spent: " + formatAmount(-t.totalAmount - t.fee)) << std::endl << WarningMsg("Fee: " + formatAmount(t.fee)) << std::endl << WarningMsg("Total Spent: " + formatAmount(-t.totalAmount)) << std::endl; const std::string paymentID = getPaymentIDFromExtra(t.extra); if (paymentID != "") { std::cout << WarningMsg("Payment ID: " + paymentID) << std::endl; } std::cout << std::endl; } void printIncomingTransfer(CryptoNote::WalletTransaction t, CryptoNote::INode &node) { std::cout << SuccessMsg("Incoming transfer:") << std::endl << SuccessMsg("Block height: " + std::to_string(t.blockHeight)) << std::endl; /* Block height will be garbage from memory if not confirmed yet */ if (t.timestamp != 0) { std::cout << SuccessMsg("Block height: ") << SuccessMsg(std::to_string(t.blockHeight)) << std::endl << SuccessMsg("Timestamp: ") << SuccessMsg(unixTimeToDate(t.timestamp)) << std::endl; } std::cout << SuccessMsg("Hash: " + Common::podToHex(t.hash)) << std::endl << SuccessMsg("Amount: " + formatAmount(t.totalAmount)) << std::endl; const std::string paymentID = getPaymentIDFromExtra(t.extra); if (paymentID != "") { std::cout << SuccessMsg("Payment ID: " + paymentID) << std::endl; } std::cout << std::endl; } void listTransfers(bool incoming, bool outgoing, CryptoNote::WalletGreen &wallet, CryptoNote::INode &node) { const size_t numTransactions = wallet.getTransactionCount(); int64_t totalSpent = 0; int64_t totalReceived = 0; for (size_t i = 0; i < numTransactions; i++) { const CryptoNote::WalletTransaction t = wallet.getTransaction(i); if (t.totalAmount < 0 && outgoing) { printOutgoingTransfer(t, node); totalSpent += -t.totalAmount; } else if (t.totalAmount > 0 && incoming) { printIncomingTransfer(t, node); totalReceived += t.totalAmount; } } if (incoming) { std::cout << SuccessMsg("Total received: " + formatAmount(totalReceived)) << std::endl; } if (outgoing) { std::cout << WarningMsg("Total spent: " + formatAmount(totalSpent)) << std::endl; } } void save(CryptoNote::WalletGreen &wallet) { std::cout << InformationMsg("Saving.") << std::endl; wallet.save(); std::cout << InformationMsg("Saved.") << std::endl; } void help(std::shared_ptr<WalletInfo> wallet) { if (wallet->viewWallet) { printCommands(basicViewWalletCommands()); } else { printCommands(basicCommands()); } } void advanced(std::shared_ptr<WalletInfo> wallet) { /* We pass the offset of the command to know what index to print for command numbers */ if (wallet->viewWallet) { printCommands(advancedViewWalletCommands(), (int)basicViewWalletCommands().size()); } else { printCommands(advancedCommands(), (int)basicCommands().size()); } } void txSecretKey(CryptoNote::WalletGreen &wallet) { std::string hashStr; Crypto::Hash txid; while (true) { std::cout << InformationMsg("Enter transaction hash: "); std::getline(std::cin, hashStr); boost::algorithm::trim(hashStr); if (!parse_hash256(hashStr, txid)) { std::cout << WarningMsg("Failed to parse txid") << std::endl; return; } else { break; } if (std::cin.fail() || std::cin.eof()) { std::cin.clear(); break; } } Crypto::SecretKey txSecretKey = wallet.getTransactionSecretKey(txid); if (txSecretKey == CryptoNote::NULL_SECRET_KEY) { std::cout << WarningMsg("Transaction ") << WarningMsg(hashStr) << WarningMsg(" secret key is not available") << std::endl; return; } std::cout << SuccessMsg("Transaction secret key: ") << std::endl << SuccessMsg(Common::podToHex(txSecretKey)) << std::endl; } void txProof(CryptoNote::WalletGreen &wallet) { std::string txHashStr; Crypto::Hash txid; while (true) { std::cout << InformationMsg("Enter transaction hash: "); std::getline(std::cin, txHashStr); boost::algorithm::trim(txHashStr); if (!parse_hash256(txHashStr, txid)) { std::cout << WarningMsg("Failed to parse txid") << std::endl; return; } else { break; } if (std::cin.fail() || std::cin.eof()) { std::cin.clear(); break; } } Crypto::SecretKey txSecretKey = wallet.getTransactionSecretKey(txid); if (txSecretKey == CryptoNote::NULL_SECRET_KEY) { std::cout << InformationMsg("Transaction ") << InformationMsg(txHashStr) << InformationMsg(" secret key is not available.") << std::endl << InformationMsg("If you have it elsewhere, ") << InformationMsg("enter it here to continue: ") << std::endl; Crypto::Hash tx_key_hash; while (true) { std::string keyStr; std::getline(std::cin, keyStr); boost::algorithm::trim(keyStr); size_t size; if (!Common::fromHex(keyStr, &tx_key_hash, sizeof(tx_key_hash), size) || size != sizeof(tx_key_hash)) { std::cout << WarningMsg("Failed to parse tx secret key ") << WarningMsg(keyStr) << std::endl; return; } else { txSecretKey = *(struct Crypto::SecretKey *) &tx_key_hash; break; } if (std::cin.fail() || std::cin.eof()) { std::cin.clear(); break; } } } CryptoNote::AccountPublicAddress destAddress; while (true) { std::cout << InformationMsg("Enter destination address: "); std::string addrStr; uint64_t prefix; std::getline(std::cin, addrStr); boost::algorithm::trim(addrStr); if (!CryptoNote::parseAccountAddressString(prefix, destAddress, addrStr)) { std::cout << WarningMsg("Failed to parse address") << std::endl; } else { break; } if (std::cin.fail() || std::cin.eof()) { std::cin.clear(); break; } } try { std::string sig; if (wallet.getTransactionProof(txid, destAddress, txSecretKey, sig)) { std::cout << SuccessMsg("Transaction proof: ") << std::endl << SuccessMsg(sig) << std::endl; } else { std::cout << WarningMsg("Failed to get transaction proof") << std::endl; } } catch (std::system_error& x) { std::cout << WarningMsg("Error while getting transaction proof: ") << WarningMsg(x.what()) << std::endl; } catch (std::exception& x) { std::cout << WarningMsg("Error while getting transaction proof: ") << WarningMsg(x.what()) << std::endl; } } void reserveProof(std::shared_ptr<WalletInfo> walletInfo, bool viewWallet) { if (viewWallet) { std::cout << WarningMsg("This is tracking wallet. ") << WarningMsg("The reserve proof can be generated ") << WarningMsg("only by a full wallet.") << std::endl; return; } uint64_t amount; uint64_t actualBalance = walletInfo->wallet.getActualBalance(); while (true) { std::cout << InformationMsg("Enter amount to prove ") << InformationMsg("or type ") << "\"all\" " << InformationMsg("if you want to prove all balance: "); std::string amtStr; std::getline(std::cin, amtStr); if (amtStr == "all") { amount = actualBalance; break; } if (parseAmount(amtStr, amount)) { if (amount > actualBalance) { std::cout << WarningMsg("Amount is bigger than ") << WarningMsg("actual balance ") << WarningMsg(formatAmount(actualBalance)) << std::endl; } else { break; } } if (std::cin.fail() || std::cin.eof()) { std::cin.clear(); break; } } std::string message; while (true) { std::cout << InformationMsg("Enter optional challenge message: "); std::getline(std::cin, message); boost::algorithm::trim(message); if (message == "") { break; } if (std::cin.fail() || std::cin.eof()) { std::cin.clear(); break; } } try { const std::string sig = walletInfo->wallet.getReserveProof(amount, walletInfo->walletAddress, message.empty() ? "" : message); std::string fileName; while (true) { std::cout << InformationMsg("Enter file name ") << InformationMsg("where to save your proof: "); std::getline(std::cin, fileName); boost::algorithm::trim(fileName); if (boost::filesystem::portable_name(fileName)) { break; } else { std::cout << WarningMsg("Enter valid file name") << std::endl; } if (std::cin.fail() || std::cin.eof()) { std::cin.clear(); break; } } fileName += ".txt"; boost::system::error_code ec; if (boost::filesystem::exists(fileName, ec)) { boost::filesystem::remove(fileName, ec); } std::ofstream proofFile(fileName, std::ios::out | std::ios::trunc | std::ios::binary); if (!proofFile.good()) { std::cout << WarningMsg("Failed to save reserve proof to file") << std::endl; return; } proofFile << sig; std::cout << SuccessMsg("Proof signature saved to file: ") << SuccessMsg(fileName) << std::endl; } catch (const std::exception &e) { std::cout << WarningMsg("Failed to get reserve proof: ") << WarningMsg(e.what()) << std::endl; } } void signMessage(std::shared_ptr<WalletInfo> walletInfo, bool viewWallet) { if (viewWallet) { std::cout << WarningMsg("This is tracking wallet. ") << WarningMsg("The message can be signed ") << WarningMsg("only by a full wallet.") << std::endl; return; } std::string message; while (true) { std::cout << InformationMsg("Enter message to sign: "); std::getline(std::cin, message); boost::algorithm::trim(message); if (!message.empty()) { break; } if (std::cin.fail() || std::cin.eof()) { std::cin.clear(); break; } } try { std::string walletAddress = walletInfo->walletAddress; std::string signature = walletInfo->wallet.signMessage(message, walletAddress); std::cout << SuccessMsg("Signature: ") << InformationMsg(signature) << std::endl; } catch (const std::exception &e) { std::cout << WarningMsg("Failed to sign message: ") << WarningMsg(e.what()) << std::endl; } } void verifyMessage(CryptoNote::WalletGreen &wallet) { std::string addrStr; while (true) { std::cout << InformationMsg("Enter address: "); CryptoNote::AccountPublicAddress address; uint64_t prefix; std::getline(std::cin, addrStr); boost::algorithm::trim(addrStr); if (!CryptoNote::parseAccountAddressString(prefix, address, addrStr)) { std::cout << WarningMsg("Failed to parse address") << std::endl; } else { break; } if (std::cin.fail() || std::cin.eof()) { std::cin.clear(); break; } } std::string message; while (true) { std::cout << InformationMsg("Enter message: "); std::getline(std::cin, message); boost::algorithm::trim(message); if (!message.empty()) { break; } if (std::cin.fail() || std::cin.eof()) { std::cin.clear(); break; } } std::string signature; while (true) { std::cout << InformationMsg("Enter signature: "); std::getline(std::cin, signature); boost::algorithm::trim(signature); if (!signature.empty()) { break; } if (std::cin.fail() || std::cin.eof()) { std::cin.clear(); break; } } try { bool r = wallet.verifyMessage(message, addrStr, signature); if (r) { std::cout << SuccessMsg("Signature is valid") << std::endl; } else { std::cout << WarningMsg("Signature is invalid") << std::endl; } } catch (const std::exception &e) { std::cout << WarningMsg("Failed to verify message: ") << WarningMsg(e.what()) << std::endl; } }
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2019 Ryo Suzuki // Copyright (c) 2016-2019 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "Array.hpp" # include "PointVector.hpp" # include "Format.hpp" namespace s3d { /// <summary> /// 可変長二次元配列 /// </summary> template <class Type, class Allocator = std::allocator<Type>> class Grid { public: using container_type = Array<Type, Allocator>; using value_type = typename container_type::value_type; using pointer = typename container_type::pointer; using const_pointer = typename container_type::const_pointer; using reference = typename container_type::reference; using const_reference = typename container_type::const_reference; using iterator = typename container_type::iterator; using const_iterator = typename container_type::const_iterator; using reverse_iterator = typename container_type::reverse_iterator; using const_reverse_iterator = typename container_type::const_reverse_iterator; using size_type = typename container_type::size_type; using difference_type = typename container_type::difference_type; using allocator_type = typename container_type::allocator_type; private: container_type m_data; size_type m_width = 0; size_type m_height = 0; public: template <class Fty, std::enable_if_t<std::is_invocable_r_v<Type, Fty>>* = nullptr> static Grid Generate(const Size& size, Fty generator) { return Generate(size.x, size.y, generator); } template <class Fty, std::enable_if_t<std::is_invocable_r_v<Type, Fty>>* = nullptr> static Grid Generate(size_type w, size_type h, Fty generator) { Grid new_grid(w, h); for (auto& value : new_grid) { value = generator(); } return new_grid; } /// <summary> /// デフォルトコンストラクタ /// </summary> Grid() = default; Grid(const Grid& g) = default; Grid(Grid&& g) = default; /// <summary> /// 幅と高さを指定して二次元配列を作成します。 /// </summary> /// <param name="w"> /// 幅(列数) /// </param> /// <param name="h"> /// 高さ(行数) /// </param> Grid(size_type w, size_type h) : m_data(w * h) , m_width(w) , m_height(h) {} /// <summary> /// 幅と高さと初期値を指定して二次元配列を作成します。 /// </summary> /// <param name="w"> /// 幅(列数) /// </param> /// <param name="h"> /// 高さ(行数) /// </param> /// <param name="val"> /// 初期値 /// </param> Grid(size_type w, size_type h, const value_type& val) : m_data(w * h, val) , m_width(w) , m_height(h) {} /// <summary> /// 幅と高さを指定して二次元配列を作成します。 /// </summary> /// <param name="size"> /// 幅(列数)と高さ(行数) /// </param> explicit Grid(const Size& size) : Grid(size.x, size.y) {} /// <summary> /// 幅と高さと初期値を指定して二次元配列を作成します。 /// </summary> /// <param name="size"> /// 幅(列数)と高さ(行数) /// </param> /// <param name="val"> /// 初期値 /// </param> Grid(const Size& size, const value_type& val) : Grid(size.x, size.y, val) {} /// <summary> /// 配列から二次元配列を作成します。 /// </summary> /// <param name="w"> /// 幅(列数) /// </param> /// <param name="h"> /// 高さ(行数) /// </param> /// <param name="data"> /// 初期値 /// </param> Grid(size_type w, size_type h, const Array<value_type>& data) : m_data(data) , m_width(w) , m_height(h) { m_data.resize(w * h); } /// <summary> /// 配列から二次元配列を作成します。 /// </summary> /// <param name="w"> /// 幅(列数) /// </param> /// <param name="h"> /// 高さ(行数) /// </param> /// <param name="data"> /// 初期値 /// </param> Grid(size_type w, size_type h, Array<value_type>&& data) : m_data(std::move(data)) , m_width(w) , m_height(h) { m_data.resize(w * h); } Grid(const Size& size, const Array<value_type>& data) : Grid(size.x, size.y, data) {} Grid(const Size& size, Array<value_type>&& data) : Grid(size.x, size.y, std::move(data)) {} /// <summary> /// Initializer-list から二次元配列を作成します。 /// </summary> /// <param name="set"> /// Initializer-list /// </param> Grid(const std::initializer_list<std::initializer_list<value_type>>& set) : Grid(std::max_element(set.begin(), set.end(), [](auto& lhs, auto& rhs) { return lhs.size() < rhs.size(); })->size(), set.size()) { auto dst = begin(); for (const auto& a : set) { std::copy(a.begin(), a.end(), dst); dst += m_width; } } template <class Fty, std::enable_if_t<std::is_invocable_r_v<Type, Fty>>* = nullptr> Grid(const size_type w, const size_type h, Arg::generator_<Fty> generator) : Grid(Generate<Fty>(w, h, *generator)) {} template <class Fty, std::enable_if_t<std::is_invocable_r_v<Type, Fty>>* = nullptr> Grid(const Size& size, Arg::generator_<Fty> generator) : Grid(Generate<Fty>(size, *generator)) {} /// <summary> /// コピー代入演算子 /// </summary> /// <returns> /// *this /// </returns> Grid& operator =(const Grid& other) = default; /// <summary> /// ムーブ代入演算子 /// </summary> /// <returns> /// *this /// </returns> Grid& operator =(Grid&& other) = default; /// <summary> /// アロケータオブジェクトを返します。 /// </summary> /// <returns> /// アロケータオブジェクト /// </returns> [[nodiscard]] allocator_type get_allocator() const noexcept { return m_data.get_allocator(); } void assign(const size_type w, const size_type h, const value_type& value) { m_data.assign(w * h, value); } void assign(const Size& size, const value_type& value) { assign(size.x, size.y, value); } void assign(const std::initializer_list<std::initializer_list<value_type>>& set) { m_data.clear(); m_data.resize(std::max_element(set.begin(), set.end(), [](auto& lhs, auto& rhs) { return lhs.size() < rhs.size(); })->size(), set.size()); auto dst = begin(); for (const auto& a : set) { std::copy(a.begin(), a.end(), dst); dst += m_width; } } /// <summary> /// 指定した位置の要素への参照を返します。 /// </summary> /// <param name="y"> /// 位置(行) /// </param> /// <param name="x"> /// 位置(列) /// </param> /// <exception cref="std::out_of_range"> /// 範囲外アクセスの場合 throw されます。 /// </exception> /// <returns> /// 指定した位置の要素への参照 /// </returns> value_type& at(const size_type y, const size_type x) & { if (!inBounds(y, x)) { throw std::out_of_range("Grid::at() index out of range"); } return m_data[y * m_width + x]; } /// <summary> /// 指定した位置の要素への参照を返します。 /// </summary> /// <param name="y"> /// 位置(行) /// </param> /// <param name="x"> /// 位置(列) /// </param> /// <exception cref="std::out_of_range"> /// 範囲外アクセスの場合 throw されます。 /// </exception> /// <returns> /// 指定した位置の要素への参照 /// </returns> const value_type& at(const size_type y, const size_type x) const & { if (!inBounds(y, x)) { throw std::out_of_range("Grid::at() index out of range"); } return m_data[y * m_width + x]; } /// <summary> /// 指定した位置の要素を取得します。 /// </summary> /// <param name="y"> /// 位置(行) /// </param> /// <param name="x"> /// 位置(列) /// </param> /// <exception cref="std::out_of_range"> /// 範囲外アクセスの場合 throw されます。 /// </exception> /// <returns> /// 指定した位置の要素への参照 /// </returns> value_type at(const size_type y, const size_type x) && { if (!inBounds(y, x)) { throw std::out_of_range("Grid::at() index out of range"); } return std::move(m_data[y * m_width + x]); } /// <summary> /// 指定した位置の要素への参照を返します。 /// </summary> /// <param name="pos"> /// 位置(列と行) /// </param> /// <exception cref="std::out_of_range"> /// 範囲外アクセスの場合 throw されます。 /// </exception> /// <returns> /// 指定した位置の要素への参照 /// </returns> value_type& at(const Point& pos) & { return at(pos.y, pos.x); } /// <summary> /// 指定した位置の要素への参照を返します。 /// </summary> /// <param name="pos"> /// 位置(列と行) /// </param> /// <exception cref="std::out_of_range"> /// 範囲外アクセスの場合 throw されます。 /// </exception> /// <returns> /// 指定した位置の要素への参照 /// </returns> const value_type& at(const Point& pos) const & { return at(pos.y, pos.x); } /// <summary> /// 指定した位置の要素を取得します。 /// </summary> /// <param name="pos"> /// 位置(列と行) /// </param> /// <exception cref="std::out_of_range"> /// 範囲外アクセスの場合 throw されます。 /// </exception> /// <returns> /// 指定した位置の要素への参照 /// </returns> value_type at(const Point& pos) && { return at(pos.y, pos.x); } /// <summary> /// 指定した行の先頭ポインタを返します。 /// </summary> /// <param name="index"> /// 位置(行) /// </param> /// <remarks> /// grid[y][x] で指定した要素にアクセスします。 /// </remarks> /// <returns> /// 指定した行の先頭ポインタ /// </returns> [[nodiscard]] value_type* operator[](const size_t index) { return &m_data[index * m_width]; } /// <summary> /// 指定した行の先頭ポインタを返します。 /// </summary> /// <param name="index"> /// 位置(行) /// </param> /// <remarks> /// grid[y][x] で指定した要素にアクセスします。 /// </remarks> /// <returns> /// 指定した行の先頭ポインタ /// </returns> [[nodiscard]] const value_type* operator[](const size_t index) const { return &m_data[index * m_width]; } /// <summary> /// 指定した位置の要素への参照を返します。 /// </summary> /// <param name="pos"> /// 位置(列と行) /// </param> /// <returns> /// 指定した位置の要素への参照 /// </returns> [[nodiscard]] value_type& operator[](const Point& pos) & { return m_data[pos.y * m_width + pos.x]; } /// <summary> /// 指定した位置の要素への参照を返します。 /// </summary> /// <param name="pos"> /// 位置(列と行) /// </param> /// <returns> /// 指定した位置の要素への参照 /// </returns> [[nodiscard]] const value_type& operator[](const Point& pos) const & { return m_data[pos.y * m_width + pos.x]; } /// <summary> /// 指定した位置の要素を取得します。 /// </summary> /// <param name="pos"> /// 位置(列と行) /// </param> /// <returns> /// 指定した位置の要素 /// </returns> [[nodiscard]] value_type operator[](const Point& pos) && { return std::move(m_data[pos.y * m_width + pos.x]); } [[nodiscard]] bool inBounds(const int64 y, const int64 x) const noexcept { return (0 <= y) && (y < static_cast<int64>(m_height)) && (0 <= x) && (x < static_cast<int64>(m_width)); } /// <summary> /// 二次元配列の先頭のポインタを返します。 /// </summary> /// <returns> /// 二次元配列の先頭へのポインタ /// </returns> [[nodiscard]] pointer data() noexcept { return m_data.data(); } /// <summary> /// 二次元配列の先頭のポインタを返します。 /// </summary> /// <returns> /// 二次元配列の先頭へのポインタ /// </returns> [[nodiscard]] const_pointer data() const noexcept { return m_data.data(); } /// <summary> /// 二次元配列の先頭位置のイテレータを返します。 /// </summary> /// <returns> /// 二次元配列の先頭位置のイテレータ /// </returns> [[nodiscard]] iterator begin() noexcept { return m_data.begin(); } /// <summary> /// 二次元配列の終了頭位置のイテレータを返します。 /// </summary> /// <returns> /// 二次元配列の終了位置のイテレータ /// </returns> [[nodiscard]] iterator end() noexcept { return m_data.end(); } /// <summary> /// 二次元配列の先頭位置のイテレータを返します。 /// </summary> /// <returns> /// 二次元配列の先頭位置のイテレータ /// </returns> [[nodiscard]] const_iterator begin() const noexcept { return m_data.cbegin(); } /// <summary> /// 二次元配列の終了頭位置のイテレータを返します。 /// </summary> /// <returns> /// 二次元配列の終了位置のイテレータ /// </returns> [[nodiscard]] const_iterator end() const noexcept { return m_data.cend(); } /// <summary> /// 二次元配列の末尾のリバースイテレータを返します。 /// </summary> /// <returns> /// 二次元配列の末尾のリバースイテレータ /// </returns> [[nodiscard]] reverse_iterator rbegin() noexcept { return m_data.rbegin(); } /// <summary> /// 二次元配列の先頭の前へのリバースイテレータを返します。 /// </summary> /// <returns> /// 二次元配列の先頭の前へのリバースイテレータ /// </returns> [[nodiscard]] reverse_iterator rend() noexcept { return m_data.rend(); } /// <summary> /// 二次元配列の末尾のリバースイテレータを返します。 /// </summary> /// <returns> /// 二次元配列の末尾のリバースイテレータ /// </returns> [[nodiscard]] const_reverse_iterator rbegin() const noexcept { return m_data.rbegin(); } /// <summary> /// 二次元配列の先頭の前へのリバースイテレータを返します。 /// </summary> /// <returns> /// 二次元配列の先頭の前へのリバースイテレータ /// </returns> [[nodiscard]] const_reverse_iterator rend() const noexcept { return m_data.rend(); } /// <summary> /// 二次元配列の先頭位置のイテレータを返します。 /// </summary> /// <returns> /// 二次元配列の先頭位置のイテレータ /// </returns> [[nodiscard]] const_iterator cbegin() const noexcept { return m_data.cbegin(); } /// <summary> /// 二次元配列の終了頭位置のイテレータを返します。 /// </summary> /// <returns> /// 二次元配列の終了位置のイテレータ /// </returns> [[nodiscard]] const_iterator cend() const noexcept { return m_data.cend(); } /// <summary> /// 二次元配列の末尾のリバースイテレータを返します。 /// </summary> /// <returns> /// 二次元配列の末尾のリバースイテレータ /// </returns> [[nodiscard]] const_reverse_iterator crbegin() const noexcept { return m_data.crbegin(); } /// <summary> /// 二次元配列の先頭の前へのリバースイテレータを返します。 /// </summary> /// <returns> /// 二次元配列の先頭の前へのリバースイテレータ /// </returns> [[nodiscard]] const_reverse_iterator crend() const noexcept { return m_data.crend(); } [[nodiscard]] bool empty() const noexcept { return m_data.empty(); } [[nodiscard]] bool isEmpty() const noexcept { return m_data.empty(); } /// <summary> /// 配列に要素が含まれているかを返します。 /// </summary> /// <returns> /// 配列に要素が含まれている場合 true, それ以外の場合は false /// </returns> [[nodiscard]] explicit operator bool() const noexcept { return !m_data.empty(); } [[nodiscard]] size_type width() const noexcept { return m_width; } [[nodiscard]] size_type height() const noexcept { return m_height; } [[nodiscard]] Size size() const noexcept { return Size{ m_width, m_height }; } [[nodiscard]] size_type count() const noexcept { return m_data.size(); } [[nodiscard]] size_type size_elements() const noexcept { return m_data.size(); } [[nodiscard]] size_type size_bytes() const noexcept { static_assert(std::is_trivially_copyable_v<value_type>, "Grid::size_bytes() value_type must be trivially copyable."); return m_data.size() * sizeof(value_type); } /// <summary> /// Array を返します。 /// </summary> /// <returns> /// Array /// </returns> [[nodiscard]] const container_type& asArray() const noexcept { return m_data; } /// <summary> /// 二次元配列用のメモリを指定したサイズで確保します。 /// </summary> /// <param name="w"> /// 確保する幅(列数) /// </param> /// <param name="h"> /// 確保する高さ(行数) /// </param> /// <returns> /// なし /// </returns> void reserve(const size_type w, const size_type h) { m_data.reserve(w * h); } void reserve(const Size& size) { reserve(size.x, size.y); } [[nodiscard]] size_type capacity() const noexcept { return m_data.capacity(); } void shrink_to_fit() { m_data.shrink_to_fit(); } void clear() noexcept { m_data.clear(); m_width = m_height = 0; } void release() { clear(); shrink_to_fit(); } void swap(Grid& other) noexcept { m_data.swap(other.m_data); std::swap(m_width, other.m_width); std::swap(m_height, other.m_height); } /// <summary> /// 末尾に行を追加します。 /// </summary> /// <param name="value"> /// 追加される行の要素 /// </param> /// <returns> /// なし /// </returns> void push_back_row(const value_type& value) { m_data.insert(m_data.end(), m_width, value); ++m_height; } /// <summary> /// 末尾の行を削除します。 /// </summary> /// <exception cref="std::out_of_range"> /// 削除する行が無い場合 throw されます。 /// </exception> /// <returns> /// なし /// </returns> void pop_back_row() { if (m_height == 0) { throw std::out_of_range("Grid::pop_back_row() pop_back from empty Grid"); } --m_height; m_data.resize(m_data.size() - m_width); } void push_back_column(const value_type& value) { reserve(m_width + 1, m_height); const size_type w = m_width + 1; for (size_type i = 0; i < m_height; ++i) { m_data.insert(m_data.begin() + i * w + (w - 1), value); } ++m_width; } void pop_back_column() { if (m_width == 0) { throw std::out_of_range("Grid::pop_back_column() pop_back from empty Grid"); } remove_column(m_width - 1); } /// <summary> /// 指定した位置に行を挿入します。 /// </summary> /// <param name="pos"> /// 挿入先の位置(行) /// </param> /// <param name="value"> /// 追加される行の要素 /// </param> /// <returns> /// なし /// </returns> void insert_row(const size_type pos, const value_type& value) { insert_rows(pos, 1, value); } /// <summary> /// 指定した位置に行を挿入します。 /// </summary> /// <param name="pos"> /// 挿入先の位置(行) /// </param> /// <param name="rows"> /// 挿入する行数 /// </param> /// <param name="value"> /// 追加される行の要素 /// </param> /// <returns> /// なし /// </returns> void insert_rows(const size_type pos, const size_type rows, const value_type& value) { m_data.insert(m_data.begin() + m_width * pos, m_width * rows, value); m_height += rows; } void insert_column(const size_type pos, const value_type& value) { reserve(m_width + 1, m_height); const size_type w = m_width + 1; for (size_type i = 0; i < m_height; ++i) { m_data.insert(m_data.begin() + i * w + pos, value); } ++m_width; } void insert_columns(const size_type pos, const size_type columns, const value_type& value) { reserve(m_width + columns, m_height); const size_type w = m_width + columns; for (size_type i = 0; i < m_height; ++i) { for (size_type k = 0; k < columns; ++k) { m_data.insert(m_data.begin() + i * w + pos + k, value); } } m_width += columns; } /// <summary> /// 指定した位置の行を削除します。 /// </summary> /// <param name="pos"> /// 削除する行の位置 /// </param> /// <returns> /// なし /// </returns> void remove_row(const size_type pos) { if (m_height <= pos) { throw std::out_of_range("Grid::remove_row() index out of range"); } remove_rows(pos, 1); } /// <summary> /// 指定した位置から行を削除します。 /// </summary> /// <param name="pos"> /// 削除する行の位置 /// </param> /// <param name="count"> /// 削除する行数 /// </param> /// <returns> /// なし /// </returns> void remove_rows(const size_type pos, const size_type count) { if (m_height <= pos || m_height < (pos + count)) { throw std::out_of_range("Grid::remove_rows() index out of range"); } const auto first = m_data.begin() + m_width * pos; const auto last = first + m_width * count; m_data.erase(first, last); m_height -= count; } /// <summary> /// 指定した位置の列を削除します。 /// </summary> /// <param name="pos"> /// 削除する列の位置 /// </param> /// <returns> /// なし /// </returns> void remove_column(const size_type pos) { if (m_width <= pos) { throw std::out_of_range("Grid::remove_column() index out of range"); } size_type index = 0; m_data.remove_if([width = m_width, col = pos, &index](const value_type&) { return ((index++) % width == col); }); --m_width; } void remove_columns(const size_type pos, const size_type count) { if (m_width <= pos || m_width < (pos + count)) { throw std::out_of_range("Grid::remove_rows() index out of range"); } size_type index = 0; m_data.remove_if([width = m_width, a = pos, b = pos + count, &index](const value_type&) { const size_type col = (index++) % width; return a <= col && col < b; }); m_width -= count; } /// <summary> /// 二次元配列のサイズを変更します。 /// </summary> /// <param name="w"> /// 新しい幅(列数) /// </param> /// <param name="h"> /// 新しい高さ(行数) /// </param> /// <returns> /// なし /// </returns> void resize(const size_type w, const size_type h) { resize(w, h, value_type()); } /// <summary> /// 二次元配列のサイズを変更します。 /// </summary> /// <param name="size"> /// 新しい幅(列数)と高さ(行数) /// </param> /// <returns> /// なし /// </returns> void resize(const Size& size) { resize(size.x, size.y, value_type()); } /// <summary> /// 二次元配列のサイズを変更します。 /// </summary> /// <param name="w"> /// 新しい幅(列数) /// </param> /// <param name="h"> /// 新しい高さ(行数) /// </param> /// <param name="val"> /// 要素を初期化する値 /// </param> /// <returns> /// なし /// </returns> void resize(const size_type w, const size_type h, const value_type& val) { if (w == m_width && h == m_height) { return; } m_width = w; m_height = h; m_data.assign(w * h, val); } /// <summary> /// 二次元配列のサイズを変更します。 /// </summary> /// <param name="size"> /// 新しい幅(列数)と高さ(行数) /// </param> /// <param name="val"> /// 要素を初期化する値 /// </param> /// <returns> /// なし /// </returns> void resize(const Size& size, const value_type& val) { resize(size.x, size.y, val); } template <class Fty = decltype(Id), std::enable_if_t<std::is_invocable_r_v<bool, Fty, Type>>* = nullptr> [[nodiscard]] bool all(Fty f = Id) const { return m_data.all(f); } template <class Fty = decltype(Id), std::enable_if_t<std::is_invocable_r_v<bool, Fty, Type>>* = nullptr> [[nodiscard]] bool any(Fty f = Id) const { return m_data.any(f); } [[nodiscard]] const value_type& choice() const { return m_data.choice(); } template <class URBG, std::enable_if_t<!std::is_scalar_v<URBG> && std::is_invocable_r_v<size_t, URBG>>* = nullptr> [[nodiscard]] const value_type& choice(URBG&& rbg) const { return m_data.choice(std::forward<URBG>(rbg)); } template <class Size_t, std::enable_if_t<std::is_integral_v<Size_t>>* = nullptr> [[nodiscard]] Array<value_type> choice(const Size_t n) const { return m_data.choice(n); } template <class URBG, std::enable_if_t<!std::is_scalar_v<URBG> && std::is_invocable_r_v<size_t, URBG>>* = nullptr> [[nodiscard]] Array<value_type> choice(const size_t n, URBG&& rbg) const { return m_data.choice(n, std::forward<URBG>(rbg)); } [[nodiscard]] size_t count(const value_type& value) const { return m_data.count(value); } template <class Fty, std::enable_if_t<std::is_invocable_r_v<bool, Fty, Type>>* = nullptr> [[nodiscard]] size_t count_if(Fty f) const { return m_data.count_if(f); } template <class Fty, std::enable_if_t<std::is_invocable_v<Fty, Type&>>* = nullptr> Grid& each(Fty f) { m_data.each(f); return *this; } template <class Fty, std::enable_if_t<std::is_invocable_v<Fty, Type>>* = nullptr> const Grid& each(Fty f) const { m_data.each(f); return *this; } template <class Fty, std::enable_if_t<std::is_invocable_v<Fty, Type&>>* = nullptr> Grid& each_index(Fty f) { if (!m_data.empty()) { pointer p = m_data.data(); for (size_t y = 0; y < m_height; ++y) { for (size_t x = 0; x < m_width; ++x) { f({ x,y }, *p++); } } } return *this; } template <class Fty, std::enable_if_t<std::is_invocable_v<Fty, Type>>* = nullptr> const Grid& each_index(Fty f) const { if (!m_data.empty()) { const_pointer p = m_data.data(); for (size_t y = 0; y < m_height; ++y) { for (size_t x = 0; x < m_width; ++x) { f({ x,y }, *p++); } } } return *this; } [[nodiscard]] const value_type& fetch(size_type y, size_type x, const value_type& defaultValue) const { if (!inBounds(y, x)) { return defaultValue; } return m_data[y * m_width + x]; } [[nodiscard]] const value_type& fetch(const Point& pos, const value_type& defaultValue) const { return fetch(pos.y, pos.x, defaultValue); } Grid& fill(const value_type& value) { m_data.fill(value); return *this; } [[nodiscard]] bool include(const value_type& value) const { return m_data.include(value); } template <class Fty> [[nodiscard]] bool include_if(Fty f) const { return m_data.include_if(f); } template <class Fty, std::enable_if_t<std::is_invocable_v<Fty, Type>>* = nullptr> auto map(Fty f) const { Array<std::decay_t<std::invoke_result_t<Fty, Type>>> new_grid; new_grid.reserve(m_width * m_height); for (const auto& v : m_data) { new_grid.push_back(f(v)); } return Grid<std::decay_t<std::invoke_result_t<Fty, Type>>>(m_width, m_height, std::move(new_grid)); } template <class Fty = decltype(Id), std::enable_if_t<std::is_invocable_r_v<bool, Fty, Type>>* = nullptr> [[nodiscard]] bool none(Fty f = Id) const { return m_data.none(f); } template <class Fty, class R = std::decay_t<std::invoke_result_t<Fty, Type, Type>>> auto reduce(Fty f, R init) const { return m_data.reduce(f, init); } template <class Fty, std::enable_if_t<std::is_invocable_v<Fty, Type, Type>>* = nullptr> auto reduce1(Fty f) const { if (m_data.empty()) { throw std::out_of_range("Grid::reduce1() reduce from empty Grid"); } return m_data.reduce1(f); } Grid& replace(const value_type& oldValue, const value_type& newValue) { m_data.replace(oldValue, newValue); return *this; } [[nodiscard]] Grid replaced(const value_type& oldValue, const value_type& newValue) const & { Grid new_grid; new_grid.reserve(m_width, m_height); for (const auto& v : m_data) { if (v == oldValue) { new_grid.push_back(newValue); } else { new_grid.push_back(v); } } return new_grid; } [[nodiscard]] Grid replaced(const value_type& oldValue, const value_type& newValue) && { replace(oldValue, newValue); return std::move(*this); } template <class Fty, std::enable_if_t<std::is_invocable_r_v<bool, Fty, Type>>* = nullptr> Grid& replace_if(Fty f, const value_type& newValue) { m_data.replace_if(f, newValue); return *this; } template <class Fty, std::enable_if_t<std::is_invocable_r_v<bool, Fty, Type>>* = nullptr> [[nodiscard]] Grid replaced_if(Fty f, const value_type& newValue) const & { Grid new_grid; new_grid.reserve(m_width, m_height); for (const auto& v : m_data) { if (f(v)) { new_grid.push_back(newValue); } else { new_grid.push_back(v); } } new_grid.m_width = m_width; new_grid.m_height = m_height; return new_grid; } template <class Fty, std::enable_if_t<std::is_invocable_r_v<bool, Fty, Type>>* = nullptr> [[nodiscard]] Grid replaced_if(Fty f, const value_type& newValue) && { replace_if(f, newValue); return std::move(*this); } Grid& reverse() { std::reverse(m_data.begin(), m_data.end()); return *this; } [[nodiscard]] Grid reversed() const & { Grid new_grid; new_grid.m_data.assign(m_data.rbegin(), m_data.rend()); new_grid.m_width = m_width; new_grid.m_height = m_height; return new_grid; } [[nodiscard]] Grid reversed() && { reverse(); return std::move(*this); } template <class Fty, std::enable_if_t<std::is_invocable_v<Fty, Type&>>* = nullptr> Grid& reverse_each(Fty f) { for (auto it = m_data.rbegin(); it != m_data.rend(); ++it) { f(*it); } return *this; } template <class Fty, std::enable_if_t<std::is_invocable_v<Fty, Type>>* = nullptr> const Grid& reverse_each(Fty f) const { for (auto it = m_data.rbegin(); it != m_data.rend(); ++it) { f(*it); } return *this; } Grid& rotate(std::ptrdiff_t count = 1) { if (empty()) { ; } else if (count > 0) // rotation to the left { if (static_cast<size_t>(count) > m_data.size()) { count %= m_data.size(); } std::rotate(m_data.begin(), m_data.begin() + count, m_data.end()); } else if (count < 0) // rotation to the right { count = -count; if (static_cast<size_t>(count) > m_data.size()) { count %= m_data.size(); } std::rotate(m_data.rbegin(), m_data.rbegin() + count, m_data.rend()); } return *this; } [[nodiscard]] Grid rotated(const std::ptrdiff_t count = 1) const & { return Grid(*this).rotate(count); } [[nodiscard]] Grid rotated(const std::ptrdiff_t count = 1) && { rotate(count); return std::move(*this); } Grid& rotate_rows(const std::ptrdiff_t count = 1) { return rotate(count * static_cast<std::ptrdiff_t>(m_width)); } [[nodiscard]] Grid rotated_rows(const std::ptrdiff_t count = 1) const & { return rotated(count * static_cast<std::ptrdiff_t>(m_width)); } [[nodiscard]] Grid rotated_rows(const std::ptrdiff_t count = 1) && { return rotated(count * static_cast<std::ptrdiff_t>(m_width)); } Grid& shuffle() { return shuffle(GetDefaultRNG()); } template <class URBG, std::enable_if_t<!std::is_scalar_v<URBG> && std::is_invocable_r_v<size_t, URBG>>* = nullptr> Grid& shuffle(URBG&& rbg) { std::shuffle(begin(), end(), std::forward<URBG>(rbg)); return *this; } [[nodiscard]] Grid shuffled() const & { return shuffled(GetDefaultRNG()); } [[nodiscard]] Grid shuffled() && { return shuffled(GetDefaultRNG()); } template <class URBG, std::enable_if_t<!std::is_scalar_v<URBG> && std::is_invocable_r_v<size_t, URBG>>* = nullptr> [[nodiscard]] Grid shuffled(URBG&& rbg) const & { return Grid(*this).shuffle(std::forward<URBG>(rbg)); } template <class URBG, std::enable_if_t<!std::is_scalar_v<URBG> && std::is_invocable_r_v<size_t, URBG>>* = nullptr> [[nodiscard]] Grid shuffled(URBG&& rbg) && { shuffle(std::forward<URBG>(rbg)); return std::move(*this); } [[nodiscard]] Array<value_type> slice(const size_type y, const size_type x) const { if (!inBounds(y, x)) { return Array<value_type>(); } return Array<value_type>(m_data.begin() + (y * m_width + x), m_data.end()); } [[nodiscard]] Array<value_type> slice(const Point& pos) const { return slice(pos.y, pos.x); } [[nodiscard]] Array<value_type> slice(const size_type y, const size_type x, const size_t length) const { if (!inBounds(y, x)) { return Array<value_type>(); } const size_type index = (y * m_width + x); return Array<value_type>(m_data.begin() + index, m_data.begin() + std::min(index + length, m_data.size())); } [[nodiscard]] Array<value_type> slice(const Point& pos, const size_t length) const { return slice(pos.y, pos.x, length); } Grid& sort() { std::sort(m_data.begin(), m_data.end()); return *this; } template <class Fty, std::enable_if_t<std::is_invocable_r_v<bool, Fty, Type, Type>>* = nullptr> Grid& sort_by(Fty f) { std::sort(m_data.begin(), m_data.end(), f); return *this; } [[nodiscard]] Grid sorted() const & { return Grid(*this).sort(); } [[nodiscard]] Grid sorted() && { sort(); return std::move(*this); } template <class Fty, std::enable_if_t<std::is_invocable_r_v<bool, Fty, Type, Type>>* = nullptr> [[nodiscard]] Grid sorted_by(Fty f) const & { return Grid(*this).sort_by(f); } template <class Fty, std::enable_if_t<std::is_invocable_r_v<bool, Fty, Type, Type>>* = nullptr> [[nodiscard]] Grid sorted_by(Fty f) && { sort_by(f); return std::move(*this); } [[nodiscard]] Array<value_type> values_at(std::initializer_list<Point> indices) const { Array<value_type> new_array; new_array.reserve(indices.size()); for (auto index : indices) { if (index >= size()) { throw std::out_of_range("Grid::values_at() index out of range"); } new_array.push_back(operator[](index)); } return new_array; } }; template <class Type> [[nodiscard]] inline bool operator ==(const Grid<Type>& x, const Grid<Type>& y) { return x.width() == y.width() && x.height() == y.height() && std::equal(x.begin(), x.end(), y.begin(), y.end()); } template <class Type> [[nodiscard]] inline bool operator !=(const Grid<Type>& x, const Grid<Type>& y) { return !(x == y); } } ////////////////////////////////////////////////// // // Format // ////////////////////////////////////////////////// namespace s3d { template <class Type, class Allocator> inline void Formatter(FormatData& formatData, const Grid<Type, Allocator>& value) { formatData.string.push_back(U'{'); bool isFirst = true; for (typename Grid<Type>::size_type y = 0; y < value.height(); ++y) { if (isFirst) { isFirst = false; } else { formatData.string.push_back(U','); formatData.string.push_back(U'\n'); } Formatter(formatData, value[y], value[y] + value.width()); } formatData.string.push_back(U'}'); } template <class Type, class Allocator> inline std::ostream & operator <<(std::ostream& output, const Grid<Type, Allocator>& value) { return output << Format(value).narrow(); } template <class Type, class Allocator> inline std::wostream & operator <<(std::wostream& output, const Grid<Type, Allocator>& value) { return output << Format(value).toWstr(); } # if defined(__cpp_deduction_guides) // deduction guide template <class Type> Grid(const std::initializer_list<std::initializer_list<Type>>&) -> Grid<Type>; # endif } ////////////////////////////////////////////////// // // Swap // ////////////////////////////////////////////////// namespace std { template <class Type> inline void swap(s3d::Grid<Type>& a, s3d::Grid<Type>& b) noexcept { a.swap(b); } }
/**************************************************************************** * Copyright 2014-2015 Trefilov Dmitrij * * * * 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 "ExpressionNode.h" namespace metacpp { namespace db { namespace detail { ExpressionNodeImplBase::ExpressionNodeImplBase() { } ExpressionNodeImplBase::~ExpressionNodeImplBase() { } ExpressionNodeImplColumn::ExpressionNodeImplColumn(const MetaFieldBase *metaField) : m_metaField(metaField) { } ExpressionNodeImplColumn::~ExpressionNodeImplColumn() { } EFieldType ExpressionNodeImplColumn::type() const { return m_metaField->type(); } ExpressionNodeType ExpressionNodeImplColumn::nodeType() const { return eNodeColumn; } bool ExpressionNodeImplColumn::isLeaf() const { return true; } const MetaFieldBase *ExpressionNodeImplColumn::metaField() const { return m_metaField; } ExpressionNodeImplLiteral::~ExpressionNodeImplLiteral() { } EFieldType ExpressionNodeImplLiteral::type() const { return m_value.type(); } ExpressionNodeType ExpressionNodeImplLiteral::nodeType() const { return eNodeLiteral; } bool ExpressionNodeImplLiteral::isLeaf() const { return true; } const Variant& ExpressionNodeImplLiteral::value() const { return m_value; } ExpressionNodeImplUnaryOperator::ExpressionNodeImplUnaryOperator(UnaryOperatorType op, ExpressionNodeImplPtr innerNode) : m_operator(op), m_innerNode(innerNode) { } ExpressionNodeImplUnaryOperator::~ExpressionNodeImplUnaryOperator() { } EFieldType ExpressionNodeImplUnaryOperator::type() const { return m_innerNode->type(); } ExpressionNodeType ExpressionNodeImplUnaryOperator::nodeType() const { return eNodeUnaryOperator; } bool ExpressionNodeImplUnaryOperator::isLeaf() const { return operatorType() == eUnaryOperatorPlus; } UnaryOperatorType ExpressionNodeImplUnaryOperator::operatorType() const { return m_operator; } ExpressionNodeImplPtr ExpressionNodeImplUnaryOperator::innerNode() const { return m_innerNode; } ExpressionNodeImplBinaryOperator::ExpressionNodeImplBinaryOperator(EFieldType type, BinaryOperatorType op, const ExpressionNodeImplPtr &lhs, const ExpressionNodeImplPtr &rhs) : m_type(type), m_operator(op), m_lhs(lhs), m_rhs(rhs) { } ExpressionNodeImplBinaryOperator::~ExpressionNodeImplBinaryOperator() { } EFieldType ExpressionNodeImplBinaryOperator::type() const { return m_type; } ExpressionNodeType ExpressionNodeImplBinaryOperator::nodeType() const { return eNodeBinaryOperator; } bool ExpressionNodeImplBinaryOperator::isLeaf() const { return false; } BinaryOperatorType ExpressionNodeImplBinaryOperator::operatorType() const { return m_operator; } ExpressionNodeImplPtr ExpressionNodeImplBinaryOperator::leftNode() const { return m_lhs; } ExpressionNodeImplPtr ExpressionNodeImplBinaryOperator::rightNode() const { return m_rhs; } ExpressionNodeImplFunctionCall::ExpressionNodeImplFunctionCall(EFieldType type, const char *funcName, std::initializer_list<ExpressionNodeImplPtr> &&argumentNodes) : m_type(type), m_functionName(funcName), m_argumentNodes(argumentNodes) { } ExpressionNodeImplFunctionCall::~ExpressionNodeImplFunctionCall() { } EFieldType ExpressionNodeImplFunctionCall::type() const { return m_type; } ExpressionNodeType ExpressionNodeImplFunctionCall::nodeType() const { return eNodeFunctionCall; } bool ExpressionNodeImplFunctionCall::isLeaf() const { return false; } const String &ExpressionNodeImplFunctionCall::functionName() const { return m_functionName; } const Array<ExpressionNodeImplPtr> &ExpressionNodeImplFunctionCall::argumentNodes() const { return m_argumentNodes; } ExpressionNodeImplNull::ExpressionNodeImplNull(EFieldType inferType) : m_type(inferType) { } ExpressionNodeImplNull::~ExpressionNodeImplNull() { } EFieldType ExpressionNodeImplNull::type() const { return m_type; } ExpressionNodeType ExpressionNodeImplNull::nodeType() const { return eNodeNull; } bool ExpressionNodeImplNull::isLeaf() const { return true; } EFieldType ExpressionNodeImplWhereClauseBase::type() const { return eFieldVoid; } bool ExpressionNodeImplWhereClauseBase::isLeaf() const { return false; } ExpressionNodeImplWhereClauseRelational::ExpressionNodeImplWhereClauseRelational(RelationOperatorType op, const ExpressionNodeImplPtr &lhs, const ExpressionNodeImplPtr &rhs) : m_operator(op), m_lhs(lhs), m_rhs(rhs) { } ExpressionNodeImplWhereClauseRelational::~ExpressionNodeImplWhereClauseRelational() { } bool ExpressionNodeImplWhereClauseRelational::complex() const { return false; } ExpressionNodeType ExpressionNodeImplWhereClauseRelational::nodeType() const { return eNodeWhereClauseRelational; } RelationOperatorType ExpressionNodeImplWhereClauseRelational::operatorType() const { return m_operator; } ExpressionNodeImplPtr ExpressionNodeImplWhereClauseRelational::leftNode() const { return m_lhs; } ExpressionNodeImplPtr ExpressionNodeImplWhereClauseRelational::rightNode() const { return m_rhs; } ExpressionNodeImplWhereClauseLogical::ExpressionNodeImplWhereClauseLogical(UnaryLogicalOperatorType op, const ExpressionNodeImplWhereClausePtr &inner) : m_operator(op), m_inner(inner) { } ExpressionNodeImplWhereClauseLogical::~ExpressionNodeImplWhereClauseLogical() { } bool ExpressionNodeImplWhereClauseLogical::complex() const { return false; } ExpressionNodeType ExpressionNodeImplWhereClauseLogical::nodeType() const { return eNodeWhereClauseLogical; } UnaryLogicalOperatorType ExpressionNodeImplWhereClauseLogical::operatorType() const { return m_operator; } ExpressionNodeImplWhereClausePtr ExpressionNodeImplWhereClauseLogical::innerNode() const { return m_inner; } ExpressionNodeImplWhereClauseConditional::ExpressionNodeImplWhereClauseConditional(ConditionalOperatorType op, const ExpressionNodeImplWhereClausePtr &lhs, const ExpressionNodeImplWhereClausePtr &rhs) : m_operator(op), m_lhs(lhs), m_rhs(rhs) { } ExpressionNodeImplWhereClauseConditional::~ExpressionNodeImplWhereClauseConditional() { } bool ExpressionNodeImplWhereClauseConditional::complex() const { return true; } ExpressionNodeType ExpressionNodeImplWhereClauseConditional::nodeType() const { return eNodeWhereClauseComplex; } ConditionalOperatorType ExpressionNodeImplWhereClauseConditional::operatorType() const { return m_operator; } ExpressionNodeImplWhereClausePtr ExpressionNodeImplWhereClauseConditional::leftNode() const { return m_lhs; } ExpressionNodeImplWhereClausePtr ExpressionNodeImplWhereClauseConditional::rightNode() const { return m_rhs; } ExpressionNodeImplCastOperator::ExpressionNodeImplCastOperator(EFieldType type, ExpressionNodeImplPtr innerNode) : m_type(type), m_innerNode(innerNode) { } ExpressionNodeImplCastOperator::~ExpressionNodeImplCastOperator() { } EFieldType ExpressionNodeImplCastOperator::type() const { return m_type; } ExpressionNodeType ExpressionNodeImplCastOperator::nodeType() const { return eNodeCastOperator; } bool ExpressionNodeImplCastOperator::isLeaf() const { return false; } ExpressionNodeImplPtr ExpressionNodeImplCastOperator::innerNode() const { return m_innerNode; } } // namespace detail ExpressionNodeBase::ExpressionNodeBase(detail::ExpressionNodeImplPtr impl) : m_impl(impl) { } ExpressionNodeBase::~ExpressionNodeBase() { } detail::ExpressionNodeImplPtr ExpressionNodeBase::impl() const { return m_impl; } bool ExpressionNodeBase::empty() const { return !m_impl; } EFieldType ExpressionNodeBase::type() const { return impl()->type(); } ExpressionNodeType ExpressionNodeBase::nodeType() const { return impl()->nodeType(); } bool ExpressionNodeBase::isLeaf() const { return impl()->isLeaf(); } ExpressionNodeWhereClause operator&&(const ExpressionNodeWhereClause &lhs, const ExpressionNodeWhereClause &rhs) { return ExpressionNodeWhereClause(std::make_shared<detail::ExpressionNodeImplWhereClauseConditional>(eConditionalOperatorAnd, std::dynamic_pointer_cast<detail::ExpressionNodeImplWhereClauseBase>(lhs.impl()), std::dynamic_pointer_cast<detail::ExpressionNodeImplWhereClauseBase>(rhs.impl()))); } ExpressionNodeWhereClause operator||(const ExpressionNodeWhereClause &lhs, const ExpressionNodeWhereClause &rhs) { return ExpressionNodeWhereClause(std::make_shared<detail::ExpressionNodeImplWhereClauseConditional>(eConditionalOperatorOr, std::dynamic_pointer_cast<detail::ExpressionNodeImplWhereClauseBase>(lhs.impl()), std::dynamic_pointer_cast<detail::ExpressionNodeImplWhereClauseBase>(rhs.impl()))); } ExpressionNodeWhereClause operator!(const ExpressionNodeWhereClause &inner) { return ExpressionNodeWhereClause(std::make_shared<detail::ExpressionNodeImplWhereClauseLogical>(eLogicalOperatorNot, std::dynamic_pointer_cast<detail::ExpressionNodeImplWhereClauseBase>(inner.impl()))); } ExpressionNodeWhereClause metacpp::db::ExpressionNode<String>::like(const String &val) { return ExpressionNodeWhereClause(std::make_shared<detail::ExpressionNodeImplWhereClauseRelational> (eRelationalOperatorLike, this->impl(), std::make_shared<detail::ExpressionNodeImplLiteral>(val))); } ExpressionNodeWhereClause metacpp::db::ExpressionNode<String>::like(const ExpressionNode<String> &other) { return ExpressionNodeWhereClause(std::make_shared<detail::ExpressionNodeImplWhereClauseRelational> (eRelationalOperatorLike, this->impl(), other.impl())); } } // namespace db } // namespace metacpp
//================================================================================================= /*! // \file src/mathtest/simd/ComplexShort.cpp // \brief Source file for the SIMD operation test for 'complex<short>' // // Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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 names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/util/Complex.h> #include <blazetest/mathtest/simd/OperationTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running SIMD test for 'complex<short>'..." << std::endl; try { RUN_SIMD_OPERATION_TEST( blaze::complex<short> ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during SIMD operation:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
#include "Virus.h" #include "Pessoa.h" Virus::Virus(string c1) { //ctor } Virus::~Virus() { //dtor }
// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "gtest/gtest.h" #include "shared_test_classes/base/layer_test_utils.hpp" #include "gflag_config.hpp" #include "conformance.hpp" static std::vector<std::string> splitStringByDelimiter(std::string str, const std::string& delimiter = ",") { size_t delimiterPos; std::vector<std::string> irPaths; while ((delimiterPos = str.find(delimiter)) != std::string::npos) { irPaths.push_back(str.substr(0, delimiterPos)); str = str.substr(delimiterPos + 1); } irPaths.push_back(str); return irPaths; } int main(int argc, char* argv[]) { FuncTestUtils::SkipTestsConfig::disable_tests_skipping = true; LayerTestsUtils::extendReport = true; // Workaround for Gtest + Gflag std::vector<char*> argv_gflags_vec; int argc_gflags = 0; for (int i = 0; i < argc; ++i) { std::string arg(argv[i]); if (arg.find("gtest") == std::string::npos) { argv_gflags_vec.emplace_back(argv[i]); argc_gflags++; } } char** argv_gflags = argv_gflags_vec.data(); // ---------------------------Parsing and validation of input args-------------------------------------- gflags::ParseCommandLineNonHelpFlags(&argc_gflags, &argv_gflags, true); if (FLAGS_h) { showUsage(); return 0; } if (!FLAGS_disable_test_config) { FuncTestUtils::SkipTestsConfig::disable_tests_skipping = false; } if (!FLAGS_extend_report) { LayerTestsUtils::extendReport = false; } // ---------------------------Initialization of Gtest env ----------------------------------------------- ConformanceTests::targetDevice = FLAGS_device.c_str(); ConformanceTests::IRFolderPaths = splitStringByDelimiter(FLAGS_input_folders); ::testing::InitGoogleTest(&argc, argv); ::testing::AddGlobalTestEnvironment(new LayerTestsUtils::TestEnvironment); return RUN_ALL_TESTS();; }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <locale> // template <class charT> bool ispunct (charT c, const locale& loc); #include <locale> #include <cassert> int main() { std::locale l; assert(!std::ispunct(' ', l)); assert( std::ispunct('<', l)); assert(!std::ispunct('\x8', l)); assert(!std::ispunct('A', l)); assert(!std::ispunct('a', l)); assert(!std::ispunct('z', l)); assert(!std::ispunct('3', l)); assert( std::ispunct('.', l)); assert(!std::ispunct('f', l)); assert(!std::ispunct('9', l)); assert( std::ispunct('+', l)); }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/quota/mock_quota_manager.h" #include <memory> #include <set> #include "base/bind.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/macros.h" #include "base/run_loop.h" #include "base/threading/thread_task_runner_handle.h" #include "content/public/test/mock_special_storage_policy.h" #include "content/public/test/mock_storage_client.h" #include "testing/gtest/include/gtest/gtest.h" using storage::kQuotaStatusOk; using storage::kStorageTypePersistent; using storage::kStorageTypeTemporary; namespace content { const char kTestOrigin1[] = "http://host1:1/"; const char kTestOrigin2[] = "http://host2:1/"; const char kTestOrigin3[] = "http://host3:1/"; const GURL kOrigin1(kTestOrigin1); const GURL kOrigin2(kTestOrigin2); const GURL kOrigin3(kTestOrigin3); const StorageType kTemporary = kStorageTypeTemporary; const StorageType kPersistent = kStorageTypePersistent; const QuotaClient::ID kClientFile = QuotaClient::kFileSystem; const QuotaClient::ID kClientDB = QuotaClient::kIndexedDatabase; class MockQuotaManagerTest : public testing::Test { public: MockQuotaManagerTest() : deletion_callback_count_(0), weak_factory_(this) { } void SetUp() override { ASSERT_TRUE(data_dir_.CreateUniqueTempDir()); policy_ = new MockSpecialStoragePolicy; manager_ = new MockQuotaManager(false /* is_incognito */, data_dir_.path(), base::ThreadTaskRunnerHandle::Get().get(), base::ThreadTaskRunnerHandle::Get().get(), policy_.get()); } void TearDown() override { // Make sure the quota manager cleans up correctly. manager_ = NULL; base::RunLoop().RunUntilIdle(); } void GetModifiedOrigins(StorageType type, base::Time since) { manager_->GetOriginsModifiedSince( type, since, base::Bind(&MockQuotaManagerTest::GotModifiedOrigins, weak_factory_.GetWeakPtr())); } void GotModifiedOrigins(const std::set<GURL>& origins, StorageType type) { origins_ = origins; type_ = type; } void DeleteOriginData(const GURL& origin, StorageType type, int quota_client_mask) { manager_->DeleteOriginData( origin, type, quota_client_mask, base::Bind(&MockQuotaManagerTest::DeletedOriginData, weak_factory_.GetWeakPtr())); } void DeletedOriginData(QuotaStatusCode status) { ++deletion_callback_count_; EXPECT_EQ(kQuotaStatusOk, status); } int deletion_callback_count() const { return deletion_callback_count_; } MockQuotaManager* manager() const { return manager_.get(); } const std::set<GURL>& origins() const { return origins_; } const StorageType& type() const { return type_; } private: base::MessageLoop message_loop_; base::ScopedTempDir data_dir_; scoped_refptr<MockQuotaManager> manager_; scoped_refptr<MockSpecialStoragePolicy> policy_; int deletion_callback_count_; std::set<GURL> origins_; StorageType type_; base::WeakPtrFactory<MockQuotaManagerTest> weak_factory_; DISALLOW_COPY_AND_ASSIGN(MockQuotaManagerTest); }; TEST_F(MockQuotaManagerTest, BasicOriginManipulation) { EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kTemporary, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kTemporary, kClientDB)); EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kPersistent, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kPersistent, kClientDB)); EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kTemporary, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kTemporary, kClientDB)); EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kPersistent, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kPersistent, kClientDB)); manager()->AddOrigin(kOrigin1, kTemporary, kClientFile, base::Time::Now()); EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kTemporary, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kTemporary, kClientDB)); EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kPersistent, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kPersistent, kClientDB)); EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kTemporary, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kTemporary, kClientDB)); EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kPersistent, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kPersistent, kClientDB)); manager()->AddOrigin(kOrigin1, kPersistent, kClientFile, base::Time::Now()); EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kTemporary, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kTemporary, kClientDB)); EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kPersistent, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kPersistent, kClientDB)); EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kTemporary, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kTemporary, kClientDB)); EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kPersistent, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kPersistent, kClientDB)); manager()->AddOrigin(kOrigin2, kTemporary, kClientFile | kClientDB, base::Time::Now()); EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kTemporary, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kTemporary, kClientDB)); EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kPersistent, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin1, kPersistent, kClientDB)); EXPECT_TRUE(manager()->OriginHasData(kOrigin2, kTemporary, kClientFile)); EXPECT_TRUE(manager()->OriginHasData(kOrigin2, kTemporary, kClientDB)); EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kPersistent, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kPersistent, kClientDB)); } TEST_F(MockQuotaManagerTest, OriginDeletion) { manager()->AddOrigin(kOrigin1, kTemporary, kClientFile, base::Time::Now()); manager()->AddOrigin(kOrigin2, kTemporary, kClientFile | kClientDB, base::Time::Now()); manager()->AddOrigin(kOrigin3, kTemporary, kClientFile | kClientDB, base::Time::Now()); DeleteOriginData(kOrigin2, kTemporary, kClientFile); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, deletion_callback_count()); EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kTemporary, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kTemporary, kClientFile)); EXPECT_TRUE(manager()->OriginHasData(kOrigin2, kTemporary, kClientDB)); EXPECT_TRUE(manager()->OriginHasData(kOrigin3, kTemporary, kClientFile)); EXPECT_TRUE(manager()->OriginHasData(kOrigin3, kTemporary, kClientDB)); DeleteOriginData(kOrigin3, kTemporary, kClientFile | kClientDB); base::RunLoop().RunUntilIdle(); EXPECT_EQ(2, deletion_callback_count()); EXPECT_TRUE(manager()->OriginHasData(kOrigin1, kTemporary, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin2, kTemporary, kClientFile)); EXPECT_TRUE(manager()->OriginHasData(kOrigin2, kTemporary, kClientDB)); EXPECT_FALSE(manager()->OriginHasData(kOrigin3, kTemporary, kClientFile)); EXPECT_FALSE(manager()->OriginHasData(kOrigin3, kTemporary, kClientDB)); } TEST_F(MockQuotaManagerTest, ModifiedOrigins) { base::Time now = base::Time::Now(); base::Time then = base::Time(); base::TimeDelta an_hour = base::TimeDelta::FromMilliseconds(3600000); base::TimeDelta a_minute = base::TimeDelta::FromMilliseconds(60000); GetModifiedOrigins(kTemporary, then); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(origins().empty()); manager()->AddOrigin(kOrigin1, kTemporary, kClientFile, now - an_hour); GetModifiedOrigins(kTemporary, then); base::RunLoop().RunUntilIdle(); EXPECT_EQ(kTemporary, type()); EXPECT_EQ(1UL, origins().size()); EXPECT_EQ(1UL, origins().count(kOrigin1)); EXPECT_EQ(0UL, origins().count(kOrigin2)); manager()->AddOrigin(kOrigin2, kTemporary, kClientFile, now); GetModifiedOrigins(kTemporary, then); base::RunLoop().RunUntilIdle(); EXPECT_EQ(kTemporary, type()); EXPECT_EQ(2UL, origins().size()); EXPECT_EQ(1UL, origins().count(kOrigin1)); EXPECT_EQ(1UL, origins().count(kOrigin2)); GetModifiedOrigins(kTemporary, now - a_minute); base::RunLoop().RunUntilIdle(); EXPECT_EQ(kTemporary, type()); EXPECT_EQ(1UL, origins().size()); EXPECT_EQ(0UL, origins().count(kOrigin1)); EXPECT_EQ(1UL, origins().count(kOrigin2)); } } // namespace content
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "LevelViewportLayout.h" #include "Layout/Margin.h" #include "Widgets/DeclarativeSyntaxSupport.h" #include "Widgets/SCompoundWidget.h" #include "Widgets/SOverlay.h" #include "Framework/Docking/LayoutService.h" #include "Misc/ConfigCacheIni.h" #include "Layout/WidgetPath.h" #include "Framework/Application/SlateApplication.h" #include "Widgets/Layout/SBorder.h" #include "Widgets/Layout/SSpacer.h" #include "Widgets/SCanvas.h" #include "EditorStyleSet.h" #include "Editor/UnrealEdEngine.h" #include "UnrealEdGlobals.h" #include "Widgets/Docking/SDockTab.h" namespace ViewportLayoutDefs { /** How many seconds to interpolate from restored to maximized state */ static const float MaximizeTransitionTime = 0.15f; /** How many seconds to interpolate from maximized to restored state */ static const float RestoreTransitionTime = 0.2f; /** Default maximized state for new layouts - will only be applied when no config data is restoring state */ static const bool bDefaultShouldBeMaximized = true; /** Default immersive state for new layouts - will only be applied when no config data is restoring state */ static const bool bDefaultShouldBeImmersive = false; } // SViewportsOverlay //////////////////////////////////////////////// /** * Overlay wrapper class so that we can cache the size of the widget * It will also store the LevelViewportLayout data because that data can't be stored * per app; it must be stored per viewport overlay in case the app that made it closes. */ class SViewportsOverlay : public SCompoundWidget { public: SLATE_BEGIN_ARGS( SViewportsOverlay ){} SLATE_DEFAULT_SLOT( FArguments, Content ) SLATE_ARGUMENT( TSharedPtr<FLevelViewportTabContent>, LevelViewportTab ) SLATE_END_ARGS() void Construct( const FArguments& InArgs ); /** Default constructor */ SViewportsOverlay() : CachedSize( FVector2D::ZeroVector ) {} /** Overridden from SWidget */ virtual void Tick( const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime ) override; /** Wraps SOverlay::AddSlot() */ SOverlay::FOverlaySlot& AddSlot(); /** Wraps SOverlay::RemoveSlot() */ void RemoveSlot(); /** * Returns the cached size of this viewport overlay * * @return The size that was cached */ const FVector2D& GetCachedSize() const; /** Gets the Level Viewport Tab that created this overlay */ TSharedPtr<FLevelViewportTabContent> GetLevelViewportTab() const; private: /** Reference to the owning level viewport tab */ TSharedPtr<FLevelViewportTabContent> LevelViewportTab; /** The overlay widget we're containing */ TSharedPtr< SOverlay > OverlayWidget; /** Cache our size, so that we can use this when animating a viewport maximize/restore */ FVector2D CachedSize; }; void SViewportsOverlay::Construct( const FArguments& InArgs ) { const TSharedRef<SWidget>& ContentWidget = InArgs._Content.Widget; LevelViewportTab = InArgs._LevelViewportTab; ChildSlot [ SAssignNew( OverlayWidget, SOverlay ) + SOverlay::Slot() [ ContentWidget ] ]; } void SViewportsOverlay::Tick( const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime ) { CachedSize = AllottedGeometry.Size; } SOverlay::FOverlaySlot& SViewportsOverlay::AddSlot() { return OverlayWidget->AddSlot(); } void SViewportsOverlay::RemoveSlot() { return OverlayWidget->RemoveSlot(); } const FVector2D& SViewportsOverlay::GetCachedSize() const { return CachedSize; } TSharedPtr<FLevelViewportTabContent> SViewportsOverlay::GetLevelViewportTab() const { return LevelViewportTab; } // FLevelViewportLayout ///////////////////////////// FLevelViewportLayout::FLevelViewportLayout() : bIsTransitioning( false ), bIsReplacement( false ), bIsQueryingLayoutMetrics( false ), bIsMaximizeSupported( true ), bIsMaximized( false ), bIsImmersive( false ), bWasMaximized( false ), bWasImmersive( false ), MaximizedViewportStartPosition( FVector2D::ZeroVector ), MaximizedViewportStartSize( FVector2D::ZeroVector ) { ViewportReplacementWidget = SNew( SSpacer ); } FLevelViewportLayout::~FLevelViewportLayout() { for (auto& Pair : Viewports) { Pair.Value->OnLayoutDestroyed(); } // Make sure that we're not locking the immersive window after we go away if( bIsImmersive || ( bWasImmersive && bIsTransitioning ) ) { TSharedPtr< SWindow > OwnerWindow( CachedOwnerWindow.Pin() ); if( OwnerWindow.IsValid() ) { OwnerWindow->SetFullWindowOverlayContent( NULL ); } } } TSharedRef<SWidget> FLevelViewportLayout::BuildViewportLayout( TSharedPtr<SDockTab> InParentDockTab, TSharedPtr<FLevelViewportTabContent> InParentTab, const FString& LayoutString, TWeakPtr<ILevelEditor> InParentLevelEditor ) { // We don't support reconfiguring an existing layout object, as this makes handling of transitions // particularly difficult. Instead just destroy the old layout and create a new layout object. check( !ParentTab.IsValid() ); ParentTab = InParentDockTab; ParentTabContent = InParentTab; ParentLevelEditor = InParentLevelEditor; MaximizedViewport = NAME_None; // We use an overlay so that we can draw a maximized viewport on top of the other viewports TSharedPtr<SBorder> ViewportsBorder; TSharedRef<SViewportsOverlay> ViewportsOverlay = SNew( SViewportsOverlay ) .LevelViewportTab(InParentTab) [ SAssignNew( ViewportsBorder, SBorder ) .Padding( 0.0f ) .BorderImage( FEditorStyle::GetBrush("NoBorder") ) .Visibility( this, &FLevelViewportLayout::OnGetNonMaximizedVisibility ) ]; ViewportsOverlayPtr = ViewportsOverlay; // Don't set the content until the OverlayPtr has been set, because it access this when we want to start with the viewports maximized. ViewportsBorder->SetContent( MakeViewportLayout(LayoutString) ); return ViewportsOverlay; } void FLevelViewportLayout::BeginThrottleForAnimatedResize() { // Only enter this mode if there is not already a request if( !ViewportResizeThrottleRequest.IsValid() ) { if( !FSlateApplication::Get().IsRunningAtTargetFrameRate() ) { ViewportResizeThrottleRequest = FSlateThrottleManager::Get().EnterResponsiveMode(); } } } void FLevelViewportLayout::EndThrottleForAnimatedResize() { // Only leave this mode if there is a request if( ViewportResizeThrottleRequest.IsValid() ) { FSlateThrottleManager::Get().LeaveResponsiveMode( ViewportResizeThrottleRequest ); } } void FLevelViewportLayout::InitCommonLayoutFromString( const FString& SpecificLayoutString, FName DefaultMaximizedViewport ) { bool bShouldBeMaximized = bIsMaximizeSupported && ViewportLayoutDefs::bDefaultShouldBeMaximized; bool bShouldBeImmersive = ViewportLayoutDefs::bDefaultShouldBeImmersive; if (!SpecificLayoutString.IsEmpty()) { const FString& IniSection = FLayoutSaveRestore::GetAdditionalLayoutConfigIni(); // NOTE: We don't support starting back up in immersive mode, even if the user shut down with a window that way. See the // comment below in SaveCommonLayoutString() for more info. GConfig->GetBool(*IniSection, *(SpecificLayoutString + TEXT(".bIsMaximized")), bShouldBeMaximized, GEditorPerProjectIni); FString MaximizedViewportString; if (GConfig->GetString(*IniSection, *(SpecificLayoutString + TEXT(".MaximizedViewport")), MaximizedViewportString, GEditorPerProjectIni)) { DefaultMaximizedViewport = *MaximizedViewportString; } } // Replacement layouts (those selected by the user via a command) don't start maximized so the layout can be seen clearly. if (!bIsReplacement && bIsMaximizeSupported && Viewports.Contains(DefaultMaximizedViewport) && (bShouldBeMaximized || bShouldBeImmersive)) { // we are not toggling maximize or immersive state but setting it directly const bool bToggle=false; // Do not allow animation at startup as it hitches const bool bAllowAnimation=false; MaximizeViewport(DefaultMaximizedViewport, bShouldBeMaximized, bShouldBeImmersive, bAllowAnimation); } } void FLevelViewportLayout::SaveCommonLayoutString( const FString& SpecificLayoutString ) const { const FString& IniSection = FLayoutSaveRestore::GetAdditionalLayoutConfigIni(); // Save all our data using the additional layout config for (auto& Pair : Viewports) { // The Viewports map is keyed on the full config name, so no need to prepend the SpecificLayoutString FString ConfigName = Pair.Key.ToString(); Pair.Value->SaveConfig(ConfigName); GConfig->SetString( *IniSection, *( ConfigName + TEXT(".TypeWithinLayout") ), *Pair.Value->GetType().ToString(), GEditorPerProjectIni ); } // We don't bother saving that we were in immersive mode, because we never want to start back up directly in immersive mode // unless the user asks for that on the command-line. The reason is it can be disorientating to not see any editor UI when // to restart the editor. In this case, we'll store the mode they were previously in before they switched to immersive mode. if( bIsImmersive ) { GConfig->SetBool( *IniSection, *( SpecificLayoutString + TEXT( ".bIsMaximized" ) ), bIsMaximizeSupported && bWasMaximized, GEditorPerProjectIni ); } else { GConfig->SetBool(*IniSection, *(SpecificLayoutString + TEXT(".bIsMaximized")), bIsMaximizeSupported && bIsMaximized, GEditorPerProjectIni); } GConfig->SetString( *IniSection, *( SpecificLayoutString + TEXT( ".MaximizedViewport" ) ), *MaximizedViewport.ToString(), GEditorPerProjectIni ); } void FLevelViewportLayout::RequestMaximizeViewport( FName ViewportToMaximize, const bool bWantMaximize, const bool bWantImmersive, const bool bAllowAnimation ) { if( bAllowAnimation ) { // Ensure the UI is responsive when animating the transition to/from maximize BeginThrottleForAnimatedResize(); // We flush commands here because there could be a pending slow viewport draw already enqueued in the render thread // We take the hitch here so that our transition to/from maximize animation is responsive next tick FlushRenderingCommands(); DeferredMaximizeCommands.Add( FMaximizeViewportCommand(ViewportToMaximize, bWantMaximize, bWantImmersive) ); } else { // Not animating so just maximise now MaximizeViewport( ViewportToMaximize, bWantMaximize, bWantImmersive, bAllowAnimation ); } } void FLevelViewportLayout::MaximizeViewport( FName ViewportToMaximize, const bool bWantMaximize, const bool bWantImmersive, const bool bAllowAnimation ) { TSharedPtr<IViewportLayoutEntity> Entity = Viewports.FindRef(ViewportToMaximize); // Should never get into a situation where the viewport is being maximized and there is already a maximized viewport. // I.E Maximized viewport is NULL which means this is a new maximize or MaximizeViewport is equal to the passed in one which means this is a restore of the current maximized viewport check( Entity.IsValid() ); check( MaximizedViewport.IsNone() || MaximizedViewport == ViewportToMaximize ); // If we're already in immersive mode, toggling maximize just needs to update some state (no visual change) if( bIsImmersive ) { bIsMaximized = bWantMaximize; } // Any changes? if( bWantMaximize != bIsMaximized || bWantImmersive != bIsImmersive ) { // Are we already animating a transition? if( bIsTransitioning ) { // Instantly finish up the current transition FinishMaximizeTransition(); check( !bIsTransitioning ); } TSharedPtr<SWindow> OwnerWindow; // NOTE: Careful, FindWidgetWindow can be reentrant in that it can call visibility delegates and such FWidgetPath ViewportWidgetPath; bIsQueryingLayoutMetrics = true; if( bIsMaximized || bIsImmersive ) { // Use the replacement widget for metrics, as our viewport widget has been reparented to the overlay OwnerWindow = FSlateApplication::Get().FindWidgetWindow( ViewportReplacementWidget.ToSharedRef(), ViewportWidgetPath ); } else { // Viewport is still within the splitter, so use it for metrics directly OwnerWindow = FSlateApplication::Get().FindWidgetWindow( Entity->AsWidget(), ViewportWidgetPath ); } bIsQueryingLayoutMetrics = false; // If the widget can't be found in the layout pass, attempt to use the cached owner window if(!OwnerWindow.IsValid() && CachedOwnerWindow.IsValid()) { OwnerWindow = CachedOwnerWindow.Pin(); } else { // Keep track of the window we're contained in // @todo immersive: Caching this after the transition is risky -- the widget could be moved to a new window! // We really need a safe way to query a widget's window that doesn't require a full layout pass. Then, // instead of caching the window we can look it up whenever it's needed CachedOwnerWindow = OwnerWindow; } if( !bIsImmersive && bWantImmersive ) { // If we can't find our owner window, that means we're likely hosted in a background tab, thus // can't continue with an immersive transition. We never want immersive mode to take over the // window when the user couldn't even see the viewports before! if( !OwnerWindow.IsValid() ) { return; } // Make sure that our viewport layout has a lock on the window's immersive state. Only one // layout can have a single immersive viewport at a time, so if something else is already immersive, // we need to fail the layout change. if( OwnerWindow->HasFullWindowOverlayContent() ) { // We can't continue with the layout change, a different window is already immersive return; } } // Update state bWasMaximized = bIsMaximized; bWasImmersive = bIsImmersive; bIsMaximized = bWantMaximize; bIsImmersive = bWantImmersive; // Start transition bIsTransitioning = true; if( bAllowAnimation ) { // Ensure responsiveness while transitioning BeginThrottleForAnimatedResize(); } if( ( bWasMaximized && !bIsMaximized ) || ( bWasImmersive && !bIsImmersive ) ) { // Play the transition backwards. Note that when transitioning from immersive mode, depending on // the current state of bIsMaximized, we'll transition to either a maximized state or a "restored" state MaximizeAnimation = FCurveSequence(); MaximizeAnimation.AddCurve( 0.0f, ViewportLayoutDefs::RestoreTransitionTime, ECurveEaseFunction::CubicIn ); MaximizeAnimation.PlayReverse( ViewportsOverlayWidget->AsShared() ); if( bWasImmersive && !bIsImmersive ) { OwnerWindow->BeginFullWindowOverlayTransition(); } } else { if( bIsImmersive && ( bWasMaximized && bIsMaximized ) ) { // Unhook our viewport overlay, as we'll let the window overlay drive this for immersive mode ViewportsOverlayPtr.Pin()->RemoveSlot(); } else { // Store the maximized viewport MaximizedViewport = ViewportToMaximize; TSharedPtr<IViewportLayoutEntity> MaximizedEntity = Viewports.FindRef(MaximizedViewport); if (MaximizedEntity.IsValid()) { // Replace our viewport with a dummy widget in it's place during the maximize transition. We can't // have a single viewport widget in two places at once! ReplaceWidget( MaximizedEntity->AsWidget(), ViewportReplacementWidget.ToSharedRef() ); TSharedRef< SCanvas > Canvas = SNew( SCanvas ); Canvas->AddSlot() .Position( TAttribute< FVector2D >( this, &FLevelViewportLayout::GetMaximizedViewportPositionOnCanvas ) ) .Size( TAttribute< FVector2D >( this, &FLevelViewportLayout::GetMaximizedViewportSizeOnCanvas ) ) [ MaximizedEntity->AsWidget() ]; ViewportsOverlayWidget = Canvas; } } // Add the maximized viewport as a top level overlay if( bIsImmersive ) { OwnerWindow->SetFullWindowOverlayContent( ViewportsOverlayWidget ); OwnerWindow->BeginFullWindowOverlayTransition(); } else { // Create a slot in our overlay to hold the content ViewportsOverlayPtr.Pin()->AddSlot() [ ViewportsOverlayWidget.ToSharedRef() ]; } // Play the "maximize" transition MaximizeAnimation = FCurveSequence(); MaximizeAnimation.AddCurve( 0.0f, ViewportLayoutDefs::MaximizeTransitionTime, ECurveEaseFunction::CubicOut ); MaximizeAnimation.Play( ViewportsOverlayWidget->AsShared() ); } // We'll only be able to get metrics if we could find an owner window. Usually that's OK, because the only // chance for this code to trigger without an owner window would be at startup, where we might ask to maximize // a viewport based on saved layout, while that viewport is hosted in a background tab. For this case, we'll // never animate (checked here), so we don't need to store "before" metrics. check( OwnerWindow.IsValid() || !bAllowAnimation ); if( OwnerWindow.IsValid() && ViewportWidgetPath.IsValid() ) { // Setup transition metrics if( bIsImmersive || bWasImmersive ) { const FVector2D WindowScreenPos = OwnerWindow->GetPositionInScreen(); if( bIsMaximized || bWasMaximized ) { FWidgetPath ViewportsOverlayWidgetPath = ViewportWidgetPath.GetPathDownTo( ViewportsOverlayPtr.Pin().ToSharedRef() ); const FArrangedWidget& ViewportsOverlayGeometry = ViewportsOverlayWidgetPath.Widgets.Last(); MaximizedViewportStartPosition = ViewportsOverlayGeometry.Geometry.AbsolutePosition - WindowScreenPos; MaximizedViewportStartSize = ViewportsOverlayPtr.Pin()->GetCachedSize(); } else { const FArrangedWidget& ViewportGeometry = ViewportWidgetPath.Widgets.Last(); MaximizedViewportStartPosition = ViewportGeometry.Geometry.AbsolutePosition - WindowScreenPos; MaximizedViewportStartSize = ViewportGeometry.Geometry.Size; } } else { const FArrangedWidget& ViewportGeometry = ViewportWidgetPath.Widgets.Last(); MaximizedViewportStartPosition = ViewportGeometry.Geometry.Position; MaximizedViewportStartSize = ViewportGeometry.Geometry.Size; } } if( !bAllowAnimation ) { // Instantly finish up the current transition FinishMaximizeTransition(); check( !bIsTransitioning ); } // Redraw all other viewports, in case there were changes made while in immersive mode that may affect // the view in other viewports. GUnrealEd->RedrawLevelEditingViewports(); } } FVector2D FLevelViewportLayout::GetMaximizedViewportPositionOnCanvas() const { FVector2D EndPos = FVector2D::ZeroVector; if( bIsImmersive ) { TSharedPtr< SWindow > OwnerWindow( CachedOwnerWindow.Pin() ); if( OwnerWindow.IsValid() && OwnerWindow->IsWindowMaximized() ) { // When maximized we offset by the window border size or else the immersive viewport will be clipped FMargin WindowContentMargin = OwnerWindow->GetWindowBorderSize(); EndPos.Set( WindowContentMargin.Right, WindowContentMargin.Bottom ); } } return FMath::Lerp( MaximizedViewportStartPosition, EndPos, MaximizeAnimation.GetLerp() ); } FVector2D FLevelViewportLayout::GetMaximizedViewportSizeOnCanvas() const { // NOTE: Should ALWAYS be valid, however because MaximizedViewport is changed in Tick, it's possible // for widgets we're adding/removing to already have been reported by ArrangeChildren, thus // we need to be able to handle cases where widgets that are not bound can still have delegates fire if( !MaximizedViewport.IsNone() || bWasImmersive ) { FVector2D TargetSize = FVector2D::ZeroVector; if( bIsImmersive || ( bIsTransitioning && bWasImmersive ) ) { TSharedPtr< SWindow > OwnerWindow( CachedOwnerWindow.Pin() ); if( OwnerWindow.IsValid() ) { FVector2D ClippedArea = FVector2D::ZeroVector; if( OwnerWindow->IsWindowMaximized() ) { // When the window is maximized and we are in immersive we size the canvas to the size of the visible area which does not include the window border const FMargin& WindowContentMargin = OwnerWindow->GetWindowBorderSize(); ClippedArea.Set( WindowContentMargin.GetTotalSpaceAlong<Orient_Horizontal>(), WindowContentMargin.GetTotalSpaceAlong<Orient_Vertical>() ); } TargetSize = (OwnerWindow->GetSizeInScreen() - ClippedArea)/OwnerWindow->GetNativeWindow()->GetDPIScaleFactor(); } } else { TargetSize = ViewportsOverlayPtr.Pin()->GetCachedSize(); } return FMath::Lerp( MaximizedViewportStartSize, TargetSize, MaximizeAnimation.GetLerp() ); } // No valid viewport to check size for return FVector2D::ZeroVector; } /** * @return true if this layout is visible. It is not visible if its parent tab is not active */ bool FLevelViewportLayout::IsVisible() const { return !ParentTab.IsValid() || ParentTab.Pin()->IsForeground(); } /** * Checks to see the specified level viewport is visible in this layout * A viewport is visible in a layout if the layout is visible and the viewport is the maximized viewport or there is no maximized viewport * * @param InViewport The viewport within this layout that should be checked * @return true if the viewport is visible. */ bool FLevelViewportLayout::IsLevelViewportVisible( FName InViewport ) const { // The passed in viewport is visible if the current layout is visible and their is no maximized viewport or the viewport that is maximized was passed in. return IsVisible() && ( MaximizedViewport.IsNone() || MaximizedViewport == InViewport ); } bool FLevelViewportLayout::IsViewportMaximized( FName InViewport ) const { return bIsMaximized && MaximizedViewport == InViewport; } bool FLevelViewportLayout::IsViewportImmersive( FName InViewport ) const { return bIsImmersive && MaximizedViewport == InViewport; } EVisibility FLevelViewportLayout::OnGetNonMaximizedVisibility() const { // The non-maximized viewports are not visible if there is a maximized viewport on top of them return ( !bIsQueryingLayoutMetrics && !MaximizedViewport.IsNone() && !bIsTransitioning && DeferredMaximizeCommands.Num() == 0 ) ? EVisibility::Collapsed : EVisibility::Visible; } void FLevelViewportLayout::FinishMaximizeTransition() { if( bIsTransitioning ) { TSharedPtr<IViewportLayoutEntity> MaximizedViewportEntity = Viewports.FindRef(MaximizedViewport); check(MaximizedViewportEntity.IsValid()); // The transition animation is complete, allow the engine to tick normally EndThrottleForAnimatedResize(); // Jump to the end if we're not already there MaximizeAnimation.JumpToEnd(); if( bIsImmersive ) { TSharedPtr< SWindow > OwnerWindow( CachedOwnerWindow.Pin() ); if( OwnerWindow.IsValid() ) { OwnerWindow->EndFullWindowOverlayTransition(); } // Finished transition from restored/maximized to immersive, if this is a PIE window we need to re-register it to capture the mouse. MaximizedViewportEntity->RegisterGameViewportIfPIE(); } else if( bIsMaximized && !bWasImmersive ) { // Finished transition from restored to immersive, if this is a PIE window we need to re-register it to capture the mouse. MaximizedViewportEntity->RegisterGameViewportIfPIE(); } else if( bWasImmersive ) // Finished transition from immersive to restored/maximized { TSharedPtr< SWindow > OwnerWindow( CachedOwnerWindow.Pin() ); if( OwnerWindow.IsValid() ) { OwnerWindow->SetFullWindowOverlayContent( NULL ); OwnerWindow->EndFullWindowOverlayTransition(); } // Release overlay mouse capture to prevent situations where user is unable to get the mouse cursor back if they were holding one of the buttons down and exited immersive mode. FSlateApplication::Get().ReleaseMouseCapture(); if( bIsMaximized ) { // If we're transitioning from immersive to maximized, then we need to add our // viewport back to the viewport overlay ViewportsOverlayPtr.Pin()->AddSlot() [ ViewportsOverlayWidget.ToSharedRef() ]; // Now that the viewport is nested within the overlay again, reset our animation so that // our metrics callbacks return the correct value (not the reserved value) MaximizeAnimation.Reverse(); MaximizeAnimation.JumpToEnd(); } else { // @todo immersive: Viewport flashes yellow for one frame in this transition point (immersive -> restored only!) } } else { // Finished transition from maximized to restored // Kill off our viewport overlay now that the animation has finished ViewportsOverlayPtr.Pin()->RemoveSlot(); } // Stop transitioning if( !bIsImmersive && !bIsMaximized ) { // We're finished with this temporary overlay widget now ViewportsOverlayWidget.Reset(); // Restore the viewport widget into the viewport layout splitter ReplaceWidget( ViewportReplacementWidget.ToSharedRef(), MaximizedViewportEntity->AsWidget() ); MaximizedViewport = NAME_None; } bIsTransitioning = false; // Update keyboard focus. Focus is usually lost when we re-parent the viewport widget. { // We first need to clear keyboard focus so that Slate doesn't assume that focus won't need to change // simply because the viewport widget object is the same -- it has a new widget path! FSlateApplication::Get().ClearKeyboardFocus( EFocusCause::SetDirectly ); // Set keyboard focus directly MaximizedViewportEntity->SetKeyboardFocus(); } // If this is a PIE window we need to re-register since the maximized window will have registered itself // as the game viewport. MaximizedViewportEntity->RegisterGameViewportIfPIE(); } } void FLevelViewportLayout::Tick( float DeltaTime ) { // If we have an animation that has finished playing, then complete the transition if( bIsTransitioning && !MaximizeAnimation.IsPlaying() ) { FinishMaximizeTransition(); } /** Resolve any maximizes or immersive commands for the viewports */ if (DeferredMaximizeCommands.Num() > 0) { // Allow the engine to tick normally. EndThrottleForAnimatedResize(); for (int32 i = 0; i < DeferredMaximizeCommands.Num(); ++i) { FMaximizeViewportCommand& Command = DeferredMaximizeCommands[i]; // Only bother with deferred maximize if we don't already have a maximized or immersive viewport unless we are toggling if( MaximizedViewport.IsNone() || Command.bToggle ) { MaximizeViewport(Command.Viewport, Command.bMaximize, Command.bImmersive, Command.bAllowAnimation ); } } DeferredMaximizeCommands.Empty(); } } bool FLevelViewportLayout::IsTickable() const { return DeferredMaximizeCommands.Num() > 0 || ( bIsTransitioning && !MaximizeAnimation.IsPlaying() ); }
/*- * Copyright (c) 2002-2018 The UbixOS Project. * All rights reserved. * * This was developed by Christopher W. Olsen for the UbixOS Project. * * 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, the following disclaimer and the list of authors. * 2) Redistributions in binary form must reproduce the above copyright notice, this list of * conditions, the following disclaimer and the list of authors in the documentation and/or * other materials provided with the distribution. * 3) Neither the name of the UbixOS Project 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 AUTHOR AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ extern "C" { #include <lib/kmalloc.h> #include <sys/video.h> void __pure_virtual() { while (1) asm("nop"); } void __cxa_pure_virtual() { while (1) asm("nop"); } /* Don't plan on exiting the kernel...so do nothing. */ int __cxa_atexit(void (*func)(void *), void * arg, void * d) { return 0; } void __dso_handle() { while (1) asm("nop"); } } #include <lib/libcpp.h> void * operator new[](unsigned size) { return kmalloc(size); } void operator delete[](void * ptr) { kfree(ptr); return; } void * operator new(unsigned size) { void * ptr = kmalloc(size); return ptr; } void operator delete(void * ptr) { kfree(ptr); return; }
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <cstddef> #include "DataStructures/Tensor/Tensor.hpp" #include "Parallel/CharmPupable.hpp" #include "PointwiseFunctions/AnalyticData/AnalyticData.hpp" #include "Utilities/FakeVirtual.hpp" #include "Utilities/TMPL.hpp" #include "Utilities/TaggedTuple.hpp" namespace Poisson { /// Analytic solutions of the Poisson equation namespace Solutions { /*! * \brief Base class for analytic solutions of the Poisson equation * * This abstract base class allows factory-creating derived classes from * input-file options (see `Registration`). The list of `Registrars` may also * contain classes that aren't analytic solutions but only derive off * `::AnalyticData`. This allows factory-creating any choice of analytic * solution _or_ analytic data from input-file options, but you must use the * `::AnalyticData` class for the factory-creation. Note that analytic solutions * provide more variables than analytic data classes, so to request variables * that only analytic solutions provide you must perform a cast to * `AnalyticSolution`. */ template <size_t Dim, typename Registrars> class AnalyticSolution : public ::AnalyticData<Dim, Registrars> { private: using Base = ::AnalyticData<Dim, Registrars>; protected: /// \cond AnalyticSolution() = default; AnalyticSolution(const AnalyticSolution&) = default; AnalyticSolution(AnalyticSolution&&) = default; AnalyticSolution& operator=(const AnalyticSolution&) = default; AnalyticSolution& operator=(AnalyticSolution&&) = default; /// \endcond public: ~AnalyticSolution() override = default; using registrars = Registrars; using creatable_classes = Registration::registrants<registrars>; /// \cond explicit AnalyticSolution(CkMigrateMessage* m) noexcept : Base(m) {} WRAPPED_PUPable_abstract(AnalyticSolution); // NOLINT /// \endcond template <typename DataType, typename... RequestedTags> tuples::TaggedTuple<RequestedTags...> variables( const tnsr::I<DataType, Dim>& x, tmpl::list<RequestedTags...> /*meta*/) const noexcept { return call_with_dynamic_type< tuples::TaggedTuple<RequestedTags...>, tmpl::filter< creatable_classes, std::is_base_of<AnalyticSolution<Dim, Registrars>, tmpl::_1>>>( this, [&x](auto* const derived) noexcept { return derived->variables(x, tmpl::list<RequestedTags...>{}); }); } }; } // namespace Solutions } // namespace Poisson
/* * This file is a part of the open source stm32plus library. * Copyright (c) 2011,2012,2013 Andy Brown <www.andybrown.me.uk> * Please see website for licensing terms. */ #include "config/stm32plus.h" #include "config/usart.h" using namespace stm32plus; /** * USART test: asynchronous sending data using interrupts * * This example will send the string "Hello World" using * USART1. Connect an RS232 cable from USART1 to your PC * and run a terminal program (there are many free * terminal programs) to see the data. The default * (unremapped) USART1 pins are used. * * We use interrupts to send the data. The hardware * raises a TXE interrupt when it's ready to send a * character and we do just that. When we get to the end * of the string we disable the TXE interrupt so it * doesn't fire again. * * Note that if you are using the STM32F4DISCOVERY * board then you cannot use Usart1 since the pins clash * with onboard peripherals. I have tested this code on * that board using Usart2. * * The protocol is 57600/8/N/1 * * Compatible MCU: * STM32F1 * STM32F4 * * Tested on devices: * STM32F103VET6 * STM32F407VGT6 */ class UsartSendInterruptsTest { protected: /* * The string we are going to send */ const char *_dataToSend; /* * The USART1 peripheral configured with the interrupt feature */ typedef Usart1InterruptFeature MyUsartInterrupt; Usart1<MyUsartInterrupt> _usart; public: /* * Use the constructor base initialiser to set up the USART at 57600 */ UsartSendInterruptsTest() : _usart(57600) { } /* * Run the test */ void run() { // we're using interrupts, set up the NVIC Nvic::initialise(); // set the initial string pointer _dataToSend="Hello World"; // register ourselves as an observer of the USART interrupts _usart.UsartInterruptEventSender.insertSubscriber( UsartInterruptEventSourceSlot::bind(this,&UsartSendInterruptsTest::onInterrupt) ); // enable interrupts. this will cause an immediate ready-to-send interrupt _usart.enableInterrupts(MyUsartInterrupt::TRANSMIT); // finished for(;;); } /* * Interrupt callback function. This is called when the TXE interrupt that we've * enabled is fired. */ void onInterrupt(UsartEventType uet) { if(uet==UsartEventType::EVENT_READY_TO_TRANSMIT && *_dataToSend) { // send the next character and increment the pointer _usart.send(*_dataToSend++); // if we are now at the end of the string then disable further interrupts // because we are done if(*_dataToSend=='\0') _usart.disableInterrupts(MyUsartInterrupt::TRANSMIT); } } }; /* * Main entry point */ int main() { UsartSendInterruptsTest test; test.run(); // not reached return 0; }
/* * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <proxygen/lib/http/codec/HQStreamCodec.h> #include <folly/Format.h> #include <folly/ScopeGuard.h> #include <folly/SingletonThreadLocal.h> #include <folly/io/Cursor.h> #include <proxygen/lib/http/HTTP3ErrorCode.h> #include <proxygen/lib/http/codec/HQUtils.h> #include <proxygen/lib/http/codec/compress/QPACKCodec.h> namespace proxygen { namespace hq { using namespace folly; using namespace folly::io; using std::string; HQStreamCodec::HQStreamCodec(StreamID streamId, TransportDirection direction, QPACKCodec& headerCodec, folly::IOBufQueue& encoderWriteBuf, folly::IOBufQueue& decoderWriteBuf, folly::Function<uint64_t()> qpackEncoderMaxData, HTTPSettings& egressSettings, HTTPSettings& ingressSettings, bool transportSupportsPartialReliability) : HQFramedCodec(streamId, direction), headerCodec_(headerCodec), qpackEncoderWriteBuf_(encoderWriteBuf), qpackDecoderWriteBuf_(decoderWriteBuf), qpackEncoderMaxDataFn_(std::move(qpackEncoderMaxData)), egressSettings_(egressSettings), ingressSettings_(ingressSettings), transportSupportsPartialReliability_( transportSupportsPartialReliability) { VLOG(4) << "creating " << getTransportDirectionString(direction) << " HQ stream codec for stream " << streamId_; } HQStreamCodec::~HQStreamCodec() { } ParseResult HQStreamCodec::checkFrameAllowed(FrameType type) { switch (type) { case hq::FrameType::SETTINGS: case hq::FrameType::GOAWAY: case hq::FrameType::MAX_PUSH_ID: case hq::FrameType::CANCEL_PUSH: return HTTP3::ErrorCode::HTTP_WRONG_STREAM; case hq::FrameType::PUSH_PROMISE: if (transportDirection_ == TransportDirection::DOWNSTREAM) { return HTTP3::ErrorCode::HTTP_WRONG_STREAM; } default: break; } return folly::none; } ParseResult HQStreamCodec::parseData(Cursor& cursor, const FrameHeader& header) { // It's possible the data is in the wrong place per HTTP semantics, but it // will be caught by HTTPTransaction std::unique_ptr<IOBuf> outData; VLOG(10) << "parsing all frame DATA bytes for stream=" << streamId_ << " length=" << header.length; auto res = hq::parseData(cursor, header, outData); if (res) { return res; } // no need to do deliverCallbackIfAllowed // the HQSession can trap this and stop reading. // i.e we can immediately reset in onNewStream if we get a stream id // higher than MAXID advertised in the goaway if (callback_ && (outData && !outData->empty())) { callback_->onBody(streamId_, std::move(outData), 0); } return res; } void HQStreamCodec::onIngressPartiallyReliableBodyStarted( uint64_t streamOffset) { CHECK(transportSupportsPartialReliability()) << __func__ << ": partially reliable operation on non-partially reliable transport"; CHECK(!ingressPrBodyTracker_.bodyStarted()) << ": partially realible body tracker already started"; // Starts tracking the body byte offsets. // streamOffset becomes the beginning (0-offset) of the body offset. ingressPrBodyTracker_.startBodyTracking(streamOffset); ingressPartiallyReliable_ = true; if (callback_) { callback_->onUnframedBodyStarted(streamId_, streamOffset); } } ParseResult HQStreamCodec::parsePartiallyReliableData(Cursor& cursor) { CHECK(transportSupportsPartialReliability()) << __func__ << ": partially reliable operation on non-partially reliable transport"; std::unique_ptr<IOBuf> outData; auto dataLength = cursor.totalLength(); VLOG(10) << "parsing all frame DATA bytes for stream=" << streamId_ << " length=" << dataLength; DCHECK(ingressPrBodyTracker_.bodyStarted()); if (!ingressPrBodyTracker_.bodyStarted()) { LOG(ERROR) << __func__ << ": body hasn't started yet"; return HTTP3::ErrorCode::HTTP_GENERAL_PROTOCOL_ERROR; } cursor.clone(outData, dataLength); ingressPrBodyTracker_.addBodyBytesProcessed(dataLength); if (callback_ && outData && !outData->empty()) { callback_->onBody(streamId_, std::move(outData), 0 /* padding */); } return folly::none; } ParseResult HQStreamCodec::parseHeaders(Cursor& cursor, const FrameHeader& header) { if (finalIngressHeadersSeen_) { // No Trailers for YOU! if (callback_) { HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS, "Invalid HEADERS frame"); ex.setErrno(uint32_t(HTTP3::ErrorCode::HTTP_FRAME_UNEXPECTED)); callback_->onError(streamId_, ex, false); } setParserPaused(true); return folly::none; } std::unique_ptr<IOBuf> outHeaderData; auto res = hq::parseHeaders(cursor, header, outHeaderData); if (res) { return res; } if (callback_) { // H2 performs the decompression/semantic validation first. // Also, this should really only be called once per this whole codec, not // per header block -- think info status, and (shudder) trailers. This // behavior mirrors HTTP2Codec at present. callback_->onMessageBegin(streamId_, nullptr); } // TODO: Handle HTTP trailers (T35711545) decodeInfo_.init(transportDirection_ == TransportDirection::DOWNSTREAM, false /* isRequestTrailers */); headerCodec_.decodeStreaming( streamId_, std::move(outHeaderData), header.length, this); // decodeInfo_.msg gets moved in onHeadersComplete. If it is still around, // parsing is incomplete, and needs to be paused. if (decodeInfo_.msg) { setParserPaused(true); } return res; } ParseResult HQStreamCodec::parsePushPromise(Cursor& cursor, const FrameHeader& header) { PushId outPushId; std::unique_ptr<IOBuf> outHeaderData; auto res = hq::parsePushPromise(cursor, header, outPushId, outHeaderData); if (res) { return res; } // Notify the callback on beginning of a push promise. // The callback will be further notified when the header block // is fully parsed, via a call to `onHeadersComplete`. // It is up to the callback to match the push promise // with the headers block, via using same stream id if (callback_) { callback_->onPushMessageBegin(outPushId, streamId_, nullptr); } decodeInfo_.init(true /* isReq */, false /* isRequestTrailers */); auto headerDataLength = outHeaderData->computeChainDataLength(); headerCodec_.decodeStreaming( streamId_, std::move(outHeaderData), headerDataLength, this); if (decodeInfo_.msg) { // parsing incomplete, see comment in parseHeaders setParserPaused(true); } return res; } void HQStreamCodec::onHeader(const HPACKHeaderName& name, const folly::fbstring& value) { if (decodeInfo_.onHeader(name, value)) { if (userAgent_.empty() && name.getHeaderCode() == HTTP_HEADER_USER_AGENT) { userAgent_ = value.toStdString(); } } else { VLOG(4) << "dir=" << uint32_t(transportDirection_) << decodeInfo_.parsingError << " codec=" << headerCodec_; } } folly::Expected<uint64_t, UnframedBodyOffsetTrackerError> HQStreamCodec::onIngressDataAvailable(uint64_t streamOffset) { CHECK(transportSupportsPartialReliability()) << __func__ << ": partially reliable operation on non-partially reliable transport"; if (!finalIngressHeadersSeen_ || !ingressPrBodyTracker_.bodyStarted()) { // Do not raise onDataAvailable() before body starts. VLOG(4) << ": suppressing " << __func__ << " because body did not start yet"; return folly::makeUnexpected(UnframedBodyOffsetTrackerError::NO_ERROR); } auto bodyStreamStart = ingressPrBodyTracker_.getBodyStreamStartOffset(); if (bodyStreamStart.hasError()) { LOG(ERROR) << __func__ << ": error: " << bodyStreamStart.error(); return folly::makeUnexpected(bodyStreamStart.error()); } if (streamOffset < *bodyStreamStart) { LOG(ERROR) << __func__ << ": stream offset provided (" << streamOffset << ") is smaller than existing body stream offset: " << *bodyStreamStart; return folly::makeUnexpected( UnframedBodyOffsetTrackerError::INVALID_OFFSET); } auto bodyOffset = streamOffset - *bodyStreamStart; return bodyOffset; } folly::Expected<uint64_t, UnframedBodyOffsetTrackerError> HQStreamCodec::onIngressDataExpired(uint64_t streamOffset) { CHECK(transportSupportsPartialReliability()) << __func__ << ": partially reliable operation on non-partially reliable transport"; CHECK(ingressPartiallyReliable_) << __func__ << ": ingressPartiallyReliable_ is false"; if (!finalIngressHeadersSeen_) { // If we haven't received headers fully yet, ignore dataExpired. // This is a legitimate situation that can happen with re-ordering/missing // data, but we're not dealing with it right now. // TODO: Cache the offset until later we receive the headers, // and raise the callback then. VLOG(2) << __func__ << ": received ingress dataExpired before HEADERS are fully received"; return folly::makeUnexpected(UnframedBodyOffsetTrackerError::NO_ERROR); } auto bytesParsed = getCodecTotalBytesParsed(); // Shouldn't happen, but still check. if (streamOffset <= bytesParsed) { LOG(ERROR) << "got stream offset (" << streamOffset << ") <= than bytes already processed (" << bytesParsed << ")"; return folly::makeUnexpected( UnframedBodyOffsetTrackerError::INVALID_OFFSET); } CHECK(ingressPrBodyTracker_.bodyStarted()) << ": partially realible body tracker not started"; auto bodyStreamStart = ingressPrBodyTracker_.getBodyStreamStartOffset(); if (bodyStreamStart.hasError()) { LOG(ERROR) << __func__ << ": error: " << bodyStreamStart.error(); return folly::makeUnexpected(bodyStreamStart.error()); } if (streamOffset <= *bodyStreamStart) { LOG(ERROR) << __func__ << ": stream offset provided (" << streamOffset << ") is smaller than existing body stream offset: " << *bodyStreamStart; return folly::makeUnexpected( UnframedBodyOffsetTrackerError::INVALID_OFFSET); } auto bodyOffset = streamOffset - *bodyStreamStart; ingressPrBodyTracker_.maybeMoveBodyBytesProcessed(bodyOffset); return bodyOffset; } folly::Expected<uint64_t, UnframedBodyOffsetTrackerError> HQStreamCodec::onIngressDataRejected(uint64_t streamOffset) { CHECK(transportSupportsPartialReliability()) << __func__ << ": partially reliable operation on non-partially reliable transport"; if (!finalEgressHeadersSeen_) { // If we haven't even sent the headers yet, ignore the dataReject. LOG(ERROR) << __func__ << ": received DataRejected from receiver before egress headers " "are sent"; return folly::makeUnexpected( UnframedBodyOffsetTrackerError::INVALID_OFFSET); } auto bytesSent = getCodecTotalEgressBytes(); if (!egressPrBodyTracker_.bodyStarted()) { egressPrBodyTracker_.startBodyTracking(bytesSent); } auto bodyStreamStart = egressPrBodyTracker_.getBodyStreamStartOffset(); if (bodyStreamStart.hasError()) { LOG(ERROR) << __func__ << ": error: " << bodyStreamStart.error(); return folly::makeUnexpected(bodyStreamStart.error()); } if (streamOffset <= *bodyStreamStart) { LOG(ERROR) << __func__ << ": stream offset provided (" << streamOffset << ") is smaller than existing body stream offset: " << *bodyStreamStart; return folly::makeUnexpected( UnframedBodyOffsetTrackerError::INVALID_OFFSET); } auto bodyOffset = streamOffset - *bodyStreamStart; egressPrBodyTracker_.maybeMoveBodyBytesProcessed(bodyOffset); return bodyOffset; } folly::Expected<uint64_t, UnframedBodyOffsetTrackerError> HQStreamCodec::onEgressBodySkip(uint64_t bodyOffset) { CHECK(transportSupportsPartialReliability()) << __func__ << ": partially reliable operation on non-partially reliable transport"; if (!finalEgressHeadersSeen_) { // Application is trying to skip body data before having sent headers. LOG(ERROR) << __func__ << ": egress skip before HEADERS sent"; return folly::makeUnexpected( UnframedBodyOffsetTrackerError::INVALID_OFFSET); } auto bytesSent = getCodecTotalEgressBytes(); if (!egressPrBodyTracker_.bodyStarted()) { egressPrBodyTracker_.startBodyTracking(bytesSent); } egressPrBodyTracker_.maybeMoveBodyBytesProcessed(bodyOffset); auto streamOffset = egressPrBodyTracker_.appTostreamOffset(bodyOffset); if (streamOffset.hasError()) { LOG(ERROR) << __func__ << ": error: " << streamOffset.error(); return folly::makeUnexpected(streamOffset.error()); } return *streamOffset; } folly::Expected<uint64_t, UnframedBodyOffsetTrackerError> HQStreamCodec::onEgressBodyReject(uint64_t bodyOffset) { CHECK(transportSupportsPartialReliability()) << __func__ << ": partially reliable operation on non-partially reliable transport"; if (!finalIngressHeadersSeen_) { // Application is trying to skip body data before having received headers. LOG(ERROR) << __func__ << ": egress reject before HEADERS received"; return folly::makeUnexpected( UnframedBodyOffsetTrackerError::INVALID_OFFSET); } auto bytesSent = getCodecTotalEgressBytes(); if (!ingressPrBodyTracker_.bodyStarted()) { ingressPrBodyTracker_.startBodyTracking(bytesSent); } ingressPrBodyTracker_.maybeMoveBodyBytesProcessed(bodyOffset); auto streamOffset = ingressPrBodyTracker_.appTostreamOffset(bodyOffset); if (streamOffset.hasError()) { LOG(ERROR) << __func__ << ": error: " << streamOffset.error(); return folly::makeUnexpected(streamOffset.error()); } return *streamOffset; } void HQStreamCodec::onHeadersComplete(HTTPHeaderSize decodedSize, bool acknowledge) { decodeInfo_.onHeadersComplete(decodedSize); auto g = folly::makeGuard([this] { setParserPaused(false); }); auto g2 = folly::makeGuard(activationHook_()); std::unique_ptr<HTTPMessage> msg = std::move(decodeInfo_.msg); // Check parsing error if (decodeInfo_.parsingError != "") { LOG(ERROR) << "Failed parsing header list for stream=" << streamId_ << ", error=" << decodeInfo_.parsingError; HTTPException err( HTTPException::Direction::INGRESS, folly::format( "HQStreamCodec stream error: stream={} status={} error:{}", streamId_, 400, decodeInfo_.parsingError) .str()); err.setHttpStatusCode(400); callback_->onError(streamId_, err, true); return; } msg->setAdvancedProtocolString(getCodecProtocolString(CodecProtocol::HQ)); if (curHeader_.type == hq::FrameType::HEADERS) { if (!finalIngressHeadersSeen_ && (msg->isRequest() || !msg->is1xxResponse())) { finalIngressHeadersSeen_ = true; } } if (acknowledge) { qpackDecoderWriteBuf_.append(headerCodec_.encodeHeaderAck(streamId_)); } // Report back what we've parsed if (callback_) { // TODO: should we treat msg as chunked like H2? callback_->onHeadersComplete(streamId_, std::move(msg)); } } void HQStreamCodec::onDecodeError(HPACK::DecodeError decodeError) { // the parser may be paused, but this codec is dead. decodeInfo_.decodeError = decodeError; DCHECK_NE(decodeInfo_.decodeError, HPACK::DecodeError::NONE); LOG(ERROR) << "Failed decoding header block for stream=" << streamId_; if (decodeInfo_.msg) { // print the partial message decodeInfo_.msg->dumpMessage(3); } if (callback_) { auto g = folly::makeGuard(activationHook_()); HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS, "Stream headers decompression error"); ex.setErrno(uint32_t(HTTP3::ErrorCode::HTTP_QPACK_DECOMPRESSION_FAILED)); callback_->onError(kSessionStreamId, ex, false); } decodeInfo_.msg.reset(); } void HQStreamCodec::generateHeader(folly::IOBufQueue& writeBuf, StreamID stream, const HTTPMessage& msg, bool /*eom*/, HTTPHeaderSize* size) { DCHECK_EQ(stream, streamId_); // Partial reliability might already be set by ingress. egressPartiallyReliable_ = egressPartiallyReliable_ || msg.isPartiallyReliable(); generateHeaderImpl(writeBuf, msg, folly::none, size); // For requests, set final header seen flag right away. // For responses, header is final only if response code is >= 200. if (msg.isRequest() || (msg.isResponse() && msg.getStatusCode() >= 200)) { finalEgressHeadersSeen_ = true; } if (egressPartiallyReliable_ && finalEgressHeadersSeen_) { // Piggyback a 0-length DATA frame to kick off partially reliable body // streaming. CHECK(!egressPrBodyTracker_.bodyStarted()) << ": egress partially relialble body tracker already started"; auto curBytesSent = getCodecTotalEgressBytes(); auto res = hq::writeFrameHeader(writeBuf, FrameType::DATA, 0); if (res.hasValue()) { totalEgressBytes_ += res.value(); auto bodyStreamOffset = curBytesSent + *res; egressPrBodyTracker_.startBodyTracking(bodyStreamOffset); } else { LOG(ERROR) << __func__ << ": failed to write 0-length DATA frame: " << res.error(); } } } void HQStreamCodec::generatePushPromise(folly::IOBufQueue& writeBuf, StreamID stream, const HTTPMessage& msg, StreamID pushId, bool /*eom*/, HTTPHeaderSize* size) { DCHECK_EQ(stream, streamId_); DCHECK(transportDirection_ == TransportDirection::DOWNSTREAM); CHECK(!egressPartiallyReliable_) << __func__ << ": not allowed in partially reliable mode"; generateHeaderImpl(writeBuf, msg, pushId, size); } void HQStreamCodec::generateHeaderImpl(folly::IOBufQueue& writeBuf, const HTTPMessage& msg, folly::Optional<StreamID> pushId, HTTPHeaderSize* size) { auto result = headerCodec_.encodeHTTP( qpackEncoderWriteBuf_, msg, true, streamId_, maxEncoderStreamData()); if (size) { *size = headerCodec_.getEncodedSize(); } if (headerCodec_.getEncodedSize().uncompressed > ingressSettings_.getSetting(SettingsId::MAX_HEADER_LIST_SIZE, std::numeric_limits<uint32_t>::max())) { // The remote side told us they don't want headers this large... // but this function has no mechanism to fail string serializedHeaders; msg.getHeaders().forEach( [&serializedHeaders](const string& name, const string& value) { serializedHeaders = folly::to<string>(serializedHeaders, "\\n", name, ":", value); }); LOG(ERROR) << "generating HEADERS frame larger than peer maximum nHeaders=" << msg.getHeaders().size() << " all headers=" << serializedHeaders; } // HTTP2/2 serializes priority here, but HQ priorities need to go on the // control stream WriteResult res; if (pushId) { CHECK(!egressPartiallyReliable_) << ": push promise not allowed on partially reliable message"; res = hq::writePushPromise(writeBuf, *pushId, std::move(result)); } else { res = hq::writeHeaders(writeBuf, std::move(result)); } if (res.hasValue()) { totalEgressBytes_ += res.value(); } else { LOG(ERROR) << __func__ << ": failed to write " << ((pushId) ? "push promise: " : "headers: ") << res.error(); } } size_t HQStreamCodec::generateBodyImpl(folly::IOBufQueue& writeBuf, std::unique_ptr<folly::IOBuf> chain) { auto result = hq::writeData(writeBuf, std::move(chain)); if (result) { return *result; } LOG(FATAL) << "frame exceeded 2^62-1 limit"; return 0; } size_t HQStreamCodec::generatePartiallyReliableBodyImpl( folly::IOBufQueue& writeBuf, std::unique_ptr<folly::IOBuf> chain) { CHECK(transportSupportsPartialReliability()) << __func__ << ": partially reliable operation on non-partially reliable transport"; auto bodyLen = chain->computeChainDataLength(); CHECK(egressPrBodyTracker_.bodyStarted()) << ": partially realible body tracker not started"; auto result = hq::writeUnframedBytes(writeBuf, std::move(chain)); if (result) { egressPrBodyTracker_.addBodyBytesProcessed(bodyLen); return *result; } CHECK(false) << "failed to write unframed data"; return 0; } size_t HQStreamCodec::generateBody(folly::IOBufQueue& writeBuf, StreamID stream, std::unique_ptr<folly::IOBuf> chain, folly::Optional<uint8_t> /*padding*/, bool /*eom*/) { DCHECK_EQ(stream, streamId_); size_t bytesWritten = 0; if (egressPartiallyReliable_) { bytesWritten = generatePartiallyReliableBodyImpl(writeBuf, std::move(chain)); } else { bytesWritten = generateBodyImpl(writeBuf, std::move(chain)); } totalEgressBytes_ += bytesWritten; return bytesWritten; } size_t HQStreamCodec::generateEOM(folly::IOBufQueue& /*writeBuf*/, StreamID stream) { // Generate EOM is a no-op DCHECK_EQ(stream, streamId_); return 0; } CompressionInfo HQStreamCodec::getCompressionInfo() const { return headerCodec_.getCompressionInfo(); } }} // namespace proxygen::hq
#include "stdafx.h" #include <playfab/PFAuthentication.h> #include "Authentication.h" #include "ApiAsyncProviders.h" #include "GlobalState.h" #include "Entity.h" using namespace PlayFab; using namespace PlayFab::Authentication; HRESULT PFAuthenticationAdminCreateOpenIdConnectionAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationCreateOpenIdConnectionRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::AdminCreateOpenIdConnection, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationAdminCreatePlayerSharedSecretAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationCreatePlayerSharedSecretRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::AdminCreatePlayerSharedSecret, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationAdminCreatePlayerSharedSecretGetResultSize( _In_ XAsyncBlock* async, _Out_ size_t* bufferSize ) noexcept { return XAsyncGetResultSize(async, bufferSize); } HRESULT PFAuthenticationAdminCreatePlayerSharedSecretGetResult( _In_ XAsyncBlock* async, _In_ size_t bufferSize, _Out_writes_bytes_to_(bufferSize, *bufferUsed) void* buffer, _Outptr_ PFAuthenticationCreatePlayerSharedSecretResult** result, _Out_opt_ size_t* bufferUsed ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(result); RETURN_IF_FAILED(XAsyncGetResult(async, nullptr, bufferSize, buffer, bufferUsed)); *result = static_cast<PFAuthenticationCreatePlayerSharedSecretResult*>(buffer); return S_OK; } HRESULT PFAuthenticationAdminDeleteOpenIdConnectionAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationDeleteOpenIdConnectionRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::AdminDeleteOpenIdConnection, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationAdminDeletePlayerSharedSecretAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationDeletePlayerSharedSecretRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::AdminDeletePlayerSharedSecret, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationAdminGetPlayerSharedSecretsAsync( _In_ PFStateHandle contextHandle, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::AdminGetPlayerSharedSecrets, contextHandle->state, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationAdminGetPlayerSharedSecretsGetResultSize( _In_ XAsyncBlock* async, _Out_ size_t* bufferSize ) noexcept { return XAsyncGetResultSize(async, bufferSize); } HRESULT PFAuthenticationAdminGetPlayerSharedSecretsGetResult( _In_ XAsyncBlock* async, _In_ size_t bufferSize, _Out_writes_bytes_to_(bufferSize, *bufferUsed) void* buffer, _Outptr_ PFAuthenticationGetPlayerSharedSecretsResult** result, _Out_opt_ size_t* bufferUsed ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(result); RETURN_IF_FAILED(XAsyncGetResult(async, nullptr, bufferSize, buffer, bufferUsed)); *result = static_cast<PFAuthenticationGetPlayerSharedSecretsResult*>(buffer); return S_OK; } HRESULT PFAuthenticationAdminGetPolicyAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationGetPolicyRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::AdminGetPolicy, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationAdminGetPolicyGetResultSize( _In_ XAsyncBlock* async, _Out_ size_t* bufferSize ) noexcept { return XAsyncGetResultSize(async, bufferSize); } HRESULT PFAuthenticationAdminGetPolicyGetResult( _In_ XAsyncBlock* async, _In_ size_t bufferSize, _Out_writes_bytes_to_(bufferSize, *bufferUsed) void* buffer, _Outptr_ PFAuthenticationGetPolicyResponse** result, _Out_opt_ size_t* bufferUsed ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(result); RETURN_IF_FAILED(XAsyncGetResult(async, nullptr, bufferSize, buffer, bufferUsed)); *result = static_cast<PFAuthenticationGetPolicyResponse*>(buffer); return S_OK; } HRESULT PFAuthenticationAdminListOpenIdConnectionAsync( _In_ PFStateHandle contextHandle, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::AdminListOpenIdConnection, contextHandle->state, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationAdminListOpenIdConnectionGetResultSize( _In_ XAsyncBlock* async, _Out_ size_t* bufferSize ) noexcept { return XAsyncGetResultSize(async, bufferSize); } HRESULT PFAuthenticationAdminListOpenIdConnectionGetResult( _In_ XAsyncBlock* async, _In_ size_t bufferSize, _Out_writes_bytes_to_(bufferSize, *bufferUsed) void* buffer, _Outptr_ PFAuthenticationListOpenIdConnectionResponse** result, _Out_opt_ size_t* bufferUsed ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(result); RETURN_IF_FAILED(XAsyncGetResult(async, nullptr, bufferSize, buffer, bufferUsed)); *result = static_cast<PFAuthenticationListOpenIdConnectionResponse*>(buffer); return S_OK; } HRESULT PFAuthenticationAdminSetPlayerSecretAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationAdminSetPlayerSecretRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::AdminSetPlayerSecret, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationAdminUpdateOpenIdConnectionAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationUpdateOpenIdConnectionRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::AdminUpdateOpenIdConnection, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationAdminUpdatePlayerSharedSecretAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationUpdatePlayerSharedSecretRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::AdminUpdatePlayerSharedSecret, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationAdminUpdatePolicyAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationUpdatePolicyRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::AdminUpdatePolicy, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationAdminUpdatePolicyGetResultSize( _In_ XAsyncBlock* async, _Out_ size_t* bufferSize ) noexcept { return XAsyncGetResultSize(async, bufferSize); } HRESULT PFAuthenticationAdminUpdatePolicyGetResult( _In_ XAsyncBlock* async, _In_ size_t bufferSize, _Out_writes_bytes_to_(bufferSize, *bufferUsed) void* buffer, _Outptr_ PFAuthenticationUpdatePolicyResponse** result, _Out_opt_ size_t* bufferUsed ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(result); RETURN_IF_FAILED(XAsyncGetResult(async, nullptr, bufferSize, buffer, bufferUsed)); *result = static_cast<PFAuthenticationUpdatePolicyResponse*>(buffer); return S_OK; } HRESULT PFAuthenticationClientGetPhotonAuthenticationTokenAsync( _In_ PFTitlePlayerHandle contextHandle, _In_ const PFAuthenticationGetPhotonAuthenticationTokenRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientGetPhotonAuthenticationToken, contextHandle->titlePlayer, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientGetPhotonAuthenticationTokenGetResultSize( _In_ XAsyncBlock* async, _Out_ size_t* bufferSize ) noexcept { return XAsyncGetResultSize(async, bufferSize); } HRESULT PFAuthenticationClientGetPhotonAuthenticationTokenGetResult( _In_ XAsyncBlock* async, _In_ size_t bufferSize, _Out_writes_bytes_to_(bufferSize, *bufferUsed) void* buffer, _Outptr_ PFAuthenticationGetPhotonAuthenticationTokenResult** result, _Out_opt_ size_t* bufferUsed ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(result); RETURN_IF_FAILED(XAsyncGetResult(async, nullptr, bufferSize, buffer, bufferUsed)); *result = static_cast<PFAuthenticationGetPhotonAuthenticationTokenResult*>(buffer); return S_OK; } HRESULT PFAuthenticationClientGetTitlePublicKeyAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationGetTitlePublicKeyRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientGetTitlePublicKey, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientGetTitlePublicKeyGetResultSize( _In_ XAsyncBlock* async, _Out_ size_t* bufferSize ) noexcept { return XAsyncGetResultSize(async, bufferSize); } HRESULT PFAuthenticationClientGetTitlePublicKeyGetResult( _In_ XAsyncBlock* async, _In_ size_t bufferSize, _Out_writes_bytes_to_(bufferSize, *bufferUsed) void* buffer, _Outptr_ PFAuthenticationGetTitlePublicKeyResult** result, _Out_opt_ size_t* bufferUsed ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(result); RETURN_IF_FAILED(XAsyncGetResult(async, nullptr, bufferSize, buffer, bufferUsed)); *result = static_cast<PFAuthenticationGetTitlePublicKeyResult*>(buffer); return S_OK; } HRESULT PFAuthenticationClientLoginWithAndroidDeviceIDAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithAndroidDeviceIDRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithAndroidDeviceID, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginGetResult( _In_ XAsyncBlock* async, _Out_ PFTitlePlayerHandle* titlePlayerHandle ) noexcept { return XAsyncGetResult(async, nullptr, sizeof(PFTitlePlayerHandle), titlePlayerHandle, nullptr); } HRESULT PFAuthenticationClientLoginWithAppleAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithAppleRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithApple, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginWithCustomIDAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithCustomIDRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithCustomID, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginWithEmailAddressAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithEmailAddressRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithEmailAddress, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginWithFacebookAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithFacebookRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithFacebook, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginWithFacebookInstantGamesIdAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithFacebookInstantGamesIdRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithFacebookInstantGamesId, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginWithGameCenterAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithGameCenterRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithGameCenter, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginWithGoogleAccountAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithGoogleAccountRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithGoogleAccount, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginWithIOSDeviceIDAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithIOSDeviceIDRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithIOSDeviceID, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginWithKongregateAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithKongregateRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithKongregate, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginWithNintendoServiceAccountAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithNintendoServiceAccountRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithNintendoServiceAccount, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginWithNintendoSwitchDeviceIdAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithNintendoSwitchDeviceIdRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithNintendoSwitchDeviceId, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginWithOpenIdConnectAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithOpenIdConnectRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithOpenIdConnect, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginWithPlayFabAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithPlayFabRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithPlayFab, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginWithPSNAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithPSNRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithPSN, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginWithSteamAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithSteamRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithSteam, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginWithTwitchAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithTwitchRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithTwitch, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientLoginWithXboxAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationClientLoginWithXboxRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientLoginWithXbox, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } #if HC_PLATFORM == HC_PLATFORM_GDK HRESULT PFAuthenticationLoginWithXUserAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithXUserRequest* request, _Inout_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::LoginWithXUser, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } #endif HRESULT PFAuthenticationClientRegisterPlayFabUserAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationRegisterPlayFabUserRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientRegisterPlayFabUser, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationClientRegisterPlayFabUserGetResult( _In_ XAsyncBlock* async, _Out_ PFTitlePlayerHandle* entityHandle ) noexcept { return XAsyncGetResult(async, nullptr, sizeof(PFTitlePlayerHandle), entityHandle, nullptr); } HRESULT PFAuthenticationClientSetPlayerSecretAsync( _In_ PFTitlePlayerHandle contextHandle, _In_ const PFAuthenticationClientSetPlayerSecretRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ClientSetPlayerSecret, contextHandle->titlePlayer, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationServerAuthenticateSessionTicketAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationAuthenticateSessionTicketRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ServerAuthenticateSessionTicket, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationServerAuthenticateSessionTicketGetResultSize( _In_ XAsyncBlock* async, _Out_ size_t* bufferSize ) noexcept { return XAsyncGetResultSize(async, bufferSize); } HRESULT PFAuthenticationServerAuthenticateSessionTicketGetResult( _In_ XAsyncBlock* async, _In_ size_t bufferSize, _Out_writes_bytes_to_(bufferSize, *bufferUsed) void* buffer, _Outptr_ PFAuthenticationAuthenticateSessionTicketResult** result, _Out_opt_ size_t* bufferUsed ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(result); RETURN_IF_FAILED(XAsyncGetResult(async, nullptr, bufferSize, buffer, bufferUsed)); *result = static_cast<PFAuthenticationAuthenticateSessionTicketResult*>(buffer); return S_OK; } HRESULT PFAuthenticationServerLoginWithServerCustomIdAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithServerCustomIdRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ServerLoginWithServerCustomId, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationServerLoginGetResult( _In_ XAsyncBlock* async, _Out_ PFTitlePlayerHandle* titlePlayerHandle ) noexcept { return XAsyncGetResult(async, nullptr, sizeof(PFTitlePlayerHandle), titlePlayerHandle, nullptr); } HRESULT PFAuthenticationServerLoginWithSteamIdAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithSteamIdRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ServerLoginWithSteamId, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationServerLoginWithXboxAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationServerLoginWithXboxRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ServerLoginWithXbox, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationServerLoginWithXboxIdAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationLoginWithXboxIdRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ServerLoginWithXboxId, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationServerSetPlayerSecretAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationServerSetPlayerSecretRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ServerSetPlayerSecret, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationGetEntityTokenAsync( _In_ PFStateHandle contextHandle, _In_ const PFAuthenticationGetEntityTokenRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeAuthProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::GetEntityToken, contextHandle->state, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationGetEntityTokenGetResult( _In_ XAsyncBlock* async, _Out_ PFEntityHandle* entityHandle ) noexcept { return XAsyncGetResult(async, nullptr, sizeof(PFEntityHandle), entityHandle, nullptr); } HRESULT PFAuthenticationValidateEntityTokenAsync( _In_ PFEntityHandle contextHandle, _In_ const PFAuthenticationValidateEntityTokenRequest* request, _In_ XAsyncBlock* async ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(contextHandle); RETURN_HR_INVALIDARG_IF_NULL(request); auto provider = MakeProvider(async, __FUNCTION__, std::bind(&AuthenticationAPI::ValidateEntityToken, contextHandle->entity, *request, std::placeholders::_1)); return Provider::Run(UniquePtr<Provider>(provider.release())); } HRESULT PFAuthenticationValidateEntityTokenGetResultSize( _In_ XAsyncBlock* async, _Out_ size_t* bufferSize ) noexcept { return XAsyncGetResultSize(async, bufferSize); } HRESULT PFAuthenticationValidateEntityTokenGetResult( _In_ XAsyncBlock* async, _In_ size_t bufferSize, _Out_writes_bytes_to_(bufferSize, *bufferUsed) void* buffer, _Outptr_ PFAuthenticationValidateEntityTokenResponse** result, _Out_opt_ size_t* bufferUsed ) noexcept { RETURN_HR_INVALIDARG_IF_NULL(result); RETURN_IF_FAILED(XAsyncGetResult(async, nullptr, bufferSize, buffer, bufferUsed)); *result = static_cast<PFAuthenticationValidateEntityTokenResponse*>(buffer); return S_OK; }
#include <gmock/gmock.h> #include "UserContext.h" #include "User.h" #include "util.h" using ::testing::Return; using ::testing::Invoke; using ::testing::_; class MockUserContext : public ty::UserContext { public: MockUserContext(xn::Context *context) : ty::UserContext(context) {} MOCK_METHOD1(onNewUser, void(XnUserID)); MOCK_METHOD1(onPoseStart, void(XnUserID)); MOCK_METHOD1(onCalibrationStart, void(XnUserID)); MOCK_METHOD2(onCalibrationEnd, void(XnUserID, bool)); void fakeOnNewUser(XnUserID uid) { ty::UserContext::onNewUser(uid); } void fakeOnPoseStart(XnUserID uid) { ty::UserContext::onPoseStart(uid); } void fakeOnCalibrationStart(XnUserID uid) { ty::UserContext::onCalibrationStart(uid); } void fakeOnCalibrationEnd(XnUserID uid, bool isCalibration) { ty::UserContext::onCalibrationEnd(uid, isCalibration); } }; class UserContextTest : public testing::Test { public: virtual void SetUp() { context.Init(); } virtual void TearDown() { context.Release(); if (player.IsValid()) { player.Release(); } } protected: xn::Context context; xn::Player player; }; #define SET_ONIFILE(file) do { \ context.OpenFileRecording(file, player); \ player.SetRepeat(false); \ } while (0) #define EXEC_ONIFILE() do { \ context.StartGeneratingAll(); \ while (!player.IsEOF()) { \ context.WaitAndUpdateAll(); \ } \ } while (0) #define FINISH_ONIFILE() do { \ context.StopGeneratingAll(); \ } while (0) TEST_F(UserContextTest, NoNewUser) { SET_ONIFILE("./test/oni/depth_only.oni"); MockUserContext object(&context); int userId = 1; ty::User user(&object, userId); EXPECT_CALL(object, onNewUser(userId)).Times(0); EXEC_ONIFILE(); ASSERT_FALSE(user.isAvailable()); ASSERT_FALSE(user.isCalibrated()); ASSERT_FALSE(object.isTracking(userId)); FINISH_ONIFILE(); } TEST_F(UserContextTest, NewUserAndNoPoseUser) { SET_ONIFILE("./test/oni/user_new.oni"); MockUserContext object(&context); int userId = 1; ty::User user(&object, userId); ON_CALL(object, onNewUser(_)) .WillByDefault(Invoke(&object, &MockUserContext::fakeOnNewUser)); EXPECT_CALL(object, onNewUser(userId)).Times(1); EXPECT_CALL(object, onPoseStart(userId)).Times(0); EXEC_ONIFILE(); ASSERT_TRUE(user.isAvailable()); ASSERT_FALSE(user.isCalibrated()); ASSERT_FALSE(user.isTracking()); FINISH_ONIFILE(); } TEST_F(UserContextTest, NewUserAndCalibrateUser) { SET_ONIFILE("./test/oni/user_calibrate.oni"); MockUserContext object(&context); int userId = 1; ty::User user(&object, userId); ON_CALL(object, onNewUser(_)) .WillByDefault(Invoke(&object, &MockUserContext::fakeOnNewUser)); ON_CALL(object, onPoseStart(_)) .WillByDefault(Invoke(&object, &MockUserContext::fakeOnPoseStart)); ON_CALL(object, onCalibrationStart(_)) .WillByDefault(Invoke(&object, &MockUserContext::fakeOnCalibrationStart)); ON_CALL(object, onCalibrationEnd(_, _)) .WillByDefault(Invoke(&object, &MockUserContext::fakeOnCalibrationEnd)); EXPECT_CALL(object, onNewUser(userId)).Times(1); EXPECT_CALL(object, onPoseStart(userId)).Times(1); EXPECT_CALL(object, onCalibrationStart(userId)).Times(1); EXPECT_CALL(object, onCalibrationEnd(userId, true)).Times(1); EXEC_ONIFILE(); ASSERT_TRUE(user.isAvailable()); ASSERT_TRUE(user.isCalibrated()); ASSERT_TRUE(user.isTracking()); FINISH_ONIFILE(); } TEST_F(UserContextTest, NewUserAndCalibrateUserFailure) { SET_ONIFILE("./test/oni/user_calibrate_failure.oni"); MockUserContext object(&context); int userId = 1; ty::User user(&object, userId); ON_CALL(object, onNewUser(_)) .WillByDefault(Invoke(&object, &MockUserContext::fakeOnNewUser)); ON_CALL(object, onPoseStart(_)) .WillByDefault(Invoke(&object, &MockUserContext::fakeOnPoseStart)); ON_CALL(object, onCalibrationStart(_)) .WillByDefault(Invoke(&object, &MockUserContext::fakeOnCalibrationStart)); ON_CALL(object, onCalibrationEnd(_, _)) .WillByDefault(Invoke(&object, &MockUserContext::fakeOnCalibrationEnd)); EXPECT_CALL(object, onNewUser(userId)).Times(1); EXPECT_CALL(object, onPoseStart(userId)).Times(1); EXPECT_CALL(object, onCalibrationStart(userId)).Times(1); EXPECT_CALL(object, onCalibrationEnd(userId, false)).Times(1); EXEC_ONIFILE(); ASSERT_TRUE(user.isAvailable()); ASSERT_FALSE(user.isTracking()); ASSERT_FALSE(user.isCalibrated()); FINISH_ONIFILE(); }
// // BakerCLI.cpp // tools/oven/src // // Created by Robbie Uvanni on 6/6/17. // Copyright 2017 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "BakerCLI.h" #include <QObject> #include <QImageReader> #include <QtCore/QDebug> #include <QFile> #include <unordered_map> #include "OvenCLIApplication.h" #include "ModelBakingLoggingCategory.h" #include "FBXBaker.h" #include "JSBaker.h" #include "TextureBaker.h" BakerCLI::BakerCLI(OvenCLIApplication* parent) : QObject(parent) { } void BakerCLI::bakeFile(QUrl inputUrl, const QString& outputPath, const QString& type) { // if the URL doesn't have a scheme, assume it is a local file if (inputUrl.scheme() != "http" && inputUrl.scheme() != "https" && inputUrl.scheme() != "ftp" && inputUrl.scheme() != "file") { inputUrl = QUrl::fromLocalFile(inputUrl.toString()); } qDebug() << "Baking file type: " << type; static const QString MODEL_EXTENSION { "fbx" }; static const QString SCRIPT_EXTENSION { "js" }; // check what kind of baker we should be creating bool isFBX = type == MODEL_EXTENSION; bool isScript = type == SCRIPT_EXTENSION; // If the type doesn't match the above, we assume we have a texture, and the type specified is the // texture usage type (albedo, cubemap, normals, etc.) auto url = inputUrl.toDisplayString(); auto idx = url.lastIndexOf('.'); auto extension = idx >= 0 ? url.mid(idx + 1).toLower() : ""; bool isSupportedImage = QImageReader::supportedImageFormats().contains(extension.toLatin1()); _outputPath = outputPath; // create our appropiate baker if (isFBX) { _baker = std::unique_ptr<Baker> { new FBXBaker(inputUrl, []() -> QThread* { return Oven::instance().getNextWorkerThread(); }, outputPath) }; _baker->moveToThread(Oven::instance().getNextWorkerThread()); } else if (isScript) { _baker = std::unique_ptr<Baker> { new JSBaker(inputUrl, outputPath) }; _baker->moveToThread(Oven::instance().getNextWorkerThread()); } else if (isSupportedImage) { static const std::unordered_map<QString, image::TextureUsage::Type> STRING_TO_TEXTURE_USAGE_TYPE_MAP { { "default", image::TextureUsage::DEFAULT_TEXTURE }, { "strict", image::TextureUsage::STRICT_TEXTURE }, { "albedo", image::TextureUsage::ALBEDO_TEXTURE }, { "normal", image::TextureUsage::NORMAL_TEXTURE }, { "bump", image::TextureUsage::BUMP_TEXTURE }, { "specular", image::TextureUsage::SPECULAR_TEXTURE }, { "metallic", image::TextureUsage::METALLIC_TEXTURE }, { "roughness", image::TextureUsage::ROUGHNESS_TEXTURE }, { "gloss", image::TextureUsage::GLOSS_TEXTURE }, { "emissive", image::TextureUsage::EMISSIVE_TEXTURE }, { "cube", image::TextureUsage::CUBE_TEXTURE }, { "occlusion", image::TextureUsage::OCCLUSION_TEXTURE }, { "scattering", image::TextureUsage::SCATTERING_TEXTURE }, { "lightmap", image::TextureUsage::LIGHTMAP_TEXTURE }, }; auto it = STRING_TO_TEXTURE_USAGE_TYPE_MAP.find(type); if (it == STRING_TO_TEXTURE_USAGE_TYPE_MAP.end()) { qCDebug(model_baking) << "Unknown texture usage type:" << type; QCoreApplication::exit(OVEN_STATUS_CODE_FAIL); } _baker = std::unique_ptr<Baker> { new TextureBaker(inputUrl, it->second, outputPath) }; _baker->moveToThread(Oven::instance().getNextWorkerThread()); } else { qCDebug(model_baking) << "Failed to determine baker type for file" << inputUrl; QCoreApplication::exit(OVEN_STATUS_CODE_FAIL); return; } // invoke the bake method on the baker thread QMetaObject::invokeMethod(_baker.get(), "bake"); // make sure we hear about the results of this baker when it is done connect(_baker.get(), &Baker::finished, this, &BakerCLI::handleFinishedBaker); } void BakerCLI::handleFinishedBaker() { qCDebug(model_baking) << "Finished baking file."; int exitCode = OVEN_STATUS_CODE_SUCCESS; // Do we need this? if (_baker->wasAborted()) { exitCode = OVEN_STATUS_CODE_ABORT; } else if (_baker->hasErrors()) { exitCode = OVEN_STATUS_CODE_FAIL; QFile errorFile { _outputPath.absoluteFilePath(OVEN_ERROR_FILENAME) }; if (errorFile.open(QFile::WriteOnly)) { errorFile.write(_baker->getErrors().join('\n').toUtf8()); errorFile.close(); } } QCoreApplication::exit(exitCode); }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/compositor/reflector_impl.h" #include "base/bind.h" #include "base/location.h" #include "content/browser/compositor/browser_compositor_output_surface.h" #include "content/browser/compositor/owned_mailbox.h" #include "ui/compositor/layer.h" namespace content { struct ReflectorImpl::LayerData { LayerData(ui::Layer* layer) : layer(layer) {} ui::Layer* layer; bool needs_set_mailbox = false; }; ReflectorImpl::ReflectorImpl(ui::Compositor* mirrored_compositor, ui::Layer* mirroring_layer) : mirrored_compositor_(mirrored_compositor), flip_texture_(false), output_surface_(nullptr) { if (mirroring_layer) AddMirroringLayer(mirroring_layer); } ReflectorImpl::~ReflectorImpl() { } void ReflectorImpl::Shutdown() { if (output_surface_) DetachFromOutputSurface(); // Prevent the ReflectorImpl from picking up a new output surface. mirroring_layers_.clear(); } void ReflectorImpl::DetachFromOutputSurface() { DCHECK(output_surface_); output_surface_->SetReflector(nullptr); DCHECK(mailbox_.get()); mailbox_ = nullptr; output_surface_ = nullptr; for (LayerData* layer_data : mirroring_layers_) layer_data->layer->SetShowSolidColorContent(); } void ReflectorImpl::OnSourceSurfaceReady( BrowserCompositorOutputSurface* output_surface) { if (mirroring_layers_.empty()) return; // Was already Shutdown(). if (output_surface == output_surface_) return; // Is already attached. if (output_surface_) DetachFromOutputSurface(); output_surface_ = output_surface; flip_texture_ = !output_surface->capabilities().flipped_output_surface; output_surface_->SetReflector(this); } void ReflectorImpl::OnMirroringCompositorResized() { for (LayerData* layer_data : mirroring_layers_) layer_data->layer->SchedulePaint(layer_data->layer->bounds()); } void ReflectorImpl::AddMirroringLayer(ui::Layer* layer) { DCHECK(layer->GetCompositor()); DCHECK(mirroring_layers_.end() == FindLayerData(layer)); LayerData* layer_data = new LayerData(layer); if (mailbox_) layer_data->needs_set_mailbox = true; mirroring_layers_.push_back(layer_data); mirrored_compositor_->ScheduleFullRedraw(); } void ReflectorImpl::RemoveMirroringLayer(ui::Layer* layer) { DCHECK(layer->GetCompositor()); ScopedVector<LayerData>::iterator iter = FindLayerData(layer); DCHECK(iter != mirroring_layers_.end()); (*iter)->layer->SetShowSolidColorContent(); mirroring_layers_.erase(iter); if (mirroring_layers_.empty() && output_surface_) DetachFromOutputSurface(); } void ReflectorImpl::OnSourceTextureMailboxUpdated( scoped_refptr<OwnedMailbox> mailbox) { mailbox_ = mailbox; if (mailbox_.get()) { for (LayerData* layer_data : mirroring_layers_) layer_data->needs_set_mailbox = true; // The texture doesn't have the data. Request full redraw on mirrored // compositor so that the full content will be copied to mirroring // compositor. This full redraw should land us in OnSourceSwapBuffers() to // resize the texture appropriately. mirrored_compositor_->ScheduleFullRedraw(); } } void ReflectorImpl::OnSourceSwapBuffers(const gfx::Size& surface_size) { if (mirroring_layers_.empty()) return; // Should be attached to the source output surface already. DCHECK(mailbox_.get()); // Request full redraw on mirroring compositor. for (LayerData* layer_data : mirroring_layers_) UpdateTexture(layer_data, surface_size, layer_data->layer->bounds()); } void ReflectorImpl::OnSourcePostSubBuffer(const gfx::Rect& swap_rect, const gfx::Size& surface_size) { if (mirroring_layers_.empty()) return; // Should be attached to the source output surface already. DCHECK(mailbox_.get()); gfx::Rect mirroring_rect = swap_rect; if (flip_texture_) { // Flip the coordinates to compositor's one. mirroring_rect.set_y(surface_size.height() - swap_rect.y() - swap_rect.height()); } // Request redraw of the dirty portion in mirroring compositor. for (LayerData* layer_data : mirroring_layers_) UpdateTexture(layer_data, surface_size, mirroring_rect); } static void ReleaseMailbox(scoped_refptr<OwnedMailbox> mailbox, const gpu::SyncToken& sync_token, bool is_lost) { mailbox->UpdateSyncToken(sync_token); } ScopedVector<ReflectorImpl::LayerData>::iterator ReflectorImpl::FindLayerData( ui::Layer* layer) { return std::find_if(mirroring_layers_.begin(), mirroring_layers_.end(), [layer](const LayerData* layer_data) { return layer_data->layer == layer; }); } void ReflectorImpl::UpdateTexture(ReflectorImpl::LayerData* layer_data, const gfx::Size& source_size, const gfx::Rect& redraw_rect) { if (layer_data->needs_set_mailbox) { layer_data->layer->SetTextureMailbox( cc::TextureMailbox(mailbox_->holder()), cc::SingleReleaseCallback::Create(base::Bind(ReleaseMailbox, mailbox_)), source_size); layer_data->needs_set_mailbox = false; } else { layer_data->layer->SetTextureSize(source_size); } layer_data->layer->SetBounds(gfx::Rect(source_size)); layer_data->layer->SetTextureFlipped(flip_texture_); layer_data->layer->SchedulePaint(redraw_rect); } } // namespace content
/**************************************************************************** ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of a Qt Solutions component. ** ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions Commercial License Agreement provided ** with the Software or, alternatively, in accordance with the terms ** contained in a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact Nokia at qt-info@nokia.com. ** ****************************************************************************/ #include "qtgroupboxpropertybrowser.h" #include <QtCore/QSet> #include <QtGui/QGridLayout> #include <QtGui/QLabel> #include <QtGui/QGroupBox> #include <QtCore/QTimer> #include <QtCore/QMap> #if QT_VERSION >= 0x040400 QT_BEGIN_NAMESPACE #endif class QtGroupBoxPropertyBrowserPrivate { QtGroupBoxPropertyBrowser *q_ptr; Q_DECLARE_PUBLIC(QtGroupBoxPropertyBrowser) public: void init(QWidget *parent); void propertyInserted(QtBrowserItem *index, QtBrowserItem *afterIndex); void propertyRemoved(QtBrowserItem *index); void propertyChanged(QtBrowserItem *index); QWidget *createEditor(QtProperty *property, QWidget *parent) const { return q_ptr->createEditor(property, parent); } void slotEditorDestroyed(); void slotUpdate(); struct WidgetItem { WidgetItem() : widget(0), label(0), widgetLabel(0), groupBox(0), layout(0), line(0), parent(0) { } QWidget *widget; // can be null QLabel *label; QLabel *widgetLabel; QGroupBox *groupBox; QGridLayout *layout; QFrame *line; WidgetItem *parent; QList<WidgetItem *> children; }; private: void updateLater(); void updateItem(WidgetItem *item); void insertRow(QGridLayout *layout, int row) const; void removeRow(QGridLayout *layout, int row) const; bool hasHeader(WidgetItem *item) const; QMap<QtBrowserItem *, WidgetItem *> m_indexToItem; QMap<WidgetItem *, QtBrowserItem *> m_itemToIndex; QMap<QWidget *, WidgetItem *> m_widgetToItem; QGridLayout *m_mainLayout; QList<WidgetItem *> m_children; QList<WidgetItem *> m_recreateQueue; }; void QtGroupBoxPropertyBrowserPrivate::init(QWidget *parent) { m_mainLayout = new QGridLayout(); parent->setLayout(m_mainLayout); QLayoutItem *item = new QSpacerItem(0, 0, QSizePolicy::Fixed, QSizePolicy::Expanding); m_mainLayout->addItem(item, 0, 0); } void QtGroupBoxPropertyBrowserPrivate::slotEditorDestroyed() { QWidget *editor = qobject_cast<QWidget *>(q_ptr->sender()); if (!editor) return; if (!m_widgetToItem.contains(editor)) return; m_widgetToItem[editor]->widget = 0; m_widgetToItem.remove(editor); } void QtGroupBoxPropertyBrowserPrivate::slotUpdate() { QListIterator<WidgetItem *> itItem(m_recreateQueue); while (itItem.hasNext()) { WidgetItem *item = itItem.next(); WidgetItem *par = item->parent; QWidget *w = 0; QGridLayout *l = 0; int oldRow = -1; if (!par) { w = q_ptr; l = m_mainLayout; oldRow = m_children.indexOf(item); } else { w = par->groupBox; l = par->layout; oldRow = par->children.indexOf(item); if (hasHeader(par)) oldRow += 2; } if (item->widget) { item->widget->setParent(w); } else if (item->widgetLabel) { item->widgetLabel->setParent(w); } else { item->widgetLabel = new QLabel(w); } int span = 1; if (item->widget) l->addWidget(item->widget, oldRow, 1, 1, 1); else if (item->widgetLabel) l->addWidget(item->widgetLabel, oldRow, 1, 1, 1); else span = 2; item->label = new QLabel(w); item->label->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); l->addWidget(item->label, oldRow, 0, 1, span); updateItem(item); } m_recreateQueue.clear(); } void QtGroupBoxPropertyBrowserPrivate::updateLater() { QTimer::singleShot(0, q_ptr, SLOT(slotUpdate())); } void QtGroupBoxPropertyBrowserPrivate::propertyInserted(QtBrowserItem *index, QtBrowserItem *afterIndex) { WidgetItem *afterItem = m_indexToItem.value(afterIndex); WidgetItem *parentItem = m_indexToItem.value(index->parent()); WidgetItem *newItem = new WidgetItem(); newItem->parent = parentItem; QGridLayout *layout = 0; QWidget *parentWidget = 0; int row = -1; if (!afterItem) { row = 0; if (parentItem) parentItem->children.insert(0, newItem); else m_children.insert(0, newItem); } else { if (parentItem) { row = parentItem->children.indexOf(afterItem) + 1; parentItem->children.insert(row, newItem); } else { row = m_children.indexOf(afterItem) + 1; m_children.insert(row, newItem); } } if (parentItem && hasHeader(parentItem)) row += 2; if (!parentItem) { layout = m_mainLayout; parentWidget = q_ptr;; } else { if (!parentItem->groupBox) { m_recreateQueue.removeAll(parentItem); WidgetItem *par = parentItem->parent; QWidget *w = 0; QGridLayout *l = 0; int oldRow = -1; if (!par) { w = q_ptr; l = m_mainLayout; oldRow = m_children.indexOf(parentItem); } else { w = par->groupBox; l = par->layout; oldRow = par->children.indexOf(parentItem); if (hasHeader(par)) oldRow += 2; } parentItem->groupBox = new QGroupBox(w); parentItem->layout = new QGridLayout(); parentItem->groupBox->setLayout(parentItem->layout); if (parentItem->label) { l->removeWidget(parentItem->label); delete parentItem->label; parentItem->label = 0; } if (parentItem->widget) { l->removeWidget(parentItem->widget); parentItem->widget->setParent(parentItem->groupBox); parentItem->layout->addWidget(parentItem->widget, 0, 0, 1, 2); parentItem->line = new QFrame(parentItem->groupBox); } else if (parentItem->widgetLabel) { l->removeWidget(parentItem->widgetLabel); delete parentItem->widgetLabel; parentItem->widgetLabel = 0; } if (parentItem->line) { parentItem->line->setFrameShape(QFrame::HLine); parentItem->line->setFrameShadow(QFrame::Sunken); parentItem->layout->addWidget(parentItem->line, 1, 0, 1, 2); } l->addWidget(parentItem->groupBox, oldRow, 0, 1, 2); updateItem(parentItem); } layout = parentItem->layout; parentWidget = parentItem->groupBox; } newItem->label = new QLabel(parentWidget); newItem->label->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); newItem->widget = createEditor(index->property(), parentWidget); if (!newItem->widget) { newItem->widgetLabel = new QLabel(parentWidget); } else { QObject::connect(newItem->widget, SIGNAL(destroyed()), q_ptr, SLOT(slotEditorDestroyed())); m_widgetToItem[newItem->widget] = newItem; } insertRow(layout, row); int span = 1; if (newItem->widget) layout->addWidget(newItem->widget, row, 1); else if (newItem->widgetLabel) layout->addWidget(newItem->widgetLabel, row, 1); else span = 2; layout->addWidget(newItem->label, row, 0, 1, span); m_itemToIndex[newItem] = index; m_indexToItem[index] = newItem; updateItem(newItem); } void QtGroupBoxPropertyBrowserPrivate::propertyRemoved(QtBrowserItem *index) { WidgetItem *item = m_indexToItem.value(index); m_indexToItem.remove(index); m_itemToIndex.remove(item); WidgetItem *parentItem = item->parent; int row = -1; if (parentItem) { row = parentItem->children.indexOf(item); parentItem->children.removeAt(row); if (hasHeader(parentItem)) row += 2; } else { row = m_children.indexOf(item); m_children.removeAt(row); } if (item->widget) delete item->widget; if (item->label) delete item->label; if (item->widgetLabel) delete item->widgetLabel; if (item->groupBox) delete item->groupBox; if (!parentItem) { removeRow(m_mainLayout, row); } else if (parentItem->children.count() != 0) { removeRow(parentItem->layout, row); } else { WidgetItem *par = parentItem->parent; QWidget *w = 0; QGridLayout *l = 0; int oldRow = -1; if (!par) { w = q_ptr; l = m_mainLayout; oldRow = m_children.indexOf(parentItem); } else { w = par->groupBox; l = par->layout; oldRow = par->children.indexOf(parentItem); if (hasHeader(par)) oldRow += 2; } if (parentItem->widget) { parentItem->widget->hide(); parentItem->widget->setParent(0); } else if (parentItem->widgetLabel) { parentItem->widgetLabel->hide(); parentItem->widgetLabel->setParent(0); } else { //parentItem->widgetLabel = new QLabel(w); } l->removeWidget(parentItem->groupBox); delete parentItem->groupBox; parentItem->groupBox = 0; parentItem->line = 0; parentItem->layout = 0; if (!m_recreateQueue.contains(parentItem)) m_recreateQueue.append(parentItem); updateLater(); } m_recreateQueue.removeAll(item); delete item; } void QtGroupBoxPropertyBrowserPrivate::insertRow(QGridLayout *layout, int row) const { QMap<QLayoutItem *, QRect> itemToPos; int idx = 0; while (idx < layout->count()) { int r, c, rs, cs; layout->getItemPosition(idx, &r, &c, &rs, &cs); if (r >= row) { itemToPos[layout->takeAt(idx)] = QRect(r + 1, c, rs, cs); } else { idx++; } } const QMap<QLayoutItem *, QRect>::ConstIterator icend = itemToPos.constEnd(); for (QMap<QLayoutItem *, QRect>::ConstIterator it = itemToPos.constBegin(); it != icend; ++it) { const QRect r = it.value(); layout->addItem(it.key(), r.x(), r.y(), r.width(), r.height()); } } void QtGroupBoxPropertyBrowserPrivate::removeRow(QGridLayout *layout, int row) const { QMap<QLayoutItem *, QRect> itemToPos; int idx = 0; while (idx < layout->count()) { int r, c, rs, cs; layout->getItemPosition(idx, &r, &c, &rs, &cs); if (r > row) { itemToPos[layout->takeAt(idx)] = QRect(r - 1, c, rs, cs); } else { idx++; } } const QMap<QLayoutItem *, QRect>::ConstIterator icend = itemToPos.constEnd(); for (QMap<QLayoutItem *, QRect>::ConstIterator it = itemToPos.constBegin(); it != icend; ++it) { const QRect r = it.value(); layout->addItem(it.key(), r.x(), r.y(), r.width(), r.height()); } } bool QtGroupBoxPropertyBrowserPrivate::hasHeader(WidgetItem *item) const { if (item->widget) return true; return false; } void QtGroupBoxPropertyBrowserPrivate::propertyChanged(QtBrowserItem *index) { WidgetItem *item = m_indexToItem.value(index); updateItem(item); } void QtGroupBoxPropertyBrowserPrivate::updateItem(WidgetItem *item) { QtProperty *property = m_itemToIndex[item]->property(); if (item->groupBox) { QFont font = item->groupBox->font(); font.setUnderline(property->isModified()); item->groupBox->setFont(font); item->groupBox->setTitle(property->propertyName()); item->groupBox->setToolTip(property->toolTip()); item->groupBox->setStatusTip(property->statusTip()); item->groupBox->setWhatsThis(property->whatsThis()); item->groupBox->setEnabled(property->isEnabled()); } if (item->label) { QFont font = item->label->font(); font.setUnderline(property->isModified()); item->label->setFont(font); item->label->setText(property->propertyName()); item->label->setToolTip(property->toolTip()); item->label->setStatusTip(property->statusTip()); item->label->setWhatsThis(property->whatsThis()); item->label->setEnabled(property->isEnabled()); } if (item->widgetLabel) { QFont font = item->widgetLabel->font(); font.setUnderline(false); item->widgetLabel->setFont(font); item->widgetLabel->setText(property->valueText()); item->widgetLabel->setEnabled(property->isEnabled()); } if (item->widget) { QFont font = item->widget->font(); font.setUnderline(false); item->widget->setFont(font); item->widget->setEnabled(property->isEnabled()); item->widget->setToolTip(property->valueText()); } //item->setIcon(1, property->valueIcon()); } /*! \class QtGroupBoxPropertyBrowser \brief The QtGroupBoxPropertyBrowser class provides a QGroupBox based property browser. A property browser is a widget that enables the user to edit a given set of properties. Each property is represented by a label specifying the property's name, and an editing widget (e.g. a line edit or a combobox) holding its value. A property can have zero or more subproperties. QtGroupBoxPropertyBrowser provides group boxes for all nested properties, i.e. subproperties are enclosed by a group box with the parent property's name as its title. For example: \image qtgroupboxpropertybrowser.png Use the QtAbstractPropertyBrowser API to add, insert and remove properties from an instance of the QtGroupBoxPropertyBrowser class. The properties themselves are created and managed by implementations of the QtAbstractPropertyManager class. \sa QtTreePropertyBrowser, QtAbstractPropertyBrowser */ /*! Creates a property browser with the given \a parent. */ QtGroupBoxPropertyBrowser::QtGroupBoxPropertyBrowser(QWidget *parent) : QtAbstractPropertyBrowser(parent) { d_ptr = new QtGroupBoxPropertyBrowserPrivate; d_ptr->q_ptr = this; d_ptr->init(this); } /*! Destroys this property browser. Note that the properties that were inserted into this browser are \e not destroyed since they may still be used in other browsers. The properties are owned by the manager that created them. \sa QtProperty, QtAbstractPropertyManager */ QtGroupBoxPropertyBrowser::~QtGroupBoxPropertyBrowser() { const QMap<QtGroupBoxPropertyBrowserPrivate::WidgetItem *, QtBrowserItem *>::ConstIterator icend = d_ptr->m_itemToIndex.constEnd(); for (QMap<QtGroupBoxPropertyBrowserPrivate::WidgetItem *, QtBrowserItem *>::ConstIterator it = d_ptr->m_itemToIndex.constBegin(); it != icend; ++it) delete it.key(); delete d_ptr; } /*! \reimp */ void QtGroupBoxPropertyBrowser::itemInserted(QtBrowserItem *item, QtBrowserItem *afterItem) { d_ptr->propertyInserted(item, afterItem); } /*! \reimp */ void QtGroupBoxPropertyBrowser::itemRemoved(QtBrowserItem *item) { d_ptr->propertyRemoved(item); } /*! \reimp */ void QtGroupBoxPropertyBrowser::itemChanged(QtBrowserItem *item) { d_ptr->propertyChanged(item); } #if QT_VERSION >= 0x040400 QT_END_NAMESPACE #endif #include "moc_qtgroupboxpropertybrowser.cpp"
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: GameplayRpcManager #include "GlobalNamespace/GameplayRpcManager.hpp" // Including type: RemoteProcedureCall #include "GlobalNamespace/RemoteProcedureCall.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Type namespace: namespace GlobalNamespace { // Forward declaring type: ReturnToMenuRpc class ReturnToMenuRpc; } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(GlobalNamespace::GameplayRpcManager::ReturnToMenuRpc); DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::GameplayRpcManager::ReturnToMenuRpc*, "", "GameplayRpcManager/ReturnToMenuRpc"); // Type namespace: namespace GlobalNamespace { // Size: 0x14 #pragma pack(push, 1) // Autogenerated type: GameplayRpcManager/ReturnToMenuRpc // [TokenAttribute] Offset: FFFFFFFF class GameplayRpcManager::ReturnToMenuRpc : public GlobalNamespace::RemoteProcedureCall { public: // public System.Void .ctor() // Offset: 0x143E81C // Implemented from: RemoteProcedureCall // Base method: System.Void RemoteProcedureCall::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static GameplayRpcManager::ReturnToMenuRpc* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::GameplayRpcManager::ReturnToMenuRpc::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<GameplayRpcManager::ReturnToMenuRpc*, creationType>())); } }; // GameplayRpcManager/ReturnToMenuRpc #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::GameplayRpcManager::ReturnToMenuRpc::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
/* //@HEADER // ************************************************************************ // // ode_advance_printing_helpers.hpp // Pressio // Copyright 2019 // National Technology & Engineering Solutions of Sandia, LLC (NTESS) // // Under the terms of Contract DE-NA0003525 with NTESS, the // U.S. Government retains certain rights in this software. // // Pressio is licensed under BSD-3-Clause terms of use: // // 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. // // Questions? Contact Francesco Rizzi (fnrizzi@sandia.gov) // // ************************************************************************ //@HEADER */ #ifndef ODE_ADVANCERS_IMPL_ODE_ADVANCE_PRINTING_HELPERS_HPP_ #define ODE_ADVANCERS_IMPL_ODE_ADVANCE_PRINTING_HELPERS_HPP_ namespace pressio{ namespace ode{ namespace impl{ template<typename ...Args> void print_start_of_advancing(Args && ... args) { #ifdef PRESSIO_ENABLE_DEBUG_PRINT using namespace ::pressio::utils::io; print_stdout("\n"); print_stdout(blue(), "-------------------------------------------------\n", reset()); print_stdout(bg_grey() + blue(), "ode:", std::forward<Args>(args)..., reset(), "\n"); print_stdout(blue(), "-------------------------------------------------", reset()); print_stdout("\n"); #endif } template <typename TimeType, class StepCountType> void print_step_time(const StepCountType & step, const TimeType & time, const TimeType & dt) { PRESSIOLOG_DEBUG("starting timestep={} from time={} with dt={}", step, time, dt); // #ifdef PRESSIO_ENABLE_DEBUG_PRINT // using namespace ::pressio::utils::io; // auto fmt = blue(); // print_stdout(fmt, // std::left, // "time step=", step, // ": starts at time=", time, // " dt=", dt, // reset(), "\n"); // #endif } }}}//end namespace pressio::ode::impl #endif // ODE_ADVANCERS_IMPL_ODE_ADVANCE_PRINTING_HELPERS_HPP_
// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "update_engine/omaha_request_action.h" #include <inttypes.h> #include <memory> #include <sstream> #include <string> #include <glog/logging.h> #include <libxml/xpath.h> #include <libxml/xpathInternals.h> #include "strings/string_number_conversions.h" #include "strings/string_printf.h" #include "update_engine/action_pipe.h" #include "update_engine/omaha_request_params.h" #include "update_engine/payload_state_interface.h" #include "update_engine/prefs_interface.h" #include "update_engine/utils.h" using std::string; using strings::StringPrintf; namespace chromeos_update_engine { // List of custom pair tags that we interpret in the Omaha Response: static const char* kTagDeadline = "deadline"; static const char* kTagDisablePayloadBackoff = "DisablePayloadBackoff"; // Deprecated: "DisplayVersion" // Deprecated: "IsDelta" static const char* kTagIsDeltaPayload = "IsDeltaPayload"; static const char* kTagMaxFailureCountPerUrl = "MaxFailureCountPerUrl"; // Deprecated: "MaxDaysToScatter"; // Deprecated: "ManifestSignatureRsa" // Deprecated: "ManifestSize" // Deprecated: "MetadataSignatureRsa" // Deprecated: "MetadataSize" static const char* kTagMoreInfo = "MoreInfo"; static const char* kTagNeedsAdmin = "needsadmin"; static const char* kTagPrompt = "Prompt"; static const char* kTagSha256 = "sha256"; namespace { const string kGupdateVersion(PACKAGE_NAME "-" PACKAGE_VERSION); // This is handy for passing strings into libxml2 #define ConstXMLStr(x) (reinterpret_cast<const xmlChar*>(x)) // These are for std::unique_ptr class ScopedPtrXmlDocFree { public: inline void operator()(void* x) const { xmlFreeDoc(reinterpret_cast<xmlDoc*>(x)); } }; class ScopedPtrXmlFree { public: inline void operator()(void* x) const { xmlFree(x); } }; class ScopedPtrXmlXPathObjectFree { public: inline void operator()(void* x) const { xmlXPathFreeObject(reinterpret_cast<xmlXPathObject*>(x)); } }; class ScopedPtrXmlXPathContextFree { public: inline void operator()(void* x) const { xmlXPathFreeContext(reinterpret_cast<xmlXPathContext*>(x)); } }; // Returns an XML ping element if any of the elapsed days need to be // sent, or an empty string otherwise. string GetPingXml(int ping_active_days, int ping_roll_call_days) { return StringPrintf(" <ping active=\"1\"></ping>\n"); } // Returns an XML that goes into the body of the <app> element of the Omaha // request based on the given parameters. string GetAppBody(const OmahaEvent* event, const OmahaRequestParams& params, bool ping_only, int ping_active_days, int ping_roll_call_days, PrefsInterface* prefs) { string app_body; if (event == NULL) { app_body = GetPingXml(ping_active_days, ping_roll_call_days); if (!ping_only) { string current_version; string prev_version; current_version = params.app_version(); if (!prefs->GetString(kPrefsPreviousVersion, &prev_version)) { prev_version = "initial"; } app_body += " <updatecheck></updatecheck>\n"; // Check if currently the same version is running as before the update, which indicates that // a rollback took place. // We do not need to check for UPDATE_STATUS_UPDATED_NEED_REBOOT because a new update won't // be attempted until the system rebooted. if (!prev_version.empty() && prev_version.compare(current_version) == 0) { LOG(ERROR) << "Rollback detected, still running " << prev_version << " after update."; app_body += StringPrintf( " <event eventtype=\"%d\" eventresult=\"%d\" errorcode=\"%d\"></event>\n", OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultError, kActionCodeRollbackError); } else { // If this is the first update check after a reboot following a previous // update, generate an event containing the previous version number. If // the previous version preference file doesn't exist the event is still // generated with a previous version of 0.0.0.0 -- this is relevant for // older clients or new installs. The previous version event is not sent // for ping-only requests because they come before the client has // rebooted. if (prev_version.compare("initial") == 0) { prev_version = "0.0.0.0"; } app_body += StringPrintf( " <event eventtype=\"%d\" eventresult=\"%d\" " "previousversion=\"%s\"></event>\n", OmahaEvent::kTypeUpdateComplete, OmahaEvent::kResultSuccessReboot, XmlEncode(prev_version).c_str()); } LOG_IF(WARNING, !prefs->SetString(kPrefsPreviousVersion, "")) << "Unable to reset the previous version."; } } else { // The error code is an optional attribute so append it only if the result // is not success. string error_code; if (event->result != OmahaEvent::kResultSuccess) { error_code = StringPrintf(" errorcode=\"%d\"", event->error_code); } app_body = StringPrintf( " <event eventtype=\"%d\" eventresult=\"%d\"%s></event>\n", event->type, event->result, error_code.c_str()); } return app_body; } // Returns an XML that corresponds to the entire <app> node of the Omaha // request based on the given parameters. string GetAppXml(const OmahaEvent* event, const OmahaRequestParams& params, bool ping_only, int ping_active_days, int ping_roll_call_days, SystemState* system_state) { string app_body = GetAppBody(event, params, ping_only, ping_active_days, ping_roll_call_days, system_state->prefs()); string delta_okay_str = params.delta_okay() ? "true" : "false"; string app_xml = " <app appid=\"" + XmlEncode(params.app_id()) + "\" " + "version=\"" + XmlEncode(params.app_version()) + "\" " + "track=\"" + XmlEncode(params.app_channel()) + "\" " + "bootid=\"" + XmlEncode(params.bootid()) + "\" " + "oem=\"" + XmlEncode(params.oemid()) + "\" " + "oemversion=\"" + XmlEncode(params.oemversion()) + "\" " + "alephversion=\"" + XmlEncode(params.alephversion()) + "\" " + "machineid=\"" + XmlEncode(params.machineid()) + "\" " + "machinealias=\"" + XmlEncode(params.machinealias()) + "\" " + "lang=\"" + XmlEncode(params.app_lang()) + "\" " + "board=\"" + XmlEncode(params.os_board()) + "\" " + "hardware_class=\"" + XmlEncode(params.hwid()) + "\" " + "delta_okay=\"" + delta_okay_str + "\" " ">\n" + app_body + " </app>\n"; return app_xml; } // Returns an XML that corresponds to the entire <os> node of the Omaha // request based on the given parameters. string GetOsXml(const OmahaRequestParams& params) { string os_xml = " <os version=\"" + XmlEncode(params.os_version()) + "\" " + "platform=\"" + XmlEncode(params.os_platform()) + "\" " + "sp=\"" + XmlEncode(params.os_sp()) + "\">" "</os>\n"; return os_xml; } // Returns an XML that corresponds to the entire Omaha request based on the // given parameters. string GetRequestXml(const OmahaEvent* event, const OmahaRequestParams& params, bool ping_only, int ping_active_days, int ping_roll_call_days, SystemState* system_state) { string os_xml = GetOsXml(params); string app_xml = GetAppXml(event, params, ping_only, ping_active_days, ping_roll_call_days, system_state); string install_source = StringPrintf("installsource=\"%s\" ", (params.interactive() ? "ondemandupdate" : "scheduler")); string request_xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<request protocol=\"3.0\" " "version=\"" + XmlEncode(kGupdateVersion) + "\" " "updaterversion=\"" + XmlEncode(kGupdateVersion) + "\" " + install_source + "ismachine=\"1\">\n" + os_xml + app_xml + "</request>\n"; return request_xml; } } // namespace {} // Encodes XML entities in a given string with libxml2. input must be // UTF-8 formatted. Output will be UTF-8 formatted. string XmlEncode(const string& input) { std::unique_ptr<xmlChar, ScopedPtrXmlFree> str( xmlEncodeEntitiesReentrant(NULL, ConstXMLStr(input.c_str()))); return string(reinterpret_cast<const char *>(str.get())); } OmahaRequestAction::OmahaRequestAction(SystemState* system_state, OmahaEvent* event, HttpFetcher* http_fetcher, bool ping_only) : system_state_(system_state), event_(event), http_fetcher_(http_fetcher), ping_only_(ping_only), ping_active_days_(0), ping_roll_call_days_(0) { params_ = system_state->request_params(); } OmahaRequestAction::~OmahaRequestAction() {} void OmahaRequestAction::PerformAction() { http_fetcher_->set_delegate(this); string request_post(GetRequestXml(event_.get(), *params_, ping_only_, ping_active_days_, ping_roll_call_days_, system_state_)); http_fetcher_->SetPostData(request_post.data(), request_post.size(), kHttpContentTypeTextXml); LOG(INFO) << "Posting an Omaha request to " << params_->update_url(); LOG(INFO) << "Request: " << request_post; http_fetcher_->BeginTransfer(params_->update_url()); } void OmahaRequestAction::TerminateProcessing() { http_fetcher_->TerminateTransfer(); } // We just store the response in the buffer. Once we've received all bytes, // we'll look in the buffer and decide what to do. void OmahaRequestAction::ReceivedBytes(HttpFetcher *fetcher, const char* bytes, int length) { response_buffer_.reserve(response_buffer_.size() + length); response_buffer_.insert(response_buffer_.end(), bytes, bytes + length); } namespace { // If non-NULL response, caller is responsible for calling xmlXPathFreeObject() // on the returned object. // This code is roughly based on the libxml tutorial at: // http://xmlsoft.org/tutorial/apd.html xmlXPathObject* GetNodeSet(xmlDoc* doc, const xmlChar* xpath) { xmlXPathObject* result = NULL; std::unique_ptr<xmlXPathContext, ScopedPtrXmlXPathContextFree> context( xmlXPathNewContext(doc)); if (!context.get()) { LOG(ERROR) << "xmlXPathNewContext() returned NULL"; return NULL; } result = xmlXPathEvalExpression(xpath, context.get()); if (result == NULL) { LOG(ERROR) << "Unable to find " << xpath << " in XML document"; return NULL; } if(xmlXPathNodeSetIsEmpty(result->nodesetval)){ LOG(INFO) << "Nodeset is empty for " << xpath; xmlXPathFreeObject(result); return NULL; } return result; } // Returns the string value of a named attribute on a node, or empty string // if no such node exists. If the attribute exists and has a value of // empty string, there's no way to distinguish that from the attribute // not existing. string XmlGetProperty(xmlNode* node, const char* name) { if (!xmlHasProp(node, ConstXMLStr(name))) return ""; std::unique_ptr<xmlChar, ScopedPtrXmlFree> str( xmlGetProp(node, ConstXMLStr(name))); string ret(reinterpret_cast<const char *>(str.get())); return ret; } // Parses a 64 bit base-10 int from a string and returns it. Returns 0 // on error. If the string contains "0", that's indistinguishable from // error. off_t ParseInt(const string& str) { off_t ret = 0; int rc = sscanf(str.c_str(), "%" PRIi64, &ret); if (rc < 1) { // failure return 0; } return ret; } } // namespace {} bool OmahaRequestAction::ParseResponse(xmlDoc* doc, OmahaResponse* output_object, ScopedActionCompleter* completer) { static const char* kUpdatecheckNodeXpath("/response/app/updatecheck"); std::unique_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree> xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdatecheckNodeXpath))); if (!xpath_nodeset.get()) { completer->set_code(kActionCodeOmahaResponseInvalid); return false; } xmlNodeSet* nodeset = xpath_nodeset->nodesetval; CHECK(nodeset) << "XPath missing UpdateCheck NodeSet"; CHECK_GE(nodeset->nodeNr, 1); xmlNode* update_check_node = nodeset->nodeTab[0]; // chromium-os:37289: The PollInterval is not supported by Omaha server // currently. But still keeping this existing code in case we ever decide to // slow down the request rate from the server-side. Note that the // PollInterval is not persisted, so it has to be sent by the server on every // response to guarantee that the UpdateCheckScheduler uses this value // (otherwise, if the device got rebooted after the last server-indicated // value, it'll revert to the default value). // Note: The parsing for PollInterval happens even before parsing // of the status because we may want to specify the PollInterval even when // there's no update. if (!strings::StringToInt(XmlGetProperty(update_check_node, "PollInterval"), &output_object->poll_interval)) output_object->poll_interval = 0; if (!ParseStatus(update_check_node, output_object, completer)) return false; if (!ParseManifest(doc, output_object, completer)) return false; // Note: ParseUrls MUST be called before ParsePackage as ParsePackage // appends the package name to the URLs populated in this method. if (!ParseUrls(doc, output_object, completer)) return false; if (!ParsePackage(doc, output_object, completer)) return false; if (!ParseParams(doc, output_object, completer)) return false; output_object->update_exists = true; SetOutputObject(*output_object); completer->set_code(kActionCodeSuccess); return true; } bool OmahaRequestAction::ParseStatus(xmlNode* update_check_node, OmahaResponse* output_object, ScopedActionCompleter* completer) { // Get status. if (!xmlHasProp(update_check_node, ConstXMLStr("status"))) { LOG(ERROR) << "Omaha Response missing status"; completer->set_code(kActionCodeOmahaResponseInvalid); return false; } const string status(XmlGetProperty(update_check_node, "status")); if (status == "noupdate") { LOG(INFO) << "No update."; output_object->update_exists = false; SetOutputObject(*output_object); completer->set_code(kActionCodeSuccess); return false; } if (status != "ok") { LOG(ERROR) << "Unknown Omaha response status: " << status; completer->set_code(kActionCodeOmahaResponseInvalid); return false; } return true; } bool OmahaRequestAction::ParseManifest(xmlDoc* doc, OmahaResponse* output_object, ScopedActionCompleter* completer) { // Get the manifest node. static const char* kManifestNodeXPath("/response/app/updatecheck/manifest"); std::unique_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree> xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kManifestNodeXPath))); if (!xpath_nodeset.get()) { completer->set_code(kActionCodeOmahaResponseInvalid); return false; } xmlNodeSet* nodeset = xpath_nodeset->nodesetval; CHECK(nodeset) << "XPath missing " << kManifestNodeXPath; CHECK_GE(nodeset->nodeNr, 1); // We only care about the first (and only hopefully) manifest. xmlNode* manifest_node = nodeset->nodeTab[0]; // Parse the version, only used for informational purposes. const string version(XmlGetProperty(manifest_node, "version")); LOG(INFO) << "Omaha Response manifest version = " << version; output_object->display_version = version; return true; } bool OmahaRequestAction::ParseUrls(xmlDoc* doc, OmahaResponse* output_object, ScopedActionCompleter* completer) { // Get the update URL. static const char* kUpdateUrlNodeXPath("/response/app/updatecheck/urls/url"); std::unique_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree> xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kUpdateUrlNodeXPath))); if (!xpath_nodeset.get()) { completer->set_code(kActionCodeOmahaResponseInvalid); return false; } xmlNodeSet* nodeset = xpath_nodeset->nodesetval; CHECK(nodeset) << "XPath missing " << kUpdateUrlNodeXPath; CHECK_GE(nodeset->nodeNr, 1); LOG(INFO) << "Found " << nodeset->nodeNr << " url(s)"; output_object->payload_urls.clear(); for (int i = 0; i < nodeset->nodeNr; i++) { xmlNode* url_node = nodeset->nodeTab[i]; const string codebase(XmlGetProperty(url_node, "codebase")); if (codebase.empty()) { LOG(ERROR) << "Omaha Response URL has empty codebase"; completer->set_code(kActionCodeOmahaResponseInvalid); return false; } output_object->payload_urls.push_back(codebase); } return true; } bool OmahaRequestAction::ParsePackage(xmlDoc* doc, OmahaResponse* output_object, ScopedActionCompleter* completer) { // Get the package node. static const char* kPackageNodeXPath( "/response/app/updatecheck/manifest/packages/package"); std::unique_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree> xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kPackageNodeXPath))); if (!xpath_nodeset.get()) { completer->set_code(kActionCodeOmahaResponseInvalid); return false; } xmlNodeSet* nodeset = xpath_nodeset->nodesetval; CHECK(nodeset) << "XPath missing " << kPackageNodeXPath; CHECK_GE(nodeset->nodeNr, 1); // We only care about the first package. LOG(INFO) << "Processing first of " << nodeset->nodeNr << " package(s)"; xmlNode* package_node = nodeset->nodeTab[0]; // Get package properties one by one. // Parse the payload name to be appended to the base Url value. const string package_name(XmlGetProperty(package_node, "name")); LOG(INFO) << "Omaha Response package name = " << package_name; if (package_name.empty()) { LOG(ERROR) << "Omaha Response has empty package name"; completer->set_code(kActionCodeOmahaResponseInvalid); return false; } // Append the package name to each URL in our list so that we don't // propagate the urlBase vs packageName distinctions beyond this point. // From now on, we only need to use payload_urls. for (size_t i = 0; i < output_object->payload_urls.size(); i++) { // The strings should not be empty but better check that instead of crashing for back() on an empty string if (output_object->payload_urls[i].length() > 0 && output_object->payload_urls[i].back() != '/') { output_object->payload_urls[i] += "/"; } output_object->payload_urls[i] += package_name; LOG(INFO) << "Url" << i << ": " << output_object->payload_urls[i]; } // Parse the payload size. off_t size = ParseInt(XmlGetProperty(package_node, "size")); if (size <= 0) { LOG(ERROR) << "Omaha Response has invalid payload size: " << size; completer->set_code(kActionCodeOmahaResponseInvalid); return false; } output_object->size = size; LOG(INFO) << "Payload size = " << output_object->size << " bytes"; return true; } bool OmahaRequestAction::ParseParams(xmlDoc* doc, OmahaResponse* output_object, ScopedActionCompleter* completer) { // Get the action node where parameters are present. static const char* kActionNodeXPath( "/response/app/updatecheck/manifest/actions/action"); std::unique_ptr<xmlXPathObject, ScopedPtrXmlXPathObjectFree> xpath_nodeset(GetNodeSet(doc, ConstXMLStr(kActionNodeXPath))); if (!xpath_nodeset.get()) { completer->set_code(kActionCodeOmahaResponseInvalid); return false; } xmlNodeSet* nodeset = xpath_nodeset->nodesetval; CHECK(nodeset) << "XPath missing " << kActionNodeXPath; // We only care about the action that has event "postinall", because this is // where Omaha puts all the generic name/value pairs in the rule. LOG(INFO) << "Found " << nodeset->nodeNr << " action(s). Processing the postinstall action."; // pie_action_node holds the action node corresponding to the // postinstall event action, if present. xmlNode* pie_action_node = NULL; for (int i = 0; i < nodeset->nodeNr; i++) { xmlNode* action_node = nodeset->nodeTab[i]; if (XmlGetProperty(action_node, "event") == "postinstall") { pie_action_node = action_node; break; } } if (!pie_action_node) { LOG(ERROR) << "Omaha Response has no postinstall event action"; completer->set_code(kActionCodeOmahaResponseInvalid); return false; } output_object->hash = XmlGetProperty(pie_action_node, kTagSha256); if (output_object->hash.empty()) { LOG(ERROR) << "Omaha Response has empty sha256 value"; completer->set_code(kActionCodeOmahaResponseInvalid); return false; } // Get the optional properties one by one. output_object->more_info_url = XmlGetProperty(pie_action_node, kTagMoreInfo); output_object->needs_admin = XmlGetProperty(pie_action_node, kTagNeedsAdmin) == "true"; output_object->prompt = XmlGetProperty(pie_action_node, kTagPrompt) == "true"; output_object->deadline = XmlGetProperty(pie_action_node, kTagDeadline); string max = XmlGetProperty(pie_action_node, kTagMaxFailureCountPerUrl); if (!strings::StringToUint(max, &output_object->max_failure_count_per_url)) output_object->max_failure_count_per_url = kDefaultMaxFailureCountPerUrl; output_object->is_delta_payload = XmlGetProperty(pie_action_node, kTagIsDeltaPayload) == "true"; output_object->disable_payload_backoff = XmlGetProperty(pie_action_node, kTagDisablePayloadBackoff) == "true"; return true; } // If the transfer was successful, this uses libxml2 to parse the response // and fill in the appropriate fields of the output object. Also, notifies // the processor that we're done. void OmahaRequestAction::TransferComplete(HttpFetcher *fetcher, bool successful) { ScopedActionCompleter completer(processor_, this); string current_response(response_buffer_.begin(), response_buffer_.end()); LOG(INFO) << "Omaha request response: " << current_response; // Events are best effort transactions -- assume they always succeed. if (IsEvent()) { CHECK(!HasOutputPipe()) << "No output pipe allowed for event requests."; if (event_->result == OmahaEvent::kResultError && successful && utils::IsOfficialBuild()) { LOG(ERROR) << "HTTP reported success but Omaha reports an error."; } completer.set_code(kActionCodeSuccess); return; } if (!successful) { LOG(ERROR) << "Omaha request network transfer failed."; int code = GetHTTPResponseCode(); // Makes sure we send sane error values. if (code < 0 || code >= 1000) { code = 999; } completer.set_code(static_cast<ActionExitCode>( kActionCodeOmahaRequestHTTPResponseBase + code)); return; } // parse our response and fill the fields in the output object std::unique_ptr<xmlDoc, ScopedPtrXmlDocFree> doc( xmlParseMemory(&response_buffer_[0], response_buffer_.size())); if (!doc.get()) { LOG(ERROR) << "Omaha response not valid XML"; completer.set_code(response_buffer_.empty() ? kActionCodeOmahaRequestEmptyResponseError : kActionCodeOmahaRequestXMLParseError); return; } if (!HasOutputPipe()) { // Just set success to whether or not the http transfer succeeded, // which must be true at this point in the code. completer.set_code(kActionCodeSuccess); return; } OmahaResponse output_object; if (!ParseResponse(doc.get(), &output_object, &completer)) return; // Update the payload state with the current response. The payload state // will automatically reset all stale state if this response is different // from what's stored already. We are updating the payload state as late // as possible in this method so that if a new release gets pushed and then // got pulled back due to some issues, we don't want to clear our internal // state unnecessarily. PayloadStateInterface* payload_state = system_state_->payload_state(); payload_state->SetResponse(output_object); if (payload_state->ShouldBackoffDownload()) { output_object.update_exists = false; LOG(INFO) << "Ignoring Omaha updates in order to backoff our retry " "attempts"; completer.set_code(kActionCodeOmahaUpdateDeferredForBackoff); return; } } } // namespace chromeos_update_engine
#ifndef ORACLESOURCE #define ORACLESOURCE #include <iostream> #include <mariadb/conncpp.hpp> namespace N { class OracleSource { public: OracleSource(); ~OracleSource(); sql::Connection* connect(std::string user, std::string password, std::string database, std::string host, std::string port); sql::ResultSet* retrieve(sql::Connection* conn, std::string proposal_type); }; } #endif
// Copyright (c) 2009-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "uritests.h" #include "guiutil.h" #include "walletmodel.h" #include <QUrl> void URITests::uriTests() { SendCoinsRecipient rv; QUrl uri; uri.setUrl(QString("mrclassic:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?req-dontexist=")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("mrclassic:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?dontexist=")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 0); uri.setUrl(QString("mrclassic:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?label=Some Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.label == QString("Some Example Address")); QVERIFY(rv.amount == 0); uri.setUrl(QString("mrclassic:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?amount=0.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100000); uri.setUrl(QString("mrclassic:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?amount=1.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100100000); uri.setUrl(QString("mrclassic:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?amount=100&label=Some Example")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.amount == 10000000000LL); QVERIFY(rv.label == QString("Some Example")); uri.setUrl(QString("mrclassic:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?message=Some Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.label == QString()); QVERIFY(GUIUtil::parseBitcoinURI("mrclassic://XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?message=Some Example Address", &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.label == QString()); uri.setUrl(QString("mrclassic:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?req-message=Some Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("mrclassic:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?amount=1,000&label=Some Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("mrclassic:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?amount=1,000.0&label=Some Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("mrclassic:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?amount=100&label=Some Example&message=Some Example Message&IS=1")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.amount == 10000000000LL); QVERIFY(rv.label == QString("Some Example")); QVERIFY(rv.message == QString("Some Example Message")); QVERIFY(rv.fUseInstantSend == 1); uri.setUrl(QString("mrclassic:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?amount=100&label=Some Example&message=Some Example Message&IS=Something Invalid")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(rv.amount == 10000000000LL); QVERIFY(rv.label == QString("Some Example")); QVERIFY(rv.message == QString("Some Example Message")); QVERIFY(rv.fUseInstantSend != 1); uri.setUrl(QString("mrclassic:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?IS=1")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.fUseInstantSend == 1); uri.setUrl(QString("mrclassic:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg?IS=0")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.fUseInstantSend != 1); uri.setUrl(QString("mrclassic:XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.fUseInstantSend != 1); }
#include <VXpch.h> #include <Core/Modules/VXCore.h> #include <Core/Events/WindowEvent.h> #include <Graphics/GraphicsContext.h> #include <Core/VXConsole.h> Vortex::VXCore* GCore; DEFINE_LOGGER(LogCore); DEFINE_LOGGER(LogWindow); namespace Vortex { void VXCore::Startup() { CREATE_LOGGER(LogCore, spdlog::level::trace); VX_TRACE(LogCore, "Starting Vortex Core Module."); VXConsole::Init(); // Make sure we can't start the engine twice. if (m_IsTicking) throw std::exception("Vortex Core already started."); // Start the tick, and does frame delta calculation setup. m_IsTicking = true; QueryPerformanceFrequency(&m_Frequency); m_RenderDeltaTime = m_TickDeltaTime = 0; // Create the Vortex Input Module. m_Input = new VXInput(); m_Input->Startup(); // Creates the layer stack. m_LayerStack = new LayerStack(); // Creates the application and binds all the required Modules. m_App = CreateApplication(); VX_TRACE(LogCore, "Created Client application."); // Create the Graphics Context. GraphicsContext::Create(GraphicsAPI::DirectX11); // Creates the window, using the application-defined properties. m_Window = Window::Create(m_App->GetWindowProperties()); m_Window->SetEventCallback([&](Window* window, Event& event) { this->OnWindowEvent(window, event); }); GWindow = m_Window; m_Gui = new VXGui(); m_Gui->Startup(); m_3dUi = new VX3dUi(); m_3dUi->Startup(); m_Renderer = new VXRenderer(); m_Renderer->Startup(); m_ScriptManager = new VXScriptManager(); m_ScriptManager->Startup(); ::GInput = m_Input; ::GLayerStack = m_LayerStack; ::GRenderer = m_Renderer; ::GScriptManager = m_ScriptManager; ::GCore = this; // Starts the user-defined application. m_App->Start(); VX_TRACE(LogCore, "Started Client application."); VX_TRACE(LogCore, "Started Vortex Core Module."); } void VXCore::Shutdown() { VX_TRACE(LogCore, "Shutting down Vortex Core Module."); m_IsTicking = false; m_RenderedGui = true; m_Rendered3dUi = true; p_RenderThread->join(); // Destroys the layer stack. delete m_LayerStack; GLayerStack = m_LayerStack = nullptr; // Deletes the application, so the user doesn't have to worry about it. delete m_App; m_App = nullptr; m_ScriptManager->Shutdown(); delete m_ScriptManager; GScriptManager = m_ScriptManager = nullptr; m_Renderer->Shutdown(); delete m_Renderer; GRenderer = m_Renderer = nullptr; m_3dUi->Shutdown(); delete m_3dUi; m_3dUi = nullptr; // Deletes the Vortex GUI Module. m_Gui->Shutdown(); delete m_Gui; m_Gui = nullptr; // Destroys the window. delete m_Window; GWindow = m_Window = nullptr; // Destroys Graphics Context. GraphicsContext::Destroy(); // Deletes the Vortex Input Module. m_Input->Shutdown(); delete m_Input; GInput = m_Input = nullptr; ::GCore = nullptr; VX_TRACE(LogCore, "Shut down Vortex Core Module."); } void VXCore::Tick(float deltaTime) { ENG_PROFILESTART("Application Tick"); // Calls the application tick. m_App->Tick(deltaTime); ENG_PROFILEEND(); // Calls the layer stack tick. m_LayerStack->Tick(deltaTime); m_ScriptManager->Tick(deltaTime); } void VXCore::Quit() { // Locks mutex so two threads cannot concurrently quit the application. m_QuitMutex.lock(); // Makes sure no one else is keeping the Module running. if (m_CanQuit) { m_Gui->Quit(); m_Input->Quit(); m_Renderer->Quit(); m_ScriptManager->Quit(); m_App->Quit(); m_IsTicking = false; } else m_WantsQuit = true; m_QuitMutex.unlock(); } void VXCore::BlockQuit() { // Locks mutex so two threads don't concurrently block and allow quitting. m_QuitMutex.lock(); m_CanQuit = false; m_IsTicking = true; m_QuitMutex.unlock(); } void VXCore::AllowQuit() { // Locks mutex so two threads don't concurrently block and allow quitting. m_QuitMutex.lock(); m_CanQuit = true; m_QuitMutex.unlock(); } void VXCore::OnConsoleCommand(ConsoleCommand command) { std::string delimiter = "."; std::string variable = command.command.substr(0, command.command.find(delimiter)); command.command.erase(0, command.command.find(delimiter) + delimiter.length()); if (variable == "restart") { VX_INFO(LogConsole, "Core: Restarting..."); m_ShouldRestart = true; } else if (variable == "quit") { VX_INFO(LogConsole, "Core: Quitting..."); Quit(); } else if (variable == "help") { VX_INFO(LogConsole, "Core: Functions: "); VX_INFO(LogConsole, "Core: quit - Quits the Vortex Engine."); VX_INFO(LogConsole, "Core: restart - Restarts the Vortex Engine."); } else if (variable == "window") { m_Window->OnConsoleCommand({ command.command }); } else { VX_ERROR(LogConsole, "'{0}' is not a valid command for module core!", variable); } } void VXCore::OnWindowEvent(Window* window, Event& event) { if (!m_IsTicking) return; ENG_PROFILE("Event Dispatching"); auto dispatcher = EventDispatcher(event); // Dispatches all Input related events to the Vortex Input Module. dispatcher.Dispatch<KeyDownEvent>(BIND_EVENT(m_Input->KDEvent)); dispatcher.Dispatch<KeyUpEvent>(BIND_EVENT(m_Input->KUEvent)); dispatcher.Dispatch<MouseMoveEvent>(BIND_EVENT(m_Input->MMEvent)); dispatcher.Dispatch<MouseButtonDownEvent>(BIND_EVENT(m_Input->MDEvent)); dispatcher.Dispatch<MouseButtonUpEvent>(BIND_EVENT(m_Input->MUEvent)); dispatcher.Dispatch<MouseButtonDoubleClickEvent>(BIND_EVENT(m_Input->MDCEvent)); dispatcher.Dispatch<MouseScrollEvent>(BIND_EVENT(m_Input->MSEvent)); dispatcher.Dispatch<MouseRawEvent>(BIND_EVENT(m_Input->RMEvent)); dispatcher.Dispatch<WindowResizeEvent>(BIND_EVENT(m_Renderer->ResizeOnWindow)); if (event.GetType() == EventType::WindowDeactivate) { m_Input->ClearInputState(); } m_LayerStack->PassEvent(event); // Passes the event to the app if it hasn't been handled already. if (!event.IsHandled() && m_App) m_App->OnEvent(event); // Quit the application if the window was closed. Doing it after everything so they have a chance to block the quit. if (event.GetType() == EventType::WindowClose) Quit(); } void VXCore::RunTickLoop() { VX_TRACE(LogCore, "Starting Vortex Core Module Tick."); if (!m_IsTicking) throw std::exception("Module has not been started!"); p_RenderThread = new std::thread(&VXCore::RunRenderLoop, this); while (m_IsTicking) { // Quit application if required. if (m_WantsQuit && m_CanQuit) Quit(); if (m_ShouldRestart) { Quit(); Shutdown(); Startup(); m_ShouldRestart = false; } // Get time before frame. QueryPerformanceCounter(&m_TickLastTime); // Ticks the Vortex Input module. m_Input->Tick(m_TickDeltaTime); // Updates the application window, getting all window events. m_Window->GetEvents(); if (m_MainThreadFrameCount - 5 > m_RenderThreadFrameCount) { if (m_RenderedGui) { QueryPerformanceCounter(&m_TickCurrentTime); m_TickDeltaTime = (float)(m_TickCurrentTime.QuadPart - m_TickLastTime.QuadPart); m_TickDeltaTime /= m_Frequency.QuadPart; continue; } m_Gui->Tick(m_TickDeltaTime); m_RenderedGui = true; if (m_Rendered3dUi) { QueryPerformanceCounter(&m_TickCurrentTime); m_TickDeltaTime = (float)(m_TickCurrentTime.QuadPart - m_TickLastTime.QuadPart); m_TickDeltaTime /= m_Frequency.QuadPart; continue; } m_3dUi->Tick(m_TickDeltaTime); m_Rendered3dUi = true; QueryPerformanceCounter(&m_TickCurrentTime); m_TickDeltaTime = (float)(m_TickCurrentTime.QuadPart - m_TickLastTime.QuadPart); m_TickDeltaTime /= m_Frequency.QuadPart; m_MainThreadFrameCount++; continue; } else { Tick(m_TickDeltaTime); if (m_RenderedGui) { QueryPerformanceCounter(&m_TickCurrentTime); m_TickDeltaTime = (float)(m_TickCurrentTime.QuadPart - m_TickLastTime.QuadPart); m_TickDeltaTime /= m_Frequency.QuadPart; continue; } m_Gui->Tick(m_TickDeltaTime); m_RenderedGui = true; if (m_Rendered3dUi) { QueryPerformanceCounter(&m_TickCurrentTime); m_TickDeltaTime = (float)(m_TickCurrentTime.QuadPart - m_TickLastTime.QuadPart); m_TickDeltaTime /= m_Frequency.QuadPart; continue; } m_3dUi->Tick(m_TickDeltaTime); m_Rendered3dUi = true; QueryPerformanceCounter(&m_TickCurrentTime); m_TickDeltaTime = (float)(m_TickCurrentTime.QuadPart - m_TickLastTime.QuadPart); m_TickDeltaTime /= m_Frequency.QuadPart; m_MainThreadFrameCount++; } } VX_TRACE(LogCore, "Ended Vortex Core Module Tick."); } void VXCore::RunRenderLoop() { VX_TRACE(LogCore, "Started Render Thread ({0}).", p_RenderThread->get_id()); while (m_IsTicking) { // Get time before frame. QueryPerformanceCounter(&m_RenderLastTime); if (m_RenderThreadFrameCount > m_MainThreadFrameCount) { QueryPerformanceCounter(&m_RenderCurrentTime); m_RenderDeltaTime = (float)(m_RenderCurrentTime.QuadPart - m_RenderLastTime.QuadPart); m_RenderDeltaTime /= m_Frequency.QuadPart; continue; } m_Renderer->ResizeIfRequired(); m_RenderedGui = false; m_Rendered3dUi = false; m_Renderer->Tick(m_RenderDeltaTime); while (!m_Rendered3dUi) {} m_3dUi->Draw(); while (!m_RenderedGui) {} m_Gui->Draw(); m_Window->GetSwapChain()->Swap(m_Window->GetProperties().syncInterval); QueryPerformanceCounter(&m_RenderCurrentTime); m_RenderDeltaTime = (float)(m_RenderCurrentTime.QuadPart - m_RenderLastTime.QuadPart); m_RenderDeltaTime /= m_Frequency.QuadPart; m_RenderThreadFrameCount++; } VX_TRACE(LogCore, "Ended Render Thread."); } VXCore::VXCore() { /* We are replacing constructors and destructors with Startup() and Shutdown() methods so that we don 't have to keep reallocating memory for the Module if it is being started and stopped many times. This also helps in handling module restarting easily. We just wait for the tick to finish, and then call Shutdown() and Startup(). This way, a module can shut itself down and restart itself as well. */ } VXCore::~VXCore() { } }
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/services/ime/public/cpp/rulebased/def/th_pattajoti.h" namespace th_pattajoti { const char* kId = "th_pattajoti"; bool kIs102 = false; const char* kNormal[] = { u8"_", // BackQuote u8"=", // Digit1 u8"\u0e52", // Digit2 u8"\u0e53", // Digit3 u8"\u0e54", // Digit4 u8"\u0e55", // Digit5 u8"\u0e39", // Digit6 u8"\u0e57", // Digit7 u8"\u0e58", // Digit8 u8"\u0e59", // Digit9 u8"\u0e50", // Digit0 u8"\u0e51", // Minus u8"\u0e56", // Equal u8"\u0e47", // KeyQ u8"\u0e15", // KeyW u8"\u0e22", // KeyE u8"\u0e2d", // KeyR u8"\u0e23", // KeyT u8"\u0e48", // KeyY u8"\u0e14", // KeyU u8"\u0e21", // KeyI u8"\u0e27", // KeyO u8"\u0e41", // KeyP u8"\u0e43", // BracketLeft u8"\u0e0c", // BracketRight u8"\u0e3a", // Backslash u8"\u0e49", // KeyA u8"\u0e17", // KeyS u8"\u0e07", // KeyD u8"\u0e01", // KeyF u8"\u0e31", // KeyG u8"\u0e35", // KeyH u8"\u0e32", // KeyJ u8"\u0e19", // KeyK u8"\u0e40", // KeyL u8"\u0e44", // Semicolon u8"\u0e02", // Quote u8"\u0e1a", // KeyZ u8"\u0e1b", // KeyX u8"\u0e25", // KeyC u8"\u0e2b", // KeyV u8"\u0e34", // KeyB u8"\u0e04", // KeyN u8"\u0e2a", // KeyM u8"\u0e30", // Comma u8"\u0e08", // Period u8"\u0e1e", // Slash u8"\u0020", // Space }; const char* kShift[] = { u8"\u0e3f", // BackQuote u8"+", // Digit1 u8"\"", // Digit2 u8"/", // Digit3 u8",", // Digit4 u8"?", // Digit5 u8"\u0e38", // Digit6 u8"\u0e45", // Digit7 u8".", // Digit8 u8"(", // Digit9 u8")", // Digit0 u8"-", // Minus u8"%", // Equal u8"\u0e4a", // KeyQ u8"\u0e24", // KeyW u8"\u0e46", // KeyE u8"\u0e0d", // KeyR u8"\u0e29", // KeyT u8"\u0e36", // KeyY u8"\u0e1d", // KeyU u8"\u0e0b", // KeyI u8"\u0e16", // KeyO u8"\u0e12", // KeyP u8"\u0e2f", // BracketLeft u8"\u0e26", // BracketRight u8"\u0e4d", // Backslash u8"\u0e4b", // KeyA u8"\u0e18", // KeyS u8"\u0e33", // KeyD u8"\u0e13", // KeyF u8"\u0e4c", // KeyG u8"\u0e37", // KeyH u8"\u0e1c", // KeyJ u8"\u0e0a", // KeyK u8"\u0e42", // KeyL u8"\u0e06", // Semicolon u8"\u0e11", // Quote u8"\u0e0e", // KeyZ u8"\u0e0f", // KeyX u8"\u0e10", // KeyC u8"\u0e20", // KeyV u8"\u0e31\u0e49", // KeyB u8"\u0e28", // KeyN u8"\u0e2e", // KeyM u8"\u0e1f", // Comma u8"\u0e09", // Period u8"\u0e2c", // Slash u8"\u0020", // Space }; const char* kAltGr[] = { u8"_", // BackQuote u8"=", // Digit1 u8"\u0e52", // Digit2 u8"\u0e53", // Digit3 u8"\u0e54", // Digit4 u8"\u0e55", // Digit5 u8"\u0e39", // Digit6 u8"\u0e57", // Digit7 u8"\u0e58", // Digit8 u8"\u0e59", // Digit9 u8"\u0e50", // Digit0 u8"\u0e51", // Minus u8"\u0e56", // Equal u8"\u0e47", // KeyQ u8"\u0e15", // KeyW u8"\u0e22", // KeyE u8"\u0e2d", // KeyR u8"\u0e23", // KeyT u8"\u0e48", // KeyY u8"\u0e14", // KeyU u8"\u0e21", // KeyI u8"\u0e27", // KeyO u8"\u0e41", // KeyP u8"\u0e43", // BracketLeft u8"\u0e0c", // BracketRight u8"\u0e3a", // Backslash u8"\u0e49", // KeyA u8"\u0e17", // KeyS u8"\u0e07", // KeyD u8"\u0e01", // KeyF u8"\u0e31", // KeyG u8"\u0e35", // KeyH u8"\u0e32", // KeyJ u8"\u0e19", // KeyK u8"\u0e40", // KeyL u8"\u0e44", // Semicolon u8"\u0e02", // Quote u8"\u0e1a", // KeyZ u8"\u0e1b", // KeyX u8"\u0e25", // KeyC u8"\u0e2b", // KeyV u8"\u0e34", // KeyB u8"\u0e04", // KeyN u8"\u0e2a", // KeyM u8"\u0e30", // Comma u8"\u0e08", // Period u8"\u0e1e", // Slash u8"\u0020", // Space }; const char* kCapslock[] = { u8"\u0e3f", // BackQuote u8"+", // Digit1 u8"\"", // Digit2 u8"/", // Digit3 u8",", // Digit4 u8"?", // Digit5 u8"\u0e38", // Digit6 u8"\u0e45", // Digit7 u8".", // Digit8 u8"(", // Digit9 u8")", // Digit0 u8"-", // Minus u8"%", // Equal u8"\u0e4a", // KeyQ u8"\u0e24", // KeyW u8"\u0e46", // KeyE u8"\u0e0d", // KeyR u8"\u0e29", // KeyT u8"\u0e36", // KeyY u8"\u0e1d", // KeyU u8"\u0e0b", // KeyI u8"\u0e16", // KeyO u8"\u0e12", // KeyP u8"\u0e2f", // BracketLeft u8"\u0e26", // BracketRight u8"\u0e4d", // Backslash u8"\u0e4b", // KeyA u8"\u0e18", // KeyS u8"\u0e33", // KeyD u8"\u0e13", // KeyF u8"\u0e4c", // KeyG u8"\u0e37", // KeyH u8"\u0e1c", // KeyJ u8"\u0e0a", // KeyK u8"\u0e42", // KeyL u8"\u0e06", // Semicolon u8"\u0e11", // Quote u8"\u0e0e", // KeyZ u8"\u0e0f", // KeyX u8"\u0e10", // KeyC u8"\u0e20", // KeyV u8"\u0e31\u0e49", // KeyB u8"\u0e28", // KeyN u8"\u0e2e", // KeyM u8"\u0e1f", // Comma u8"\u0e09", // Period u8"\u0e2c", // Slash u8"\u0020", // Space }; const char* kShiftAltGr[] = { u8"\u0e3f", // BackQuote u8"+", // Digit1 u8"\"", // Digit2 u8"/", // Digit3 u8",", // Digit4 u8"?", // Digit5 u8"\u0e38", // Digit6 u8"\u0e45", // Digit7 u8".", // Digit8 u8"(", // Digit9 u8")", // Digit0 u8"-", // Minus u8"%", // Equal u8"\u0e4a", // KeyQ u8"\u0e24", // KeyW u8"\u0e46", // KeyE u8"\u0e0d", // KeyR u8"\u0e29", // KeyT u8"\u0e36", // KeyY u8"\u0e1d", // KeyU u8"\u0e0b", // KeyI u8"\u0e16", // KeyO u8"\u0e12", // KeyP u8"\u0e2f", // BracketLeft u8"\u0e26", // BracketRight u8"\u0e4d", // Backslash u8"\u0e4b", // KeyA u8"\u0e18", // KeyS u8"\u0e33", // KeyD u8"\u0e13", // KeyF u8"\u0e4c", // KeyG u8"\u0e37", // KeyH u8"\u0e1c", // KeyJ u8"\u0e0a", // KeyK u8"\u0e42", // KeyL u8"\u0e06", // Semicolon u8"\u0e11", // Quote u8"\u0e0e", // KeyZ u8"\u0e0f", // KeyX u8"\u0e10", // KeyC u8"\u0e20", // KeyV u8"\u0e31\u0e49", // KeyB u8"\u0e28", // KeyN u8"\u0e2e", // KeyM u8"\u0e1f", // Comma u8"\u0e09", // Period u8"\u0e2c", // Slash u8"\u0020", // Space }; const char* kAltgrCapslock[] = { u8"\u0e3f", // BackQuote u8"+", // Digit1 u8"\"", // Digit2 u8"/", // Digit3 u8",", // Digit4 u8"?", // Digit5 u8"\u0e38", // Digit6 u8"\u0e45", // Digit7 u8".", // Digit8 u8"(", // Digit9 u8")", // Digit0 u8"-", // Minus u8"%", // Equal u8"\u0e4a", // KeyQ u8"\u0e24", // KeyW u8"\u0e46", // KeyE u8"\u0e0d", // KeyR u8"\u0e29", // KeyT u8"\u0e36", // KeyY u8"\u0e1d", // KeyU u8"\u0e0b", // KeyI u8"\u0e16", // KeyO u8"\u0e12", // KeyP u8"\u0e2f", // BracketLeft u8"\u0e26", // BracketRight u8"\u0e4d", // Backslash u8"\u0e4b", // KeyA u8"\u0e18", // KeyS u8"\u0e33", // KeyD u8"\u0e13", // KeyF u8"\u0e4c", // KeyG u8"\u0e37", // KeyH u8"\u0e1c", // KeyJ u8"\u0e0a", // KeyK u8"\u0e42", // KeyL u8"\u0e06", // Semicolon u8"\u0e11", // Quote u8"\u0e0e", // KeyZ u8"\u0e0f", // KeyX u8"\u0e10", // KeyC u8"\u0e20", // KeyV u8"\u0e31\u0e49", // KeyB u8"\u0e28", // KeyN u8"\u0e2e", // KeyM u8"\u0e1f", // Comma u8"\u0e09", // Period u8"\u0e2c", // Slash u8"\u0020", // Space }; const char* kShiftCapslock[] = { u8"_", // BackQuote u8"=", // Digit1 u8"\u0e52", // Digit2 u8"\u0e53", // Digit3 u8"\u0e54", // Digit4 u8"\u0e55", // Digit5 u8"\u0e39", // Digit6 u8"\u0e57", // Digit7 u8"\u0e58", // Digit8 u8"\u0e59", // Digit9 u8"\u0e50", // Digit0 u8"\u0e51", // Minus u8"\u0e56", // Equal u8"\u0e47", // KeyQ u8"\u0e15", // KeyW u8"\u0e22", // KeyE u8"\u0e2d", // KeyR u8"\u0e23", // KeyT u8"\u0e48", // KeyY u8"\u0e14", // KeyU u8"\u0e21", // KeyI u8"\u0e27", // KeyO u8"\u0e41", // KeyP u8"\u0e43", // BracketLeft u8"\u0e0c", // BracketRight u8"\u0e3a", // Backslash u8"\u0e49", // KeyA u8"\u0e17", // KeyS u8"\u0e07", // KeyD u8"\u0e01", // KeyF u8"\u0e31", // KeyG u8"\u0e35", // KeyH u8"\u0e32", // KeyJ u8"\u0e19", // KeyK u8"\u0e40", // KeyL u8"\u0e44", // Semicolon u8"\u0e02", // Quote u8"\u0e1a", // KeyZ u8"\u0e1b", // KeyX u8"\u0e25", // KeyC u8"\u0e2b", // KeyV u8"\u0e34", // KeyB u8"\u0e04", // KeyN u8"\u0e2a", // KeyM u8"\u0e30", // Comma u8"\u0e08", // Period u8"\u0e1e", // Slash u8"\u0020", // Space }; const char* kShiftAltGrCapslock[] = { u8"_", // BackQuote u8"=", // Digit1 u8"\u0e52", // Digit2 u8"\u0e53", // Digit3 u8"\u0e54", // Digit4 u8"\u0e55", // Digit5 u8"\u0e39", // Digit6 u8"\u0e57", // Digit7 u8"\u0e58", // Digit8 u8"\u0e59", // Digit9 u8"\u0e50", // Digit0 u8"\u0e51", // Minus u8"\u0e56", // Equal u8"\u0e47", // KeyQ u8"\u0e15", // KeyW u8"\u0e22", // KeyE u8"\u0e2d", // KeyR u8"\u0e23", // KeyT u8"\u0e48", // KeyY u8"\u0e14", // KeyU u8"\u0e21", // KeyI u8"\u0e27", // KeyO u8"\u0e41", // KeyP u8"\u0e43", // BracketLeft u8"\u0e0c", // BracketRight u8"\u0e3a", // Backslash u8"\u0e49", // KeyA u8"\u0e17", // KeyS u8"\u0e07", // KeyD u8"\u0e01", // KeyF u8"\u0e31", // KeyG u8"\u0e35", // KeyH u8"\u0e32", // KeyJ u8"\u0e19", // KeyK u8"\u0e40", // KeyL u8"\u0e44", // Semicolon u8"\u0e02", // Quote u8"\u0e1a", // KeyZ u8"\u0e1b", // KeyX u8"\u0e25", // KeyC u8"\u0e2b", // KeyV u8"\u0e34", // KeyB u8"\u0e04", // KeyN u8"\u0e2a", // KeyM u8"\u0e30", // Comma u8"\u0e08", // Period u8"\u0e1e", // Slash u8"\u0020", // Space }; const char** kKeyMap[8] = { kNormal, kShift, kAltGr, kShiftAltGr, kCapslock, kShiftCapslock, kAltgrCapslock, kShiftAltGrCapslock}; } // namespace th_pattajoti
#include "Smark/SmkConfig.h" #include "Smark/SmkMarkWidget.h" SmkMarkWidget::SmkMarkWidget(QWidget* parent) : SmkBasicMarkWidget(parent) { connect(verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(when_VerticalScrollBar_valueChanged(int)) ); } /* ***************************************************************************** * * synchronized scrolling * * ****************************************************************************/ float SmkMarkWidget::scrollRatio() { QScrollBar* scroll = verticalScrollBar(); return float(scroll->value()-scroll->minimum()) / float(scroll->maximum()-scroll->minimum()); } void SmkMarkWidget::when_VerticalScrollBar_valueChanged(int val) { QScrollBar* scroll = verticalScrollBar(); float ratio = float(val-scroll->minimum()) / float(scroll->maximum()-scroll->minimum()); emit verticalScroll(ratio); } /* ***************************************************************************** * * find and replace * * ****************************************************************************/ void SmkMarkWidget::findPrevious(const QString& text, bool cased, bool whole) { QTextDocument::FindFlags find_flags; find_flags |= QTextDocument::FindBackward; if(cased) find_flags |= QTextDocument::FindCaseSensitively; if(whole) find_flags |= QTextDocument::FindWholeWords; this->find(text, find_flags); } void SmkMarkWidget::findNext(const QString& text, bool cased, bool whole) { QTextDocument::FindFlags find_flags; if(cased) find_flags |= QTextDocument::FindCaseSensitively; if(whole) find_flags |= QTextDocument::FindWholeWords; this->find(text, find_flags); } void SmkMarkWidget::replaceCurrent(const QString& new_text) { QTextCursor cursor = this->textCursor(); cursor.insertText(new_text); } void SmkMarkWidget::replaceAll(const QString& old_text, const QString& new_text, bool cased, bool /*whole*/) { // \todo replace all like this can't redo & undo Qt::CaseSensitivity cs = cased ? Qt::CaseSensitive : Qt::CaseInsensitive; QString context = this->toPlainText(); context.replace(old_text, new_text, cs); this->setPlainText(context); } /* ***************************************************************************** * * set selected format * * ****************************************************************************/ void SmkMarkWidget::setSelectedFormat(const QString& before, const QString& after) { QTextCursor cursor = this->textCursor(); QString selected = cursor.selectedText(); if(selected.startsWith(before) && selected.endsWith(after)) { selected.remove(before); selected.remove(after); } else { selected.prepend(before); selected.append(after); } cursor.insertText(selected); } void SmkMarkWidget::setSelectedBlod(void) { setSelectedFormat("<b>", "</b>"); } void SmkMarkWidget::setSelectedItalic(void) { setSelectedFormat("<i>", "</i>"); } void SmkMarkWidget::setSelectedUnderLine(void) { setSelectedFormat("<u>", "</u>"); } void SmkMarkWidget::setSelectedDeleted(void) { setSelectedFormat("<del>", "</del>"); } void SmkMarkWidget::setSelectedQuote(void) { QTextCursor cursor = this->textCursor(); if(cursor.hasSelection()) { QString selected = cursor.selectedText(); QStringList lines = selected.split(SMK_LINE_END); if(lines.size() == 1) { setSelectedFormat("<q>", "</q>"); } else { for(QStringList::iterator it=lines.begin(); it!=lines.end(); ++it) it->prepend("> "); cursor.insertText(lines.join(SMK_LINE_END)); } } // if(cursor.hasSelection()) } void SmkMarkWidget::setSelectedCode(void) { setSelectedFormat("`", "`"); } void SmkMarkWidget::setSelectedSub(void) { setSelectedFormat("<sub>", "</sub>"); } void SmkMarkWidget::setSelectedSup(void) { setSelectedFormat("<sup>", "</sup>"); } void SmkMarkWidget::setSelectedBigger(void) { setSelectedFormat("<big>", "</big>"); } void SmkMarkWidget::setSelectedSmaller(void) { setSelectedFormat("<small>", "</small>"); } void SmkMarkWidget::setSelectedOrderedList(void) { QTextCursor cursor = this->textCursor(); QString selected = cursor.selectedText(); QStringList lines = selected.split(SMK_LINE_END); int list_num = 1; for(QStringList::iterator it=lines.begin(); it!=lines.end(); ++it) { if(! it->isEmpty()) { it->prepend(" " + QString::number(list_num) + ". "); ++list_num; } } cursor.insertText(lines.join(SMK_LINE_END)); } void SmkMarkWidget::setSelectedUnorderedList(void) { QTextCursor cursor = this->textCursor(); QString selected = cursor.selectedText(); QStringList lines = selected.split(SMK_LINE_END); for(QStringList::iterator it=lines.begin(); it!=lines.end(); ++it) if(! it->isEmpty()) it->prepend(" + "); cursor.insertText(lines.join(SMK_LINE_END)); } void SmkMarkWidget::setSelectedLeftAlign(void) { setSelectedFormat("<p align=left>", "</p>"); } void SmkMarkWidget::setSelectedRightAlign(void) { setSelectedFormat("<p align=right>", "</p>"); } void SmkMarkWidget::setSelectedCenterAlign(void) { setSelectedFormat("<center>", "</center>"); } /* ***************************************************************************** * * insert context template * * ****************************************************************************/ void SmkMarkWidget::insertImage(void) { QTextCursor cursor = this->textCursor(); cursor.insertText("<p align=\"center\">\n" " <img src=\"____\" width=\"60%\">\n" " <small> tittle </small>\n" "</p>"); } void SmkMarkWidget::insertLink(void) { QTextCursor cursor = this->textCursor(); QString selected = cursor.selectedText(); if(selected.isEmpty()) { cursor.insertText("[___](___)"); } else { selected.prepend("["); selected.append("](____)"); cursor.insertText(selected); } } void SmkMarkWidget::insertMathJax(void) { QTextCursor cursor = this->textCursor(); QString selected = cursor.selectedText(); if(cursor.atBlockStart()) { // the cursor is at the start of a block // insert a center align math formation if(selected.isEmpty()) { cursor.insertText("<center>$$\n" "_____\n" "$$</center>"); } else { selected.prepend("<center>$$\n"); selected.append("$$</center>"); cursor.insertText(selected); } } else { // the cursor is not at the start of a block // insert a inline math formation if(selected.isEmpty()) { cursor.insertText("${ ____ }$"); } else { selected.prepend("${ "); selected.append(" }$"); cursor.insertText(selected); } }//if(cursor.atBlockStart()... } /* ***************************************************************************** * * event porcess * * ****************************************************************************/ void SmkMarkWidget::keyPressEvent(QKeyEvent* event) { // switch tab char to spaces if(event->key() == Qt::Key_Tab) { QTextCursor cursor = this->textCursor(); if(cursor.hasSelection()) { QString selected = cursor.selectedText(); QStringList lines = selected.split(SMK_LINE_END); bool inverse_operation = (event->modifiers() & Qt::ControlModifier) || (event->modifiers() & Qt::ShiftModifier); if( inverse_operation ) { // [Ctrl + Tab] or [Shift + Tab], remove an indentation for(QStringList::iterator it=lines.begin(); it!=lines.end(); ++it) if(it->startsWith(" ")) it->remove(0, 4); } else { // Only Tab, add an indentation for(QStringList::iterator it=lines.begin(); it!=lines.end(); ++it) if(! it->isEmpty()) it->prepend(" "); } cursor.insertText(lines.join(SMK_LINE_END)); } else { // if(cursor.hasSelection()) // Just insert a '\t', but we replace '\t' as " " cursor.insertText(" "); } // if(cursor.hasSelection()) return; } SmkBasicMarkWidget::keyPressEvent(event); }
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CameraOfflineSessionBase.h" namespace android { /** * Base class destructors */ CameraOfflineSessionBase::~CameraOfflineSessionBase() { } } // namespace android
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2017 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "amount.h" #include "tinyformat.h" CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nSize) { if (nSize > 0) nSatoshisPerK = nFeePaid * 1000 / nSize; else nSatoshisPerK = 0; } CAmount CFeeRate::GetFee(size_t nSize) const { CAmount nFee = nSatoshisPerK * nSize / 1000; if (nFee == 0 && nSatoshisPerK > 0) nFee = nSatoshisPerK; return nFee; } std::string CFeeRate::ToString() const { return strprintf("%d.%08d ICOL/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN); }
// 2次低域通過濾波器クラス // 2011/02/14 Yuki YOKOKURA // // 2次低域通過濾波器 G(s)=w^2/(s^2 + w/Q*s + w^2) (双一次変換) // // Copyright (C) 2011 Yuki YOKOKURA // 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 3 of the License, or 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 <http://www.gnu.org/licenses/>. // Besides, you can negotiate about other options of licenses instead of GPL. // If you would like to get other licenses, please contact us<yuki@katsura.sd.keio.ac.jp>. #ifndef LOWPASSFILTER2 #define LOWPASSFILTER2 namespace ARCS { // ARCS名前空間 class LowPassFilter2 { private: double Ts; // [s] 制御周期 double w; // [rad/s] 遮断周波数 double Q; // 鋭さ(0.5のときに重根設定となる) double uZ1; // 状態変数1 変数名Z1の意味はz変換のz^(-1)を示す double uZ2; // 状態変数2 double uZ3; // 状態変数3 double yZ1; // 状態変数4 double yZ2; // 状態変数5 double yZ3; // 状態変数6 public: LowPassFilter2(double CutFreq, double Sharp, double SmplTime); // コンストラクタ CutFreq;[rad/s] 遮断周波数,Sharp;鋭さ,SmplTime;[s] 制御周期 ~LowPassFilter2(); // デストラクタ double GetSignal(double u); // 出力信号の取得 u;入力信号 void SetCutFreq(double CutFreq); // 遮断周波数の再設定 CutFreq;[rad/s] 遮断周波数 void SetSharpness(double Sharp); // 鋭さの再設定 Sharp;鋭さ void SetSmplTime(double SmplTime); // 制御周期の再設定 SmplTime;[s] 制御周期 void ClearStateVars(void); // すべての状態変数のリセット }; } #endif
#include <iostream> using namespace std; int main(){ int n; while(cin>>n){ if(n == 1){ cout<<1<<'\n'; continue; } cout<<n*2-2<<'\n'; } return 0; }
//If Statements by u1tbmo #include <iostream> using namespace std; int main(){ bool is_cool; bool is_awesome; cout << "Input 1 for \"TRUE\" and 0 for \"FALSE\"." << endl; cout << "Are you cool? (1/0)" << endl; cin >> is_cool; cout << "Are you awesome? (1/0)" << endl; cin >> is_awesome; if(is_cool && is_awesome){ cout << "You are cool and awesome!"; } else if(is_cool && !is_awesome){ cout << "You are cool although not awesome. (what\?\?)"; } else if(!is_cool&& is_awesome){ cout << "You are not cool although you're awesome. (what\?\?)"; } else{ cout << "You are not cool and awesome. (Although this message comes from a machine)"; } return 0; }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2020 The F44RedCoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <netbase.h> #include <sync.h> #include <tinyformat.h> #include <util/strencodings.h> #include <util/string.h> #include <util/system.h> #include <atomic> #ifndef WIN32 #include <fcntl.h> #else #include <codecvt> #endif #ifdef USE_POLL #include <poll.h> #endif #if !defined(MSG_NOSIGNAL) #define MSG_NOSIGNAL 0 #endif // Settings static RecursiveMutex cs_proxyInfos; static proxyType proxyInfo[NET_MAX] GUARDED_BY(cs_proxyInfos); static proxyType nameProxy GUARDED_BY(cs_proxyInfos); int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT; bool fNameLookup = DEFAULT_NAME_LOOKUP; // Need ample time for negotiation for very slow proxies such as Tor (milliseconds) static const int SOCKS5_RECV_TIMEOUT = 20 * 1000; static std::atomic<bool> interruptSocks5Recv(false); enum Network ParseNetwork(const std::string& net_in) { std::string net = ToLower(net_in); if (net == "ipv4") return NET_IPV4; if (net == "ipv6") return NET_IPV6; if (net == "onion") return NET_ONION; if (net == "tor") { LogPrintf("Warning: net name 'tor' is deprecated and will be removed in the future. You should use 'onion' instead.\n"); return NET_ONION; } return NET_UNROUTABLE; } std::string GetNetworkName(enum Network net) { switch(net) { case NET_IPV4: return "ipv4"; case NET_IPV6: return "ipv6"; case NET_ONION: return "onion"; default: return ""; } } bool static LookupIntern(const std::string& name, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup) { vIP.clear(); if (!ValidAsCString(name)) { return false; } { CNetAddr addr; // From our perspective, onion addresses are not hostnames but rather // direct encodings of CNetAddr much like IPv4 dotted-decimal notation // or IPv6 colon-separated hextet notation. Since we can't use // getaddrinfo to decode them and it wouldn't make sense to resolve // them, we return a network address representing it instead. See // CNetAddr::SetSpecial(const std::string&) for more details. if (addr.SetSpecial(name)) { vIP.push_back(addr); return true; } } struct addrinfo aiHint; memset(&aiHint, 0, sizeof(struct addrinfo)); // We want a TCP port, which is a streaming socket type aiHint.ai_socktype = SOCK_STREAM; aiHint.ai_protocol = IPPROTO_TCP; // We don't care which address family (IPv4 or IPv6) is returned aiHint.ai_family = AF_UNSPEC; // If we allow lookups of hostnames, use the AI_ADDRCONFIG flag to only // return addresses whose family we have an address configured for. // // If we don't allow lookups, then use the AI_NUMERICHOST flag for // getaddrinfo to only decode numerical network addresses and suppress // hostname lookups. aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST; struct addrinfo *aiRes = nullptr; int nErr = getaddrinfo(name.c_str(), nullptr, &aiHint, &aiRes); if (nErr) return false; // Traverse the linked list starting with aiTrav, add all non-internal // IPv4,v6 addresses to vIP while respecting nMaxSolutions. struct addrinfo *aiTrav = aiRes; while (aiTrav != nullptr && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions)) { CNetAddr resolved; if (aiTrav->ai_family == AF_INET) { assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in)); resolved = CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr); } if (aiTrav->ai_family == AF_INET6) { assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6)); struct sockaddr_in6* s6 = (struct sockaddr_in6*) aiTrav->ai_addr; resolved = CNetAddr(s6->sin6_addr, s6->sin6_scope_id); } /* Never allow resolving to an internal address. Consider any such result invalid */ if (!resolved.IsInternal()) { vIP.push_back(resolved); } aiTrav = aiTrav->ai_next; } freeaddrinfo(aiRes); return (vIP.size() > 0); } /** * Resolve a host string to its corresponding network addresses. * * @param name The string representing a host. Could be a name or a numerical * IP address (IPv6 addresses in their bracketed form are * allowed). * @param[out] vIP The resulting network addresses to which the specified host * string resolved. * * @returns Whether or not the specified host string successfully resolved to * any resulting network addresses. * * @see Lookup(const char *, std::vector<CService>&, int, bool, unsigned int) * for additional parameter descriptions. */ bool LookupHost(const std::string& name, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup) { if (!ValidAsCString(name)) { return false; } std::string strHost = name; if (strHost.empty()) return false; if (strHost.front() == '[' && strHost.back() == ']') { strHost = strHost.substr(1, strHost.size() - 2); } return LookupIntern(strHost, vIP, nMaxSolutions, fAllowLookup); } /** * Resolve a host string to its first corresponding network address. * * @see LookupHost(const std::string&, std::vector<CNetAddr>&, unsigned int, bool) for * additional parameter descriptions. */ bool LookupHost(const std::string& name, CNetAddr& addr, bool fAllowLookup) { if (!ValidAsCString(name)) { return false; } std::vector<CNetAddr> vIP; LookupHost(name, vIP, 1, fAllowLookup); if(vIP.empty()) return false; addr = vIP.front(); return true; } /** * Resolve a service string to its corresponding service. * * @param name The string representing a service. Could be a name or a * numerical IP address (IPv6 addresses should be in their * disambiguated bracketed form), optionally followed by a port * number. (e.g. example.com:8333 or * [2001:db8:85a3:8d3:1319:8a2e:370:7348]:420) * @param[out] vAddr The resulting services to which the specified service string * resolved. * @param portDefault The default port for resulting services if not specified * by the service string. * @param fAllowLookup Whether or not hostname lookups are permitted. If yes, * external queries may be performed. * @param nMaxSolutions The maximum number of results we want, specifying 0 * means "as many solutions as we get." * * @returns Whether or not the service string successfully resolved to any * resulting services. */ bool Lookup(const std::string& name, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions) { if (name.empty() || !ValidAsCString(name)) { return false; } int port = portDefault; std::string hostname; SplitHostPort(name, port, hostname); std::vector<CNetAddr> vIP; bool fRet = LookupIntern(hostname, vIP, nMaxSolutions, fAllowLookup); if (!fRet) return false; vAddr.resize(vIP.size()); for (unsigned int i = 0; i < vIP.size(); i++) vAddr[i] = CService(vIP[i], port); return true; } /** * Resolve a service string to its first corresponding service. * * @see Lookup(const char *, std::vector<CService>&, int, bool, unsigned int) * for additional parameter descriptions. */ bool Lookup(const std::string& name, CService& addr, int portDefault, bool fAllowLookup) { if (!ValidAsCString(name)) { return false; } std::vector<CService> vService; bool fRet = Lookup(name, vService, portDefault, fAllowLookup, 1); if (!fRet) return false; addr = vService[0]; return true; } /** * Resolve a service string with a numeric IP to its first corresponding * service. * * @returns The resulting CService if the resolution was successful, [::]:0 * otherwise. * * @see Lookup(const char *, CService&, int, bool) for additional parameter * descriptions. */ CService LookupNumeric(const std::string& name, int portDefault) { if (!ValidAsCString(name)) { return {}; } CService addr; // "1.2:345" will fail to resolve the ip, but will still set the port. // If the ip fails to resolve, re-init the result. if(!Lookup(name, addr, portDefault, false)) addr = CService(); return addr; } struct timeval MillisToTimeval(int64_t nTimeout) { struct timeval timeout; timeout.tv_sec = nTimeout / 1000; timeout.tv_usec = (nTimeout % 1000) * 1000; return timeout; } /** SOCKS version */ enum SOCKSVersion: uint8_t { SOCKS4 = 0x04, SOCKS5 = 0x05 }; /** Values defined for METHOD in RFC1928 */ enum SOCKS5Method: uint8_t { NOAUTH = 0x00, //!< No authentication required GSSAPI = 0x01, //!< GSSAPI USER_PASS = 0x02, //!< Username/password NO_ACCEPTABLE = 0xff, //!< No acceptable methods }; /** Values defined for CMD in RFC1928 */ enum SOCKS5Command: uint8_t { CONNECT = 0x01, BIND = 0x02, UDP_ASSOCIATE = 0x03 }; /** Values defined for REP in RFC1928 */ enum SOCKS5Reply: uint8_t { SUCCEEDED = 0x00, //!< Succeeded GENFAILURE = 0x01, //!< General failure NOTALLOWED = 0x02, //!< Connection not allowed by ruleset NETUNREACHABLE = 0x03, //!< Network unreachable HOSTUNREACHABLE = 0x04, //!< Network unreachable CONNREFUSED = 0x05, //!< Connection refused TTLEXPIRED = 0x06, //!< TTL expired CMDUNSUPPORTED = 0x07, //!< Command not supported ATYPEUNSUPPORTED = 0x08, //!< Address type not supported }; /** Values defined for ATYPE in RFC1928 */ enum SOCKS5Atyp: uint8_t { IPV4 = 0x01, DOMAINNAME = 0x03, IPV6 = 0x04, }; /** Status codes that can be returned by InterruptibleRecv */ enum class IntrRecvError { OK, Timeout, Disconnected, NetworkError, Interrupted }; /** * Try to read a specified number of bytes from a socket. Please read the "see * also" section for more detail. * * @param data The buffer where the read bytes should be stored. * @param len The number of bytes to read into the specified buffer. * @param timeout The total timeout in milliseconds for this read. * @param hSocket The socket (has to be in non-blocking mode) from which to read * bytes. * * @returns An IntrRecvError indicating the resulting status of this read. * IntrRecvError::OK only if all of the specified number of bytes were * read. * * @see This function can be interrupted by calling InterruptSocks5(bool). * Sockets can be made non-blocking with SetSocketNonBlocking(const * SOCKET&, bool). */ static IntrRecvError InterruptibleRecv(uint8_t* data, size_t len, int timeout, const SOCKET& hSocket) { int64_t curTime = GetTimeMillis(); int64_t endTime = curTime + timeout; // Maximum time to wait for I/O readiness. It will take up until this time // (in millis) to break off in case of an interruption. const int64_t maxWait = 1000; while (len > 0 && curTime < endTime) { ssize_t ret = recv(hSocket, (char*)data, len, 0); // Optimistically try the recv first if (ret > 0) { len -= ret; data += ret; } else if (ret == 0) { // Unexpected disconnection return IntrRecvError::Disconnected; } else { // Other error or blocking int nErr = WSAGetLastError(); if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) { if (!IsSelectableSocket(hSocket)) { return IntrRecvError::NetworkError; } // Only wait at most maxWait milliseconds at a time, unless // we're approaching the end of the specified total timeout int timeout_ms = std::min(endTime - curTime, maxWait); #ifdef USE_POLL struct pollfd pollfd = {}; pollfd.fd = hSocket; pollfd.events = POLLIN; int nRet = poll(&pollfd, 1, timeout_ms); #else struct timeval tval = MillisToTimeval(timeout_ms); fd_set fdset; FD_ZERO(&fdset); FD_SET(hSocket, &fdset); int nRet = select(hSocket + 1, &fdset, nullptr, nullptr, &tval); #endif if (nRet == SOCKET_ERROR) { return IntrRecvError::NetworkError; } } else { return IntrRecvError::NetworkError; } } if (interruptSocks5Recv) return IntrRecvError::Interrupted; curTime = GetTimeMillis(); } return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout; } /** Credentials for proxy authentication */ struct ProxyCredentials { std::string username; std::string password; }; /** Convert SOCKS5 reply to an error message */ static std::string Socks5ErrorString(uint8_t err) { switch(err) { case SOCKS5Reply::GENFAILURE: return "general failure"; case SOCKS5Reply::NOTALLOWED: return "connection not allowed"; case SOCKS5Reply::NETUNREACHABLE: return "network unreachable"; case SOCKS5Reply::HOSTUNREACHABLE: return "host unreachable"; case SOCKS5Reply::CONNREFUSED: return "connection refused"; case SOCKS5Reply::TTLEXPIRED: return "TTL expired"; case SOCKS5Reply::CMDUNSUPPORTED: return "protocol error"; case SOCKS5Reply::ATYPEUNSUPPORTED: return "address type not supported"; default: return "unknown"; } } /** * Connect to a specified destination service through an already connected * SOCKS5 proxy. * * @param strDest The destination fully-qualified domain name. * @param port The destination port. * @param auth The credentials with which to authenticate with the specified * SOCKS5 proxy. * @param hSocket The SOCKS5 proxy socket. * * @returns Whether or not the operation succeeded. * * @note The specified SOCKS5 proxy socket must already be connected to the * SOCKS5 proxy. * * @see <a href="https://www.ietf.org/rfc/rfc1928.txt">RFC1928: SOCKS Protocol * Version 5</a> */ static bool Socks5(const std::string& strDest, int port, const ProxyCredentials *auth, const SOCKET& hSocket) { IntrRecvError recvr; LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest); if (strDest.size() > 255) { return error("Hostname too long"); } // Construct the version identifier/method selection message std::vector<uint8_t> vSocks5Init; vSocks5Init.push_back(SOCKSVersion::SOCKS5); // We want the SOCK5 protocol if (auth) { vSocks5Init.push_back(0x02); // 2 method identifiers follow... vSocks5Init.push_back(SOCKS5Method::NOAUTH); vSocks5Init.push_back(SOCKS5Method::USER_PASS); } else { vSocks5Init.push_back(0x01); // 1 method identifier follows... vSocks5Init.push_back(SOCKS5Method::NOAUTH); } ssize_t ret = send(hSocket, (const char*)vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL); if (ret != (ssize_t)vSocks5Init.size()) { return error("Error sending to proxy"); } uint8_t pchRet1[2]; if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) { LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port); return false; } if (pchRet1[0] != SOCKSVersion::SOCKS5) { return error("Proxy failed to initialize"); } if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) { // Perform username/password authentication (as described in RFC1929) std::vector<uint8_t> vAuth; vAuth.push_back(0x01); // Current (and only) version of user/pass subnegotiation if (auth->username.size() > 255 || auth->password.size() > 255) return error("Proxy username or password too long"); vAuth.push_back(auth->username.size()); vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end()); vAuth.push_back(auth->password.size()); vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end()); ret = send(hSocket, (const char*)vAuth.data(), vAuth.size(), MSG_NOSIGNAL); if (ret != (ssize_t)vAuth.size()) { return error("Error sending authentication to proxy"); } LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password); uint8_t pchRetA[2]; if ((recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) { return error("Error reading proxy authentication response"); } if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) { return error("Proxy authentication unsuccessful"); } } else if (pchRet1[1] == SOCKS5Method::NOAUTH) { // Perform no authentication } else { return error("Proxy requested wrong authentication method %02x", pchRet1[1]); } std::vector<uint8_t> vSocks5; vSocks5.push_back(SOCKSVersion::SOCKS5); // VER protocol version vSocks5.push_back(SOCKS5Command::CONNECT); // CMD CONNECT vSocks5.push_back(0x00); // RSV Reserved must be 0 vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // ATYP DOMAINNAME vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end()); vSocks5.push_back((port >> 8) & 0xFF); vSocks5.push_back((port >> 0) & 0xFF); ret = send(hSocket, (const char*)vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL); if (ret != (ssize_t)vSocks5.size()) { return error("Error sending to proxy"); } uint8_t pchRet2[4]; if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) { if (recvr == IntrRecvError::Timeout) { /* If a timeout happens here, this effectively means we timed out while connecting * to the remote node. This is very common for Tor, so do not print an * error message. */ return false; } else { return error("Error while reading proxy response"); } } if (pchRet2[0] != SOCKSVersion::SOCKS5) { return error("Proxy failed to accept request"); } if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) { // Failures to connect to a peer that are not proxy errors LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1])); return false; } if (pchRet2[2] != 0x00) { // Reserved field must be 0 return error("Error: malformed proxy response"); } uint8_t pchRet3[256]; switch (pchRet2[3]) { case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break; case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break; case SOCKS5Atyp::DOMAINNAME: { recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket); if (recvr != IntrRecvError::OK) { return error("Error reading from proxy"); } int nRecv = pchRet3[0]; recvr = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket); break; } default: return error("Error: malformed proxy response"); } if (recvr != IntrRecvError::OK) { return error("Error reading from proxy"); } if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) { return error("Error reading from proxy"); } LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest); return true; } /** * Try to create a socket file descriptor with specific properties in the * communications domain (address family) of the specified service. * * For details on the desired properties, see the inline comments in the source * code. */ SOCKET CreateSocket(const CService &addrConnect) { // Create a sockaddr from the specified service. struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { LogPrintf("Cannot create socket for %s: unsupported network\n", addrConnect.ToString()); return INVALID_SOCKET; } // Create a TCP socket in the address family of the specified service. SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hSocket == INVALID_SOCKET) return INVALID_SOCKET; // Ensure that waiting for I/O on this socket won't result in undefined // behavior. if (!IsSelectableSocket(hSocket)) { CloseSocket(hSocket); LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n"); return INVALID_SOCKET; } #ifdef SO_NOSIGPIPE int set = 1; // Set the no-sigpipe option on the socket for BSD systems, other UNIXes // should use the MSG_NOSIGNAL flag for every send. setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int)); #endif // Set the no-delay option (disable Nagle's algorithm) on the TCP socket. SetSocketNoDelay(hSocket); // Set the non-blocking option on the socket. if (!SetSocketNonBlocking(hSocket, true)) { CloseSocket(hSocket); LogPrintf("CreateSocket: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError())); } return hSocket; } template<typename... Args> static void LogConnectFailure(bool manual_connection, const char* fmt, const Args&... args) { std::string error_message = tfm::format(fmt, args...); if (manual_connection) { LogPrintf("%s\n", error_message); } else { LogPrint(BCLog::NET, "%s\n", error_message); } } /** * Try to connect to the specified service on the specified socket. * * @param addrConnect The service to which to connect. * @param hSocket The socket on which to connect. * @param nTimeout Wait this many milliseconds for the connection to be * established. * @param manual_connection Whether or not the connection was manually requested * (e.g. through the addnode RPC) * * @returns Whether or not a connection was successfully made. */ bool ConnectSocketDirectly(const CService &addrConnect, const SOCKET& hSocket, int nTimeout, bool manual_connection) { // Create a sockaddr from the specified service. struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (hSocket == INVALID_SOCKET) { LogPrintf("Cannot connect to %s: invalid socket\n", addrConnect.ToString()); return false; } if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString()); return false; } // Connect to the addrConnect service on the hSocket socket. if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); // WSAEINVAL is here because some legacy version of winsock uses it if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) { // Connection didn't actually fail, but is being established // asynchronously. Thus, use async I/O api (select/poll) // synchronously to check for successful connection with a timeout. #ifdef USE_POLL struct pollfd pollfd = {}; pollfd.fd = hSocket; pollfd.events = POLLIN | POLLOUT; int nRet = poll(&pollfd, 1, nTimeout); #else struct timeval timeout = MillisToTimeval(nTimeout); fd_set fdset; FD_ZERO(&fdset); FD_SET(hSocket, &fdset); int nRet = select(hSocket + 1, nullptr, &fdset, nullptr, &timeout); #endif // Upon successful completion, both select and poll return the total // number of file descriptors that have been selected. A value of 0 // indicates that the call timed out and no file descriptors have // been selected. if (nRet == 0) { LogPrint(BCLog::NET, "connection to %s timeout\n", addrConnect.ToString()); return false; } if (nRet == SOCKET_ERROR) { LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError())); return false; } // Even if the select/poll was successful, the connect might not // have been successful. The reason for this failure is hidden away // in the SO_ERROR for the socket in modern systems. We read it into // nRet here. socklen_t nRetSize = sizeof(nRet); if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (sockopt_arg_type)&nRet, &nRetSize) == SOCKET_ERROR) { LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError())); return false; } if (nRet != 0) { LogConnectFailure(manual_connection, "connect() to %s failed after select(): %s", addrConnect.ToString(), NetworkErrorString(nRet)); return false; } } #ifdef WIN32 else if (WSAGetLastError() != WSAEISCONN) #else else #endif { LogConnectFailure(manual_connection, "connect() to %s failed: %s", addrConnect.ToString(), NetworkErrorString(WSAGetLastError())); return false; } } return true; } bool SetProxy(enum Network net, const proxyType &addrProxy) { assert(net >= 0 && net < NET_MAX); if (!addrProxy.IsValid()) return false; LOCK(cs_proxyInfos); proxyInfo[net] = addrProxy; return true; } bool GetProxy(enum Network net, proxyType &proxyInfoOut) { assert(net >= 0 && net < NET_MAX); LOCK(cs_proxyInfos); if (!proxyInfo[net].IsValid()) return false; proxyInfoOut = proxyInfo[net]; return true; } /** * Set the name proxy to use for all connections to nodes specified by a * hostname. After setting this proxy, connecting to a node specified by a * hostname won't result in a local lookup of said hostname, rather, connect to * the node by asking the name proxy for a proxy connection to the hostname, * effectively delegating the hostname lookup to the specified proxy. * * This delegation increases privacy for those who set the name proxy as they no * longer leak their external hostname queries to their DNS servers. * * @returns Whether or not the operation succeeded. * * @note SOCKS5's support for UDP-over-SOCKS5 has been considered, but no SOCK5 * server in common use (most notably Tor) actually implements UDP * support, and a DNS resolver is beyond the scope of this project. */ bool SetNameProxy(const proxyType &addrProxy) { if (!addrProxy.IsValid()) return false; LOCK(cs_proxyInfos); nameProxy = addrProxy; return true; } bool GetNameProxy(proxyType &nameProxyOut) { LOCK(cs_proxyInfos); if(!nameProxy.IsValid()) return false; nameProxyOut = nameProxy; return true; } bool HaveNameProxy() { LOCK(cs_proxyInfos); return nameProxy.IsValid(); } bool IsProxy(const CNetAddr &addr) { LOCK(cs_proxyInfos); for (int i = 0; i < NET_MAX; i++) { if (addr == static_cast<CNetAddr>(proxyInfo[i].proxy)) return true; } return false; } /** * Connect to a specified destination service through a SOCKS5 proxy by first * connecting to the SOCKS5 proxy. * * @param proxy The SOCKS5 proxy. * @param strDest The destination service to which to connect. * @param port The destination port. * @param hSocket The socket on which to connect to the SOCKS5 proxy. * @param nTimeout Wait this many milliseconds for the connection to the SOCKS5 * proxy to be established. * @param[out] outProxyConnectionFailed Whether or not the connection to the * SOCKS5 proxy failed. * * @returns Whether or not the operation succeeded. */ bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, const SOCKET& hSocket, int nTimeout, bool& outProxyConnectionFailed) { // first connect to proxy server if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout, true)) { outProxyConnectionFailed = true; return false; } // do socks negotiation if (proxy.randomize_credentials) { ProxyCredentials random_auth; static std::atomic_int counter(0); random_auth.username = random_auth.password = strprintf("%i", counter++); if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket)) { return false; } } else { if (!Socks5(strDest, (unsigned short)port, 0, hSocket)) { return false; } } return true; } /** * Parse and resolve a specified subnet string into the appropriate internal * representation. * * @param strSubnet A string representation of a subnet of the form `network * address [ "/", ( CIDR-style suffix | netmask ) ]`(e.g. * `2001:db8::/32`, `192.0.2.0/255.255.255.0`, or `8.8.8.8`). * @param ret The resulting internal representation of a subnet. * * @returns Whether the operation succeeded or not. */ bool LookupSubNet(const std::string& strSubnet, CSubNet& ret) { if (!ValidAsCString(strSubnet)) { return false; } size_t slash = strSubnet.find_last_of('/'); std::vector<CNetAddr> vIP; std::string strAddress = strSubnet.substr(0, slash); // TODO: Use LookupHost(const std::string&, CNetAddr&, bool) instead to just get // one CNetAddr. if (LookupHost(strAddress, vIP, 1, false)) { CNetAddr network = vIP[0]; if (slash != strSubnet.npos) { std::string strNetmask = strSubnet.substr(slash + 1); int32_t n; if (ParseInt32(strNetmask, &n)) { // If valid number, assume CIDR variable-length subnet masking ret = CSubNet(network, n); return ret.IsValid(); } else // If not a valid number, try full netmask syntax { // Never allow lookup for netmask if (LookupHost(strNetmask, vIP, 1, false)) { ret = CSubNet(network, vIP[0]); return ret.IsValid(); } } } else { ret = CSubNet(network); return ret.IsValid(); } } return false; } #ifdef WIN32 std::string NetworkErrorString(int err) { wchar_t buf[256]; buf[0] = 0; if(FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, ARRAYSIZE(buf), nullptr)) { return strprintf("%s (%d)", std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().to_bytes(buf), err); } else { return strprintf("Unknown error (%d)", err); } } #else std::string NetworkErrorString(int err) { char buf[256]; buf[0] = 0; /* Too bad there are two incompatible implementations of the * thread-safe strerror. */ const char *s; #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */ s = strerror_r(err, buf, sizeof(buf)); #else /* POSIX variant always returns message in buffer */ s = buf; if (strerror_r(err, buf, sizeof(buf))) buf[0] = 0; #endif return strprintf("%s (%d)", s, err); } #endif bool CloseSocket(SOCKET& hSocket) { if (hSocket == INVALID_SOCKET) return false; #ifdef WIN32 int ret = closesocket(hSocket); #else int ret = close(hSocket); #endif if (ret) { LogPrintf("Socket close failed: %d. Error: %s\n", hSocket, NetworkErrorString(WSAGetLastError())); } hSocket = INVALID_SOCKET; return ret != SOCKET_ERROR; } bool SetSocketNonBlocking(const SOCKET& hSocket, bool fNonBlocking) { if (fNonBlocking) { #ifdef WIN32 u_long nOne = 1; if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) { #else int fFlags = fcntl(hSocket, F_GETFL, 0); if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) { #endif return false; } } else { #ifdef WIN32 u_long nZero = 0; if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) { #else int fFlags = fcntl(hSocket, F_GETFL, 0); if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) { #endif return false; } } return true; } bool SetSocketNoDelay(const SOCKET& hSocket) { int set = 1; int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int)); return rc == 0; } void InterruptSocks5(bool interrupt) { interruptSocks5Recv = interrupt; }
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/lightsail/model/GetLoadBalancerMetricDataResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::Lightsail::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; GetLoadBalancerMetricDataResult::GetLoadBalancerMetricDataResult() : m_metricName(LoadBalancerMetricName::NOT_SET) { } GetLoadBalancerMetricDataResult::GetLoadBalancerMetricDataResult(const Aws::AmazonWebServiceResult<JsonValue>& result) : m_metricName(LoadBalancerMetricName::NOT_SET) { *this = result; } GetLoadBalancerMetricDataResult& GetLoadBalancerMetricDataResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("metricName")) { m_metricName = LoadBalancerMetricNameMapper::GetLoadBalancerMetricNameForName(jsonValue.GetString("metricName")); } if(jsonValue.ValueExists("metricData")) { Array<JsonView> metricDataJsonList = jsonValue.GetArray("metricData"); for(unsigned metricDataIndex = 0; metricDataIndex < metricDataJsonList.GetLength(); ++metricDataIndex) { m_metricData.push_back(metricDataJsonList[metricDataIndex].AsObject()); } } return *this; }
/* * Copyright 2017-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <AACE/Engine/AASB/AASBEngineImpl.h> #include <AACE/Engine/Core/EngineMacros.h> namespace aace { namespace engine { namespace aasb { // String to identify log entries originating from this file. static const std::string TAG("aace.aasb.AASBEngineImpl"); AASBEngineImpl::AASBEngineImpl(std::shared_ptr<aace::aasb::AASB> aasbPlatformInterface) : m_aasbPlatformInterface(aasbPlatformInterface) { } std::shared_ptr<AASBEngineImpl> AASBEngineImpl::create( std::shared_ptr<aace::aasb::AASB> aasbPlatformInterface, std::shared_ptr<aace::engine::messageBroker::MessageBrokerInterface> messageBroker, std::shared_ptr<aace::engine::messageBroker::StreamManagerInterface> streamManager) { std::shared_ptr<AASBEngineImpl> aasbEngineImpl = nullptr; try { ThrowIfNull(aasbPlatformInterface, "invalidPlatformInterface"); aasbEngineImpl = std::shared_ptr<AASBEngineImpl>(new AASBEngineImpl(aasbPlatformInterface)); ThrowIfNull(messageBroker, "invalidMessageBrokerInterface"); ThrowIfNull(streamManager, "invalidStreamManagerInterface"); ThrowIfNot(aasbEngineImpl->initialize(messageBroker, streamManager), "initializeFailed"); // set the engine interface aasbPlatformInterface->setEngineInterface(aasbEngineImpl); return aasbEngineImpl; } catch (std::exception& ex) { AACE_ERROR(LX(TAG).d("reason", ex.what())); return nullptr; } } bool AASBEngineImpl::initialize( std::shared_ptr<aace::engine::messageBroker::MessageBrokerInterface> messageBroker, std::shared_ptr<aace::engine::messageBroker::StreamManagerInterface> streamManager) { try { m_messageBroker = messageBroker; m_streamManager = streamManager; // subscribe to all outgoing messages from the message broker, and route them // through the AASB platform interface... std::weak_ptr<AASBEngineImpl> wp = shared_from_this(); messageBroker->subscribe( "*", [wp](const aace::engine::messageBroker::Message& message) { if (auto sp = wp.lock()) { if (sp->m_aasbPlatformInterface != nullptr) { sp->m_aasbPlatformInterface->messageReceived(message.str()); } } else { AACE_ERROR(LX(TAG, "initialize").d("reason", "invalidWeakPtrReference")); } }, aace::engine::messageBroker::Message::Direction::OUTGOING); return true; } catch (std::exception& ex) { AACE_ERROR(LX(TAG).d("reason", ex.what())); return false; } } // // aace::aasb::AASBEngineInterface // void AASBEngineImpl::onPublish(const std::string& message) { try { auto m_messageBroker_lock = m_messageBroker.lock(); ThrowIfNull(m_messageBroker_lock, "invalidMessageBrokerReference"); m_messageBroker_lock->publish(message, aace::engine::messageBroker::Message::Direction::INCOMING).send(); } catch (std::exception& ex) { AACE_ERROR(LX(TAG).d("reason", ex.what())); } } std::shared_ptr<aace::aasb::AASBStream> AASBEngineImpl::onOpenStream( const std::string& streamId, aace::aasb::AASBStream::Mode mode) { try { auto m_streamManager_lock = m_streamManager.lock(); ThrowIfNull(m_streamManager_lock, "invalidStreamManagerReference"); return m_streamManager_lock->requestStreamHandler(streamId, mode); } catch (std::exception& ex) { AACE_ERROR(LX(TAG).d("reason", ex.what())); return nullptr; } } } // namespace aasb } // namespace engine } // namespace aace
// clazy:skip #include "proofcore/errornotifier.h" #include "proofcore/memorystoragenotificationhandler.h" #include "gtest/proof/test_global.h" using namespace Proof; TEST(MemoryStorageNotificationHandlerTest, registerUnregister) { MemoryStorageNotificationHandler *handler = ErrorNotifier::instance()->handler<MemoryStorageNotificationHandler>(); ASSERT_TRUE(handler); EXPECT_TRUE(handler->messages().isEmpty()); ErrorNotifier::instance()->unregisterHandler<MemoryStorageNotificationHandler>(); handler = ErrorNotifier::instance()->handler<MemoryStorageNotificationHandler>(); EXPECT_FALSE(handler); MemoryStorageNotificationHandler *newHandler = new MemoryStorageNotificationHandler("testsHandler"); ErrorNotifier::instance()->registerHandler(newHandler); handler = ErrorNotifier::instance()->handler<MemoryStorageNotificationHandler>(); ASSERT_TRUE(handler); EXPECT_EQ(newHandler, handler); EXPECT_EQ("testsHandler", handler->appId()); EXPECT_TRUE(handler->messages().isEmpty()); } TEST(MemoryStorageNotificationHandlerTest, notify) { MemoryStorageNotificationHandler *handler = ErrorNotifier::instance()->handler<MemoryStorageNotificationHandler>(); ASSERT_TRUE(handler); ASSERT_TRUE(handler->messages().isEmpty()); QDateTime timestamp = QDateTime::currentDateTime(); ErrorNotifier::instance()->notify("error message"); { ASSERT_EQ(1, handler->messages().size()); auto all = handler->messages(); auto last = handler->lastMessage(); EXPECT_NEAR(last.first.toSecsSinceEpoch(), timestamp.toSecsSinceEpoch(), 10); EXPECT_EQ("error message", last.second); EXPECT_EQ(last.first, all.firstKey()); EXPECT_EQ(last.second, all.first()); } QThread::msleep(100); timestamp = QDateTime::currentDateTime(); ErrorNotifier::instance()->notify("error message 2"); { ASSERT_EQ(2, handler->messages().size()); auto all = handler->messages(); auto last = handler->lastMessage(); EXPECT_NEAR(last.first.toSecsSinceEpoch(), timestamp.toSecsSinceEpoch(), 10); EXPECT_EQ("error message 2", last.second); EXPECT_EQ(last.first, all.lastKey()); EXPECT_EQ(last.second, all.last()); } }
#include "common/Timer.h" #include "common/common.h" #include "core/Loc.h" #include "core/TypeConstraint.h" #include "core/errors/infer.h" #include "core/lsp/QueryResponse.h" #include "infer/SigSuggestion.h" #include "infer/environment.h" #include "infer/infer.h" using namespace std; namespace sorbet::infer { unique_ptr<cfg::CFG> Inference::run(core::Context ctx, unique_ptr<cfg::CFG> cfg) { Timer timeit(ctx.state.tracer(), "Inference::run", {{"func", (string)cfg->symbol.data(ctx)->toStringFullName(ctx)}}); ENFORCE(cfg->symbol == ctx.owner); auto methodLoc = cfg->symbol.data(ctx)->loc(); prodCounterInc("types.input.methods.typechecked"); int typedSendCount = 0; int totalSendCount = 0; const int startErrorCount = ctx.state.totalErrors(); auto guessTypes = true; unique_ptr<core::TypeConstraint> _constr; core::TypeConstraint *constr = &core::TypeConstraint::EmptyFrozenConstraint; if (cfg->symbol.data(ctx)->isGenericMethod()) { _constr = make_unique<core::TypeConstraint>(); constr = _constr.get(); for (core::SymbolRef typeArgument : cfg->symbol.data(ctx)->typeArguments()) { constr->rememberIsSubtype(ctx, typeArgument.data(ctx)->resultType, core::make_type<core::SelfTypeParam>(typeArgument)); } if (!constr->solve(ctx)) { Exception::raise("should never happen"); } guessTypes = false; } core::TypePtr methodReturnType = cfg->symbol.data(ctx)->resultType; auto missingReturnType = methodReturnType == nullptr; if (cfg->symbol.data(ctx)->name.data(ctx)->kind != core::NameKind::UTF8 || cfg->symbol.data(ctx)->name == core::Names::staticInit() || !cfg->symbol.data(ctx)->loc().exists()) { guessTypes = false; } if (missingReturnType) { if (guessTypes) { ENFORCE(constr->isSolved() && constr->isEmpty()); _constr = make_unique<core::TypeConstraint>(); constr = _constr.get(); auto returnTypeVar = core::Symbols:: Sorbet_Private_Static_ReturnTypeInference_guessed_type_type_parameter_holder_tparam_contravariant(); InlinedVector<core::SymbolRef, 4> domainTemp; domainTemp.emplace_back(returnTypeVar); methodReturnType = returnTypeVar.data(ctx)->resultType; constr->defineDomain(ctx, domainTemp); } else { methodReturnType = core::Types::untyped(ctx, cfg->symbol); } } else { auto enclosingClass = cfg->symbol.data(ctx)->enclosingClass(ctx); methodReturnType = core::Types::instantiate( ctx, core::Types::resultTypeAsSeenFrom(ctx, cfg->symbol.data(ctx)->resultType, cfg->symbol.data(ctx)->owner, enclosingClass, enclosingClass.data(ctx)->selfTypeArgs(ctx)), *constr); methodReturnType = core::Types::replaceSelfType(ctx, methodReturnType, enclosingClass.data(ctx)->selfType(ctx)); } vector<Environment> outEnvironments; outEnvironments.reserve(cfg->maxBasicBlockId); for (int i = 0; i < cfg->maxBasicBlockId; i++) { outEnvironments.emplace_back(methodLoc); } for (int i = 0; i < cfg->basicBlocks.size(); i++) { outEnvironments[cfg->forwardsTopoSort[i]->id].bb = cfg->forwardsTopoSort[i]; } vector<bool> visited; visited.resize(cfg->maxBasicBlockId); KnowledgeFilter knowledgeFilter(ctx, cfg); for (auto it = cfg->forwardsTopoSort.rbegin(); it != cfg->forwardsTopoSort.rend(); ++it) { cfg::BasicBlock *bb = *it; if (bb == cfg->deadBlock()) { continue; } Environment &current = outEnvironments[bb->id]; current.vars.reserve(bb->args.size()); for (cfg::VariableUseSite &arg : bb->args) { current.vars[arg.variable].typeAndOrigins.type = nullptr; } if (bb->backEdges.size() == 1) { auto *parent = bb->backEdges[0]; bool isTrueBranch = parent->bexit.thenb == bb; if (!outEnvironments[parent->id].isDead) { Environment tempEnv(methodLoc); auto &envAsSeenFromBranch = Environment::withCond(ctx, outEnvironments[parent->id], tempEnv, isTrueBranch, current.vars); current.populateFrom(ctx, envAsSeenFromBranch); } else { current.isDead = true; } } else { current.isDead = (bb != cfg->entry()); for (cfg::BasicBlock *parent : bb->backEdges) { if (!visited[parent->id] || outEnvironments[parent->id].isDead) { continue; } bool isTrueBranch = parent->bexit.thenb == bb; Environment tempEnv(methodLoc); auto &envAsSeenFromBranch = Environment::withCond(ctx, outEnvironments[parent->id], tempEnv, isTrueBranch, current.vars); if (!envAsSeenFromBranch.isDead) { current.isDead = false; current.mergeWith(ctx, envAsSeenFromBranch, core::Loc(ctx.file, parent->bexit.loc), *cfg.get(), bb, knowledgeFilter); } } } current.computePins(ctx, outEnvironments, *cfg.get(), bb); for (auto &uninitialized : current.vars) { if (uninitialized.second.typeAndOrigins.type.get() == nullptr) { uninitialized.second.typeAndOrigins.type = core::Types::nilClass(); uninitialized.second.typeAndOrigins.origins.emplace_back(cfg->symbol.data(ctx)->loc()); } else { uninitialized.second.typeAndOrigins.type->sanityCheck(ctx); } } for (auto &blockArg : bb->args) { current.getAndFillTypeAndOrigin(ctx, blockArg); } visited[bb->id] = true; if (current.isDead) { bb->firstDeadInstructionIdx = 0; // this block is unreachable. if (!bb->exprs.empty()) { for (auto &expr : bb->exprs) { if (expr.value->isSynthetic) { continue; } if (cfg::isa_instruction<cfg::TAbsurd>(expr.value.get())) { continue; } if (auto e = ctx.beginError(expr.loc, core::errors::Infer::DeadBranchInferencer)) { e.setHeader("This code is unreachable"); } break; } } continue; } core::Loc madeBlockDead; int i = 0; for (cfg::Binding &bind : bb->exprs) { i++; if (!current.isDead) { current.ensureGoodAssignTarget(ctx, bind.bind.variable); bind.bind.type = current.processBinding(ctx, bind, bb->outerLoops, cfg->minLoops[bind.bind.variable], knowledgeFilter, *constr, methodReturnType); if (cfg::isa_instruction<cfg::Send>(bind.value.get())) { totalSendCount++; if (bind.bind.type && !bind.bind.type->isUntyped()) { typedSendCount++; } else if (bind.bind.type->hasUntyped()) { DEBUG_ONLY(histogramInc("untyped.sources", bind.bind.type->untypedBlame()._id);); if (auto e = ctx.beginError(bind.loc, core::errors::Infer::UntypedValue)) { e.setHeader("This code is untyped"); } } } ENFORCE(bind.bind.type); bind.bind.type->sanityCheck(ctx); if (bind.bind.type->isBottom()) { current.isDead = true; madeBlockDead = core::Loc(ctx.file, bind.loc); } if (current.isDead) { // this can also be result of evaluating an instruction, e.g. an always false hard_assert bb->firstDeadInstructionIdx = i; } } else if (current.isDead && !bind.value->isSynthetic) { if (auto e = ctx.beginError(bind.loc, core::errors::Infer::DeadBranchInferencer)) { e.setHeader("This code is unreachable"); e.addErrorLine(madeBlockDead, "This expression always raises or can never be computed"); } break; } } if (!current.isDead) { ENFORCE(bb->firstDeadInstructionIdx == -1); current.getAndFillTypeAndOrigin(ctx, bb->bexit.cond); current.ensureGoodCondition(ctx, bb->bexit.cond.variable); } else { ENFORCE(bb->firstDeadInstructionIdx != -1); } histogramInc("infer.environment.size", current.vars.size()); for (auto &pair : current.vars) { auto &k = pair.second.knowledge; histogramInc("infer.knowledge.truthy.yes.size", k.truthy->yesTypeTests.size()); histogramInc("infer.knowledge.truthy.no.size", k.truthy->noTypeTests.size()); histogramInc("infer.knowledge.falsy.yes.size", k.falsy->yesTypeTests.size()); histogramInc("infer.knowledge.falsy.no.size", k.falsy->noTypeTests.size()); } } if (startErrorCount == ctx.state.totalErrors()) { counterInc("infer.methods_typechecked.no_errors"); } if (missingReturnType && guessTypes) { if (auto e = ctx.state.beginError(cfg->symbol.data(ctx)->loc(), core::errors::Infer::UntypedMethod)) { e.setHeader("This function does not have a `{}`", "sig"); auto maybeAutocorrect = SigSuggestion::maybeSuggestSig(ctx, cfg, methodReturnType, *constr); if (maybeAutocorrect.has_value()) { e.addAutocorrect(move(maybeAutocorrect.value())); } } else if (ctx.state.lspQuery.matchesSuggestSig(cfg->symbol)) { // Force maybeSuggestSig to run just to respond to the query (discard the result) SigSuggestion::maybeSuggestSig(ctx, cfg, methodReturnType, *constr); } } prodCounterAdd("types.input.sends.typed", typedSendCount); prodCounterAdd("types.input.sends.total", totalSendCount); return cfg; } } // namespace sorbet::infer
/** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common/format_utils.h" #include <set> #include <string> #include "ops/tuple_get_item.h" #include "ops/depend.h" #include "ops/make_tuple.h" #include "ops/return.h" #include "ops/batch_norm.h" #include "ops/batch_to_space.h" #include "ops/bias_add.h" #include "ops/depth_to_space.h" #include "ops/fused_batch_norm.h" #include "ops/fusion/avg_pool_fusion.h" #include "ops/fusion/conv2d_fusion.h" #include "ops/fusion/conv2d_transpose_fusion.h" #include "ops/fusion/max_pool_fusion.h" #include "ops/fusion/prelu_fusion.h" #include "ops/fusion/topk_fusion.h" #include "ops/instance_norm.h" #include "ops/lrn.h" #include "ops/resize.h" #include "ops/roi_pooling.h" #include "ops/space_to_batch.h" #include "ops/space_to_batch_nd.h" #include "ops/space_to_depth.h" #include "common/anf_util.h" namespace mindspore { namespace dpico { namespace { const std::set<std::string> kAssignedFormatOpSet = { mindspore::ops::kNameAvgPoolFusion, mindspore::ops::kNameBatchNorm, mindspore::ops::kNameBatchToSpace, mindspore::ops::kNameBiasAdd, mindspore::ops::kNameConv2DFusion, mindspore::ops::kNameConv2dTransposeFusion, mindspore::ops::kNameDepthToSpace, mindspore::ops::kNameFusedBatchNorm, mindspore::ops::kNameInstanceNorm, mindspore::ops::kNameLRN, mindspore::ops::kNameMaxPoolFusion, mindspore::ops::kNamePReLUFusion, mindspore::ops::kNameResize, mindspore::ops::kNameROIPooling, mindspore::ops::kNameSpaceToBatch, mindspore::ops::kNameSpaceToBatchND, mindspore::ops::kNameSpaceToDepth, mindspore::ops::kNameTopKFusion}; } // namespace const std::set<std::string> &GetAssignedFormatOpSet() { return kAssignedFormatOpSet; } bool IsSpecialType(const api::CNodePtr &cnode) { return CheckPrimitiveType(cnode, api::MakeShared<ops::TupleGetItem>()) || CheckPrimitiveType(cnode, api::MakeShared<ops::Depend>()) || CheckPrimitiveType(cnode, api::MakeShared<ops::MakeTuple>()) || CheckPrimitiveType(cnode, api::MakeShared<ops::Return>()); } std::string FormatEnumToString(mindspore::Format format) { static std::vector<std::string> names = { "NCHW", "NHWC", "NHWC4", "HWKC", "HWCK", "KCHW", "CKHW", "KHWC", "CHWK", "HW", "HW4", "NC", "NC4", "NC4HW4", "NUM_OF_FORMAT", "NCDHW", "NWC", "NCW", }; if (format < mindspore::NCHW || format > mindspore::NCW) { return ""; } return names[format]; } } // namespace dpico } // namespace mindspore
#pragma once #include "Matrix.hpp" namespace Sirius { /////////////////////////////////////// /// @brief 2-dimensional matrix inverse template<typename T> constexpr Matrix<2, T> inverse(const Matrix<2, T>& mat); /////////////////////////////////////// /// @brief 3-dimensional matrix inverse template<typename T> constexpr Matrix<3, T> inverse(const Matrix<3, T>& mat); /////////////////////////////////////// /// @brief 4-dimensional matrix inverse template<typename T> constexpr Matrix<4, T> inverse(const Matrix<4, T>& mat); template<typename T> constexpr Matrix<2, T> transpose(const Matrix<2, T>& mat); template<typename T> constexpr Matrix<3, T> transpose(const Matrix<3, T>& mat); template<typename T> constexpr Matrix<4, T> transpose(const Matrix<4, T>& mat); } #include "functions.tpp"
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/updater/browser_updater_client_util.h" // TODO(crbug.com/1134631): Make updater branding files mergeable with browser // branding files. const char kUpdaterName[] = "ChromiumUpdater";
#include <iostream> #include <Eigen/Dense> using namespace Eigen; using namespace std; int main() { MatrixXd m = MatrixXd::Random(3,3); m = (m + MatrixXd::Constant(3,3,1.2)) * 50; cout << "m =" << endl << m << endl; VectorXd v(3); v << 1, 2, 3; cout << "m * v =" << endl << m * v << endl; }
// Copyright (c) 2015-2017 Josh Blum // SPDX-License-Identifier: BSL-1.0 #include <Pothos/Framework.hpp> #include <cstring> #include "MacHelper.hpp" /*********************************************************************** * |PothosDoc Simple MAC * * The Simple MAC block is an implementation of a media access control layer. * It acts as an interface between physical-layer datagrams and a layer of addressable packets. * Packets from the MAC to the PHY get a packet header to embed source, destination and checksum. * Packets from the PHY to the MAC have their header inspected and stripped from the payload. * * https://en.wikipedia.org/wiki/Media_access_control * * <h3>Error recovery</h3> * When the simple MAC detects a packet checksum error, it simply drops the packet. * The MAC block does not handle packet loss, error recovery, or resending of data. * However, the simple LLC block can be used with the simple MAC to implement reliability. * * <h2>Interfaces</h2> * The Simple MAC block has 4 ports that operate on packet streams: * <ul> * <li><b>macIn</b> - This port accepts a packet of user data * where the metadata has the "recipient" field set to the remote destination MAC.</li> * <li><b>phyOut</b> - This port produces a packet of user data with an additional header * containing source address, destination address, and checksum.</li> * <li><b>phyIn</b> - This port accepts a packet of physical-layer data, * and inspects the payload for the MAC-layer header. * Packets with checksum errors or incorrect destinations are dropped.</li> * <li><b>macOut</b> - This port produces a packet of user data * where the metadata has the "sender" field set to the remote destination MAC.</li> * </ul> * * |category /MAC * |keywords MAC PHY packet * |alias /blocks/simple_mac * * |param macId[MAC ID] A 16-bit address of the MAC interface. * This address is used as the sender ID for outgoing PHY packets, * and is used to check the recipient ID for incoming PHY packets. * |default 0 * * |factory /comms/simple_mac() * |setter setMacId(macId) **********************************************************************/ class SimpleMac : public Pothos::Block { public: SimpleMac(void): _id(0), _errorCount(0) { this->setupInput("phyIn"); this->setupInput("macIn"); this->setupOutput("phyOut"); this->setupOutput("macOut"); this->registerCall(this, POTHOS_FCN_TUPLE(SimpleMac, setMacId)); this->registerCall(this, POTHOS_FCN_TUPLE(SimpleMac, getMacId)); this->registerCall(this, POTHOS_FCN_TUPLE(SimpleMac, getErrorCount)); this->registerProbe("getErrorCount"); } static Block *make(void) { return new SimpleMac(); } void activate(void) { _phyIn = this->input("phyIn"); _macIn = this->input("macIn"); _phyOut = this->output("phyOut"); _macOut = this->output("macOut"); } void setMacId(uint16_t macId) { _id = macId; } uint16_t getMacId(void) const { return _id; } unsigned long long getErrorCount(void) const { return _errorCount; } Pothos::BufferChunk unpack(const Pothos::Packet &pkt, uint16_t &senderId, uint16_t &recipientId) { const auto byteBuf = pkt.payload.as<const uint8_t *>(); if (pkt.payload.length < 7) return Pothos::BufferChunk(); // Data byte format: CRC SENDER_MSB SENDER_LSB RECIPIENT_MSB RECIPIENT_LSB LENGTH_MSB LENGTH_LSB int headerSize = 0; uint8_t crc = byteBuf[headerSize]; headerSize += 1; senderId = (byteBuf[headerSize] << 8) + byteBuf[headerSize + 1]; headerSize += 2; recipientId = (byteBuf[headerSize] << 8) + byteBuf[headerSize + 1]; headerSize += 2; uint16_t packetLength = (byteBuf[headerSize] << 8) + byteBuf[headerSize + 1]; headerSize += 2; // checking for the unfinished packet if (packetLength > pkt.payload.length) return Pothos::BufferChunk(); if (recipientId != _id) return Pothos::BufferChunk(); //check crc auto newCrc = Crc8(byteBuf + 1, packetLength - 1); if (newCrc != crc) return Pothos::BufferChunk(); //return the payload auto payload = pkt.payload; payload.length = packetLength - headerSize; payload.address += headerSize; return payload; } void work(void) { //check phy input packets for crc and send to the mac out if (_phyIn->hasMessage()) { auto msg = _phyIn->popMessage(); auto pktIn = msg.extract<Pothos::Packet>(); Pothos::Packet pktOut = pktIn; uint16_t recipientId = 0, senderId = 0; pktOut.payload = this->unpack(pktIn, recipientId, senderId); if (pktOut.payload) { pktOut.metadata["recipient"] = Pothos::Object(recipientId); pktOut.metadata["sender"] = Pothos::Object(senderId); _macOut->postMessage(std::move(pktOut)); } else _errorCount++; } //mac input packets are protocol framed and sent to the phy out if (_macIn->hasMessage()) { auto msg = _macIn->popMessage(); const auto &pktIn = msg.extract<Pothos::Packet>(); const auto &data = pktIn.payload; auto recipientIdIter = pktIn.metadata.find("recipient"); if (recipientIdIter == pktIn.metadata.end()) { _errorCount++; return; } auto recipientId = recipientIdIter->second.convert<uint16_t>(); auto packetLength = data.length + 7; Pothos::Packet pktOut = pktIn; pktOut.payload = Pothos::BufferChunk(packetLength); pktOut.payload.dtype = pktIn.payload.dtype; auto byteBuf = pktOut.payload.as<uint8_t *>(); // Data byte format: CRC SENDER_MSB SENDER_LSB RECIPIENT_MSB RECIPIENT_LSB LENGTH_MSB LENGTH_LSB byteBuf[1] = _id >> 8; byteBuf[2] = _id & 0xFF; byteBuf[3] = recipientId >> 8; byteBuf[4] = recipientId & 0xFF; byteBuf[5] = packetLength >> 8; byteBuf[6] = packetLength & 0xFF; std::memcpy(byteBuf + 7, data.as<const uint8_t*>(), data.length); byteBuf[0] = Crc8(byteBuf + 1, packetLength - 1); _phyOut->postMessage(std::move(pktOut)); } } private: size_t _id; unsigned long long _errorCount; Pothos::OutputPort *_phyOut; Pothos::OutputPort *_macOut; Pothos::InputPort *_phyIn; Pothos::InputPort *_macIn; }; static Pothos::BlockRegistry registerSimpleMac( "/comms/simple_mac", &SimpleMac::make); static Pothos::BlockRegistry registerSimpleMacOldPath( "/blocks/simple_mac", &SimpleMac::make);
#include "mem.h" #include <vector> #include <iostream> #include <fstream> #include <assert.h> #include "util.h" using namespace vortex; RamMemDevice::RamMemDevice(const char *filename, uint32_t wordSize) : wordSize_(wordSize) { std::ifstream input(filename); if (!input) { std::cout << "Error reading file \"" << filename << "\" into RamMemDevice.\n"; std::abort(); } do { contents_.push_back(input.get()); } while (input); while (contents_.size() & (wordSize-1)) contents_.push_back(0x00); } RamMemDevice::RamMemDevice(uint64_t size, uint32_t wordSize) : contents_(size) , wordSize_(wordSize) {} void RamMemDevice::read(void *data, uint64_t addr, uint64_t size) { auto addr_end = addr + size; if ((addr & (wordSize_-1)) || (addr_end & (wordSize_-1)) || (addr_end <= contents_.size())) { std::cout << "lookup of 0x" << std::hex << (addr_end-1) << " failed.\n"; throw BadAddress(); } const uint8_t *s = contents_.data() + addr; for (uint8_t *d = (uint8_t*)data, *de = d + size; d != de;) { *d++ = *s++; } } void RamMemDevice::write(const void *data, uint64_t addr, uint64_t size) { auto addr_end = addr + size; if ((addr & (wordSize_-1)) || (addr_end & (wordSize_-1)) || (addr_end <= contents_.size())) { std::cout << "lookup of 0x" << std::hex << (addr_end-1) << " failed.\n"; throw BadAddress(); } const uint8_t *s = (const uint8_t*)data; for (uint8_t *d = contents_.data() + addr, *de = d + size; d != de;) { *d++ = *s++; } } /////////////////////////////////////////////////////////////////////////////// void RomMemDevice::write(const void* /*data*/, uint64_t /*addr*/, uint64_t /*size*/) { std::cout << "attempt to write to ROM.\n"; std::abort(); } /////////////////////////////////////////////////////////////////////////////// bool MemoryUnit::ADecoder::lookup(uint64_t a, uint32_t wordSize, mem_accessor_t* ma) { uint64_t e = a + (wordSize - 1); assert(e >= a); for (auto iter = entries_.rbegin(), iterE = entries_.rend(); iter != iterE; ++iter) { if (a >= iter->start && e <= iter->end) { ma->md = iter->md; ma->addr = a - iter->start; return true; } } return false; } void MemoryUnit::ADecoder::map(uint64_t a, uint64_t e, MemDevice &m) { assert(e >= a); entry_t entry{&m, a, e}; entries_.emplace_back(entry); } void MemoryUnit::ADecoder::read(void *data, uint64_t addr, uint64_t size) { mem_accessor_t ma; if (!this->lookup(addr, size, &ma)) { std::cout << "lookup of 0x" << std::hex << addr << " failed.\n"; throw BadAddress(); } ma.md->read(data, ma.addr, size); } void MemoryUnit::ADecoder::write(const void *data, uint64_t addr, uint64_t size) { mem_accessor_t ma; if (!this->lookup(addr, size, &ma)) { std::cout << "lookup of 0x" << std::hex << addr << " failed.\n"; throw BadAddress(); } ma.md->write(data, ma.addr, size); } /////////////////////////////////////////////////////////////////////////////// MemoryUnit::MemoryUnit(uint64_t pageSize, uint64_t addrBytes, bool disableVm) : pageSize_(pageSize) , addrBytes_(addrBytes) , disableVM_(disableVm) { if (!disableVm) { tlb_[0] = TLBEntry(0, 077); } } void MemoryUnit::attach(MemDevice &m, uint64_t start, uint64_t end) { decoder_.map(start, end, m); } MemoryUnit::TLBEntry MemoryUnit::tlbLookup(uint64_t vAddr, uint32_t flagMask) { auto iter = tlb_.find(vAddr / pageSize_); if (iter != tlb_.end()) { if (iter->second.flags & flagMask) return iter->second; else { throw PageFault(vAddr, false); } } else { throw PageFault(vAddr, true); } } void MemoryUnit::read(void *data, uint64_t addr, uint64_t size, bool sup) { uint64_t pAddr; if (disableVM_) { pAddr = addr; } else { uint32_t flagMask = sup ? 8 : 1; TLBEntry t = this->tlbLookup(addr, flagMask); pAddr = t.pfn * pageSize_ + addr % pageSize_; } return decoder_.read(data, pAddr, size); } void MemoryUnit::write(const void *data, uint64_t addr, uint64_t size, bool sup) { uint64_t pAddr; if (disableVM_) { pAddr = addr; } else { uint32_t flagMask = sup ? 16 : 2; TLBEntry t = tlbLookup(addr, flagMask); pAddr = t.pfn * pageSize_ + addr % pageSize_; } decoder_.write(data, pAddr, size); } void MemoryUnit::tlbAdd(uint64_t virt, uint64_t phys, uint32_t flags) { tlb_[virt / pageSize_] = TLBEntry(phys / pageSize_, flags); } void MemoryUnit::tlbRm(uint64_t va) { if (tlb_.find(va / pageSize_) != tlb_.end()) tlb_.erase(tlb_.find(va / pageSize_)); } /////////////////////////////////////////////////////////////////////////////// RAM::RAM(uint32_t page_size) : size_(0) , page_bits_(log2ceil(page_size)) , last_page_(nullptr) , last_page_index_(0) { assert(ispow2(page_size)); } RAM::~RAM() { this->clear(); } void RAM::clear() { for (auto& page : pages_) { delete[] page.second; } } uint64_t RAM::size() const { return uint64_t(pages_.size()) << page_bits_; } uint8_t *RAM::get(uint64_t address) const { uint32_t page_size = 1 << page_bits_; uint32_t page_offset = address & (page_size - 1); uint64_t page_index = address >> page_bits_; uint8_t* page; if (last_page_ && last_page_index_ == page_index) { page = last_page_; } else { auto it = pages_.find(page_index); if (it != pages_.end()) { page = it->second; } else { uint8_t *ptr = new uint8_t[page_size]; // set uninitialized data to "baadf00d" for (uint32_t i = 0; i < page_size; ++i) { ptr[i] = (0xbaadf00d >> ((i & 0x3) * 8)) & 0xff; } pages_.emplace(page_index, ptr); page = ptr; } last_page_ = page; last_page_index_ = page_index; } return page + page_offset; } void RAM::read(void *data, uint64_t addr, uint64_t size) { uint8_t* d = (uint8_t*)data; for (uint64_t i = 0; i < size; i++) { d[i] = *this->get(addr + i); } } void RAM::write(const void *data, uint64_t addr, uint64_t size) { const uint8_t* s = (const uint8_t*)data; for (uint64_t i = 0; i < size; i++) { *this->get(addr + i) = s[i]; } } void RAM::loadBinImage(const char* filename, uint64_t destination) { std::ifstream ifs(filename); if (!ifs) { std::cout << "error: " << filename << " not found" << std::endl; } ifs.seekg(0, ifs.end); size_t size = ifs.tellg(); std::vector<uint8_t> content(size); ifs.seekg(0, ifs.beg); ifs.read((char*)content.data(), size); this->clear(); this->write(content.data(), destination, size); } void RAM::loadHexImage(const char* filename) { auto hti = [&](char c)->uint32_t { if (c >= 'A' && c <= 'F') return c - 'A' + 10; if (c >= 'a' && c <= 'f') return c - 'a' + 10; return c - '0'; }; auto hToI = [&](const char *c, uint32_t size)->uint32_t { uint32_t value = 0; for (uint32_t i = 0; i < size; i++) { value += hti(c[i]) << ((size - i - 1) * 4); } return value; }; std::ifstream ifs(filename); if (!ifs) { std::cout << "error: " << filename << " not found" << std::endl; } ifs.seekg(0, ifs.end); size_t size = ifs.tellg(); std::vector<char> content(size); ifs.seekg(0, ifs.beg); ifs.read(content.data(), size); int offset = 0; char *line = content.data(); this->clear(); while (true) { if (line[0] == ':') { uint32_t byteCount = hToI(line + 1, 2); uint32_t nextAddr = hToI(line + 3, 4) + offset; uint32_t key = hToI(line + 7, 2); switch (key) { case 0: for (uint32_t i = 0; i < byteCount; i++) { uint32_t addr = nextAddr + i; uint32_t value = hToI(line + 9 + i * 2, 2); *this->get(addr) = value; } break; case 2: offset = hToI(line + 9, 4) << 4; break; case 4: offset = hToI(line + 9, 4) << 16; break; default: break; } } while (*line != '\n' && size != 0) { ++line; --size; } if (size <= 1) break; ++line; --size; } }
#include <gsl/gsl> #include <memory> template<typename T, size_t ROW, size_t COL> class Array2D { private: std::unique_ptr<T[]> storage; std::unique_ptr<T*[]> array; public: Array2D() : storage(std::make_unique<T[]>(ROW * COL)), array(std::make_unique<T*[]>(ROW)) { for (size_t i = 0; i < ROW; i++) array[i] = &storage[i * COL]; } Array2D(std::initializer_list<T> &&list) : Array2D() { // no existing like memcpy? int i = 0; for (auto t : list) storage[i++] = t; } Array2D(std::initializer_list<std::initializer_list<T>> &&list) : Array2D() { int i = 0; for (auto j : list) { for (auto k : j) storage[i++] = k; } } Array2D(const Array2D &other) : Array2D() { for (size_t i = 0; i < ROW * COL; i++) storage[i] = other.storage[i]; } Array2D(Array2D &&other) : Array2D() { storage = std::move(other.storage); array = std::move(other.array); } T* operator[](size_t row) { return array[row]; } size_t size() { return ROW * COL; } T& at(size_t row, size_t col) { return storage[row * col + col]; } T* data() { return storage.get(); } T* begin() { return data(); } T* end() { return &(storage[ROW * COL]); } // what different const T& with T&& ?? Array2D& operator=(const Array2D& other) { for (size_t i = 0; i < ROW * COL; i++) storage[i] = other.storage[i]; return *this; } // move assign Array2D& operator=(Array2D&& other) { storage = std::move(other.storage); array = std::move(other.array); return *this; } // friend??? friend void swap(Array2D &a, Array2D &b) { Array2D tmp = std::move(a); a = std::move(b); b = std::move(tmp); } void print() { for (uint32_t i = 0; i < ROW; i++) { for (uint32_t j = 0; j< COL; j++) printf("%d ", array[i][j]); } printf("\n"); } }; int main() { Array2D<int, 2, 2> arr = {1, 2, 3, 4}; printf("arr : %d %d %d %d\n", arr[0][0], arr[0][1], arr[1][0], arr[1][1]); Array2D<int, 2, 2> arr2 = {{1, 2}, {3, 4}}; printf("arr2 : "); arr2.print(); arr2[0][0] = 5; printf("arr2 : "); arr2.print(); printf("Assign arr2 to arr\n"); arr = arr2; printf("arr : "); arr.print(); Array2D<int, 2, 2> arr3 = {9,8,7,6}; printf("Swap arr3 and arr\n"); swap(arr, arr3); printf("arr : "); arr.print(); printf("arr3 : "); arr3.print(); }
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2016-2017 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <modules/animation/datastructures/keyframeobserver.h> namespace inviwo { namespace animation { void KeyframeObservable::notifKeyframeTimeChanged(Keyframe* key, Seconds oldTime) { forEachObserver([&](KeyframeObserver* o) { o->onKeyframeTimeChanged(key, oldTime); }); } } // namespace } // namespace
// Copyright (c) 2004 Daniel Wallin and Arvid Norberg // 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 <luabind/lua_include.hpp> #include <luabind/scope.hpp> #include <luabind/detail/debug.hpp> #include <luabind/detail/stack_utils.hpp> #include <cassert> namespace luabind { namespace detail { registration::registration() : m_next(0) { } registration::~registration() { delete m_next; } } // namespace detail scope::scope() : m_chain(0) { } scope::scope(std::unique_ptr<detail::registration> reg) : m_chain(reg.release()) { } scope::scope(scope const& other) : m_chain(other.m_chain) { const_cast<scope&>(other).m_chain = 0; } scope::~scope() { delete m_chain; } scope& scope::operator,(scope s) { if (!m_chain) { m_chain = s.m_chain; s.m_chain = 0; return *this; } for (detail::registration* c = m_chain;; c = c->m_next) { if (!c->m_next) { c->m_next = s.m_chain; s.m_chain = 0; break; } } return *this; } void scope::register_(lua_State* L) const { for (detail::registration* r = m_chain; r != 0; r = r->m_next) { LUABIND_CHECK_STACK(L); r->register_(L); } } } // namespace luabind namespace luabind { namespace { struct lua_pop_stack { lua_pop_stack(lua_State* L) : m_state(L) { } ~lua_pop_stack() { lua_pop(m_state, 1); } lua_State* m_state; }; } // namespace unnamed module_::module_(lua_State* L, char const* name = 0) : m_state(L) , m_name(name) { } void module_::operator[](scope s) { if (m_name) { lua_pushstring(m_state, m_name); lua_gettable(m_state, LUA_GLOBALSINDEX); if (!lua_istable(m_state, -1)) { lua_pop(m_state, 1); lua_newtable(m_state); lua_pushstring(m_state, m_name); lua_pushvalue(m_state, -2); lua_settable(m_state, LUA_GLOBALSINDEX); } } else { lua_pushvalue(m_state, LUA_GLOBALSINDEX); } lua_pop_stack guard(m_state); s.register_(m_state); } struct namespace_::registration_ : detail::registration { registration_(char const* name) : m_name(name) { } void register_(lua_State* L) const { LUABIND_CHECK_STACK(L); assert(lua_gettop(L) >= 1); lua_pushstring(L, m_name); lua_gettable(L, -2); detail::stack_pop p(L, 1); // pops the table on exit if (!lua_istable(L, -1)) { lua_pop(L, 1); lua_newtable(L); lua_pushstring(L, m_name); lua_pushvalue(L, -2); lua_settable(L, -4); } m_scope.register_(L); } char const* m_name; scope m_scope; }; namespace_::namespace_(char const* name) : scope(std::unique_ptr<detail::registration>( m_registration = new registration_(name))) { } namespace_& namespace_::operator[](scope s) { m_registration->m_scope.operator,(s); return *this; } } // namespace luabind
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <mesos/type_utils.hpp> #include <process/collect.hpp> #include <process/delay.hpp> #include <process/process.hpp> #include <process/reap.hpp> #include <stout/unreachable.hpp> #include <stout/os/killtree.hpp> #ifdef __linux__ #include "linux/systemd.hpp" #endif // __linux__ #include "mesos/resources.hpp" #include "slave/containerizer/mesos/launcher.hpp" using namespace process; using std::list; using std::map; using std::string; using std::vector; using mesos::slave::ContainerState; namespace mesos { namespace internal { namespace slave { Try<Launcher*> PosixLauncher::create(const Flags& flags) { return new PosixLauncher(); } Future<hashset<ContainerID>> PosixLauncher::recover( const list<ContainerState>& states) { foreach (const ContainerState& state, states) { const ContainerID& containerId = state.container_id(); pid_t pid = state.pid(); if (pids.containsValue(pid)) { // This should (almost) never occur. There is the possibility // that a new executor is launched with the same pid as one that // just exited (highly unlikely) and the slave dies after the // new executor is launched but before it hears about the // termination of the earlier executor (also unlikely). // Regardless, the launcher can't do anything sensible so this // is considered an error. return Failure("Detected duplicate pid " + stringify(pid) + " for container " + stringify(containerId)); } pids.put(containerId, pid); } return hashset<ContainerID>(); } Try<pid_t> PosixLauncher::fork( const ContainerID& containerId, const string& path, const vector<string>& argv, const Subprocess::IO& in, const Subprocess::IO& out, const Subprocess::IO& err, const Option<flags::FlagsBase>& flags, const Option<map<string, string>>& environment, const Option<int>& namespaces, vector<process::Subprocess::Hook> parentHooks) { if (namespaces.isSome() && namespaces.get() != 0) { return Error("Posix launcher does not support namespaces"); } if (pids.contains(containerId)) { return Error("Process has already been forked for container " + stringify(containerId)); } // If we are on systemd, then extend the life of the child. Any // grandchildren's lives will also be extended. #ifdef __linux__ if (systemd::enabled()) { parentHooks.emplace_back(Subprocess::Hook(&systemd::mesos::extendLifetime)); } #endif // __linux__ Try<Subprocess> child = subprocess( path, argv, in, out, err, SETSID, flags, environment, None(), parentHooks); if (child.isError()) { return Error("Failed to fork a child process: " + child.error()); } LOG(INFO) << "Forked child with pid '" << child.get().pid() << "' for container '" << containerId << "'"; // Store the pid (session id and process group id). pids.put(containerId, child.get().pid()); return child.get().pid(); } // Forward declaration. Future<Nothing> _destroy(const Future<Option<int>>& future); Future<Nothing> PosixLauncher::destroy(const ContainerID& containerId) { if (!pids.contains(containerId)) { return Failure("Unknown container " + containerId.value()); } pid_t pid = pids.get(containerId).get(); // Kill all processes in the session and process group. Try<list<os::ProcessTree>> trees = os::killtree(pid, SIGKILL, true, true); pids.erase(containerId); // The child process may not have been waited on yet so we'll delay // completing destroy until we're sure it has been reaped. return process::reap(pid) .then(lambda::bind(&_destroy, lambda::_1)); } Future<Nothing> _destroy(const Future<Option<int>>& future) { if (future.isReady()) { return Nothing(); } else { return Failure("Failed to kill all processes: " + (future.isFailed() ? future.failure() : "unknown error")); } } Try<Launcher*> WindowsLauncher::create(const Flags& flags) { return new WindowsLauncher(); } } // namespace slave { } // namespace internal { } // namespace mesos {
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017 The BeetleCoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "libzerocoin/Params.h" #include "chainparams.h" #include "random.h" #include "util.h" #include "utilstrencodings.h" #include <assert.h> #include <boost/assign/list_of.hpp> using namespace std; using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" /** * Main network */ //! Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress>& vSeedsOut, const SeedSpec6* data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7 * 24 * 60 * 60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } // What makes a good checkpoint block? // + Is surrounded by blocks with reasonable timestamps // (no blocks before with a timestamp after, none after with // timestamp before) // + Contains no strange transactions static Checkpoints::MapCheckpoints mapCheckpoints = boost::assign::map_list_of (0, uint256("0x00000c9d6ee5917dcd9e9d291f4b2283fce7d6b8525a653267bae3a1c5fbdd00")); static const Checkpoints::CCheckpointData data = { &mapCheckpoints, 1536981458, // * UNIX timestamp of last checkpoint block 0, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 2000 // * estimated number of transactions per day after checkpoint }; static Checkpoints::MapCheckpoints mapCheckpointsTestnet = boost::assign::map_list_of(0, uint256("0x001")); static const Checkpoints::CCheckpointData dataTestnet = { &mapCheckpointsTestnet, 1740710, 0, 250}; static Checkpoints::MapCheckpoints mapCheckpointsRegtest = boost::assign::map_list_of(0, uint256("0x001")); static const Checkpoints::CCheckpointData dataRegtest = { &mapCheckpointsRegtest, 1454124731, 0, 100}; libzerocoin::ZerocoinParams* CChainParams::Zerocoin_Params() const { assert(this); static CBigNum bnTrustedModulus(zerocoinModulus); static libzerocoin::ZerocoinParams ZCParams = libzerocoin::ZerocoinParams(bnTrustedModulus); return &ZCParams; } class CMainParams : public CChainParams { public: CMainParams() { networkID = CBaseChainParams::MAIN; strNetworkID = "main"; pchMessageStart[0] = 0x10; pchMessageStart[1] = 0x48; pchMessageStart[2] = 0x09; pchMessageStart[3] = 0x18; vAlertPubKey = ParseHex("048f93954327e5d350971d7ef82431ffae98147a91139a54da5af57cb3942368c5d4a39a141ba44326eea9b0fd4e81c4716126b9462407d88c6b21ea0ab5808ebf"); nDefaultPort = 3133; bnProofOfWorkLimit = ~uint256(0) >> 20; nSubsidyHalvingInterval = 2100000; nMaxReorganizationDepth = 100; nEnforceBlockUpgradeMajority = 750; nRejectBlockOutdatedMajority = 950; nToCheckBlockUpgradeMajority = 1000; nMinerThreads = 0; nTargetTimespan = 1 * 60; nTargetSpacingSlowLaunch = 1 * 60; nTargetSpacing = 1 * 60; nMaturity = 15; nMasternodeCountDrift = 20; nMaxMoneyOut = 500000000 * COIN; nLastPOWBlock = 200; nModifierUpdateBlock = 999999999; nZerocoinStartHeight = 1024000; nAccumulatorStartHeight = 1; nZerocoinStartTime = 1536981458; nBlockEnforceSerialRange = 1; nBlockRecalculateAccumulators = ~1; nBlockFirstFraudulent = ~1; nBlockLastGoodCheckpoint = ~1; const char* pszTimestamp = "Any foolish boy can stamp on a beetle, but all the professors in the world cannot make a beetle"; CMutableTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = 1 * COIN; txNew.vout[0].scriptPubKey = CScript() << ParseHex("040f54c5893d68f990bdba4c5b9bc8f9eae59bb6df5ecb1fde548446e2292a9b514915ba867b8a9edcdced258ba8d16c3cdaf274d8896a645088fd86e4d75112d9") << OP_CHECKSIG; genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1536981458; genesis.nBits = 0x1e0ffff0; genesis.nNonce = 1510561; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x00000c9d6ee5917dcd9e9d291f4b2283fce7d6b8525a653267bae3a1c5fbdd00")); assert(genesis.hashMerkleRoot == uint256("0x64a35990d03a0a06b73a4ec8524ec98f315f5a0ce6b0682743374789c5da6557")); vSeeds.push_back(CDNSSeedData("85.255.5.178", "85.255.5.178")); vSeeds.push_back(CDNSSeedData("80.211.194.181", "80.211.194.181")); vSeeds.push_back(CDNSSeedData("194.182.73.166", "194.182.73.166")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 75); // X base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 85); // b base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 127); // t base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x02)(0x2D)(0x25)(0x73).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x02)(0x21)(0x31)(0x2B).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x80)(0x00)(0x1d)(0xfc).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); fRequireRPCPassword = true; fMiningRequiresPeers = true; fAllowMinDifficultyBlocks = false; fDefaultConsistencyChecks = false; fRequireStandard = true; fMineBlocksOnDemand = false; fSkipProofOfWorkCheck = false; fTestnetToBeDeprecatedFieldRPC = false; fHeadersFirstSyncingActive = false; nPoolMaxTransactions = 3; strSporkKey = "04DE3E3D0380A7359563B990F7AF701320F44CEB0FBC325CD7EB06A6C228FE57D8448AD2365E7F36B31591B9B3BFCE6A5FE9A01773215604CB9DD512470AFBB9BB"; strObfuscationPoolDummyAddress = "XKCwyEbFpa9xTC1ontK3v2JzLns2Zc6UCJ"; nStartMasternodePayments = 1536981458; /** Zerocoin */ zerocoinModulus = "0xc95577b6dce0049b0a20c779af38079355abadde1a1d80c353f6cb697a7ae5a087bad39caa5798478551d0f9d91e6267716506f32412de1d19d17588765eb9502b85c6a18abdb05791cfd8b734e960281193705eeece210920cc922b3af3ceb178bf12c22eb565d5767fbf19545639be8953c2c38ffad41f3371e4aac750ac2d7bd614b3faabb453081d5d88fdbb803657a980bc93707e4b14233a2358c97763bf28f7c933206071477e8b371f229bc9ce7d6ef0ed7163aa5dfe13bc15f7816348b328fa2c1e69d5c88f7b94cee7829d56d1842d77d7bb8692e9fc7b7db059836500de8d57eb43c345feb58671503b932829112941367996b03871300f25efb5"; nMaxZerocoinSpendsPerTransaction = 7; // Assume about 20kb each nMinZerocoinMintFee = 1 * ZCENT; //high fee required for zerocoin mints nMintRequiredConfirmations = 20; //the maximum amount of confirmations until accumulated in 19 nRequiredAccumulation = 1; nDefaultSecurityLevel = 100; //full security level for accumulators nZerocoinHeaderVersion = 4; //Block headers must be this version once zerocoin is active nBudget_Fee_Confirmations = 6; // Number of confirmations for the finalization fee } const Checkpoints::CCheckpointData& Checkpoints() const { return data; } }; static CMainParams mainParams; /** * Testnet (v3) */ class CTestNetParams : public CMainParams { public: CTestNetParams() { networkID = CBaseChainParams::TESTNET; strNetworkID = "test"; pchMessageStart[0] = 0x43; pchMessageStart[1] = 0x76; pchMessageStart[2] = 0x65; pchMessageStart[3] = 0xba; vAlertPubKey = ParseHex("042292b1f401860eea99e1a8a103effbd7e1c013a59a1a3a0c91c9d1997a0bc6f338567278c11344802838c107055bf7c1641eaed61e879245c255a4f5be5746fc"); nDefaultPort = 51434; nEnforceBlockUpgradeMajority = 51; nRejectBlockOutdatedMajority = 75; nToCheckBlockUpgradeMajority = 100; nMinerThreads = 0; nTargetTimespan = 1 * 60; // BeetleCoin: 1 day nTargetSpacing = 1 * 60; // BeetleCoin: 1 minute nLastPOWBlock = 200; nMaturity = 15; nMasternodeCountDrift = 4; nModifierUpdateBlock = 51197; //approx Mon, 17 Apr 2017 04:00:00 GMT nMaxMoneyOut = 43199500 * COIN; nZerocoinStartHeight = 201576; nZerocoinStartTime = 1524711188; nBlockEnforceSerialRange = 1; //Enforce serial range starting this block nBlockRecalculateAccumulators = 9908000; //Trigger a recalculation of accumulators nBlockFirstFraudulent = 9891737; //First block that bad serials emerged nBlockLastGoodCheckpoint = 9891730; //Last valid accumulator checkpoint //! Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1515616140; genesis.nNonce = 79855; hashGenesisBlock = genesis.GetHash(); //assert(hashGenesisBlock == uint256("0x000007cff63ef602a51bf074e384b3516f0dd202f14d52f7c8c9b1af9423ab2e")); vFixedSeeds.clear(); vSeeds.clear(); // vSeeds.push_back(CDNSSeedData("45.76.61.28", "207.148.0.129")); // Single node address // vSeeds.push_back(CDNSSeedData("209.250.240.94", "45.77.239.30")); // Single node address // vSeeds.push_back(CDNSSeedData("45.77.176.204", "45.76.226.204")); // Single node address base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 139); // Testnet beetlecoin addresses start with 'x' or 'y' base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 19); // Testnet beetlecoin script addresses start with '8' or '9' base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 239); // Testnet private keys start with '9' or 'c' (Bitcoin defaults) // Testnet beetlecoin BIP32 pubkeys start with 'DRKV' base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x3a)(0x80)(0x61)(0xa0).convert_to_container<std::vector<unsigned char> >(); // Testnet beetlecoin BIP32 prvkeys start with 'DRKP' base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x3a)(0x80)(0x58)(0x37).convert_to_container<std::vector<unsigned char> >(); // Testnet beetlecoin BIP44 coin type is '1' (All coin's testnet default) base58Prefixes[EXT_COIN_TYPE] = boost::assign::list_of(0x80)(0x00)(0x00)(0x01).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test)); fRequireRPCPassword = true; fMiningRequiresPeers = true; fAllowMinDifficultyBlocks = true; fDefaultConsistencyChecks = false; fRequireStandard = false; fMineBlocksOnDemand = false; fTestnetToBeDeprecatedFieldRPC = true; nPoolMaxTransactions = 2; strSporkKey = "04188441e39d99aa69068ee07d26980f459b84465bbd765c6ee15d1aec5b76b5aebb01b24be184a1d3a12af61276549d96cc9499d909f8afc183132837d18d643d"; strObfuscationPoolDummyAddress = "xp87cG8UEQgzs1Bk67Yk884C7pnQfAeo7q"; nStartMasternodePayments = 1420837558; //Fri, 09 Jan 2015 21:05:58 GMT nBudget_Fee_Confirmations = 3; // Number of confirmations for the finalization fee. We have to make this very short // here because we only have a 8 block finalization window on testnet } const Checkpoints::CCheckpointData& Checkpoints() const { return dataTestnet; } }; static CTestNetParams testNetParams; /** * Regression test */ class CRegTestParams : public CTestNetParams { public: CRegTestParams() { networkID = CBaseChainParams::REGTEST; strNetworkID = "regtest"; strNetworkID = "regtest"; pchMessageStart[0] = 0x69; pchMessageStart[1] = 0xcf; pchMessageStart[2] = 0x7e; pchMessageStart[3] = 0xac; nSubsidyHalvingInterval = 150; nEnforceBlockUpgradeMajority = 750; nRejectBlockOutdatedMajority = 950; nToCheckBlockUpgradeMajority = 1000; nMinerThreads = 1; nTargetTimespan = 24 * 60 * 60; // BeetleCoin: 1 day nTargetSpacing = 1 * 60; // BeetleCoin: 1 minutes bnProofOfWorkLimit = ~uint256(0) >> 1; genesis.nTime = 1515524400; genesis.nBits = 0x1e0ffff0; genesis.nNonce = 732084; hashGenesisBlock = genesis.GetHash(); nDefaultPort = 51436; //assert(hashGenesisBlock == uint256("0x000008415bdca132b70cf161ecc548e5d0150fd6634a381ee2e99bb8bb77dbb3")); vFixedSeeds.clear(); //! Testnet mode doesn't have any fixed seeds. vSeeds.clear(); //! Testnet mode doesn't have any DNS seeds. fRequireRPCPassword = false; fMiningRequiresPeers = false; fAllowMinDifficultyBlocks = true; fDefaultConsistencyChecks = true; fRequireStandard = false; fMineBlocksOnDemand = true; fTestnetToBeDeprecatedFieldRPC = false; } const Checkpoints::CCheckpointData& Checkpoints() const { return dataRegtest; } }; static CRegTestParams regTestParams; /** * Unit test */ class CUnitTestParams : public CMainParams, public CModifiableParams { public: CUnitTestParams() { networkID = CBaseChainParams::UNITTEST; strNetworkID = "unittest"; nDefaultPort = 51478; vFixedSeeds.clear(); //! Unit test mode doesn't have any fixed seeds. vSeeds.clear(); //! Unit test mode doesn't have any DNS seeds. fRequireRPCPassword = false; fMiningRequiresPeers = false; fDefaultConsistencyChecks = true; fAllowMinDifficultyBlocks = false; fMineBlocksOnDemand = true; } const Checkpoints::CCheckpointData& Checkpoints() const { // UnitTest share the same checkpoints as MAIN return data; } //! Published setters to allow changing values in unit test cases virtual void setSubsidyHalvingInterval(int anSubsidyHalvingInterval) { nSubsidyHalvingInterval = anSubsidyHalvingInterval; } virtual void setEnforceBlockUpgradeMajority(int anEnforceBlockUpgradeMajority) { nEnforceBlockUpgradeMajority = anEnforceBlockUpgradeMajority; } virtual void setRejectBlockOutdatedMajority(int anRejectBlockOutdatedMajority) { nRejectBlockOutdatedMajority = anRejectBlockOutdatedMajority; } virtual void setToCheckBlockUpgradeMajority(int anToCheckBlockUpgradeMajority) { nToCheckBlockUpgradeMajority = anToCheckBlockUpgradeMajority; } virtual void setDefaultConsistencyChecks(bool afDefaultConsistencyChecks) { fDefaultConsistencyChecks = afDefaultConsistencyChecks; } virtual void setAllowMinDifficultyBlocks(bool afAllowMinDifficultyBlocks) { fAllowMinDifficultyBlocks = afAllowMinDifficultyBlocks; } virtual void setSkipProofOfWorkCheck(bool afSkipProofOfWorkCheck) { fSkipProofOfWorkCheck = afSkipProofOfWorkCheck; } }; static CChainParams* pCurrentParams = 0; const CChainParams& Params() { assert(pCurrentParams); return *pCurrentParams; } CChainParams& Params(CBaseChainParams::Network network) { switch (network) { case CBaseChainParams::MAIN: return mainParams; case CBaseChainParams::TESTNET: return testNetParams; case CBaseChainParams::REGTEST: return regTestParams; default: assert(false && "Unimplemented network"); return mainParams; } } void SelectParams(CBaseChainParams::Network network) { SelectBaseParams(network); pCurrentParams = &Params(network); } bool SelectParamsFromCommandLine() { CBaseChainParams::Network network = NetworkIdFromCommandLine(); if (network == CBaseChainParams::MAX_NETWORK_TYPES) return false; SelectParams(network); return true; }
// Fill out your copyright notice in the Description page of Project Settings. #include "MyDropPart.h"