hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
631cb35c55d0b3fe1cf8aa567a91933e241dab72
1,775
cc
C++
chrome/browser/ui/website_settings/mock_permission_bubble_view.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
chrome/browser/ui/website_settings/mock_permission_bubble_view.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/website_settings/mock_permission_bubble_view.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2015 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/ui/website_settings/mock_permission_bubble_view.h" #include "base/bind.h" #include "base/run_loop.h" #include "chrome/browser/ui/website_settings/mock_permission_bubble_factory.h" #include "chrome/browser/ui/website_settings/permission_bubble_manager.h" MockPermissionBubbleView::~MockPermissionBubbleView() { Hide(); } void MockPermissionBubbleView::Show( const std::vector<PermissionBubbleRequest*>& requests, const std::vector<bool>& accept_state) { factory_->ShowView(this); factory_->show_count_++; factory_->requests_count_ = manager_->requests_.size(); factory_->total_requests_count_ += manager_->requests_.size(); factory_->UpdateResponseType(); is_visible_ = true; if (browser_test_) base::MessageLoopForUI::current()->QuitWhenIdle(); } bool MockPermissionBubbleView::CanAcceptRequestUpdate() { return can_update_ui_; } void MockPermissionBubbleView::Hide() { if (is_visible_ && factory_) factory_->HideView(this); is_visible_ = false; } bool MockPermissionBubbleView::IsVisible() { return is_visible_; } void MockPermissionBubbleView::UpdateAnchorPosition() {} gfx::NativeWindow MockPermissionBubbleView::GetNativeWindow() { // This class should only be used when the UI is not necessary. NOTREACHED(); return nullptr; } MockPermissionBubbleView::MockPermissionBubbleView( MockPermissionBubbleFactory* factory, PermissionBubbleManager* manager, bool browser_test) : factory_(factory), manager_(manager), browser_test_(browser_test), can_update_ui_(true), is_visible_(false) {}
29.098361
78
0.760563
Wzzzx
6322f86fbb23198e86f7584e107ffe8c1f1ca165
807
cpp
C++
talent/talent.cpp
chenhongqiao/OI-Solutions
009a3c4b713b62658b835b52e0f61f882b5a6ffe
[ "MIT" ]
1
2020-12-15T20:25:21.000Z
2020-12-15T20:25:21.000Z
talent/talent.cpp
chenhongqiao/OI-Solutions
009a3c4b713b62658b835b52e0f61f882b5a6ffe
[ "MIT" ]
null
null
null
talent/talent.cpp
chenhongqiao/OI-Solutions
009a3c4b713b62658b835b52e0f61f882b5a6ffe
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct cow { long long w, t; }; cow c[255]; long long dp[1000005]; int main() { //freopen("talent.in", "r", stdin); //freopen("talent.out", "w", stdout); int n, wl; cin >> n >> wl; for (int i = 1; i <= n; i++) { long long w, t; cin >> w >> t; c[i] = {w, t * 1000}; } for (int i = 1; i <= 1000000; i++) { dp[i] = -10000000000; } for (int i = 1; i <= n; i++) { for (int j = 1000000; j >= c[i].w; j--) { dp[j] = max(dp[j], dp[j - c[i].w] + c[i].t); } } int ans = 0; for (int i = wl; i <= 1000000; i++) { if (dp[i] / i > ans) { ans = dp[i] / i; } } cout << ans << endl; return 0; }
19.214286
56
0.385378
chenhongqiao
63294f6ebd9958e2f4745105a11eaefede33bfc4
2,560
hpp
C++
Contrib-Intel/RSD-PSME-RMM/common/ipmi/include/ipmi/command/generic/reserve_sdr_repository.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
5
2019-11-11T07:57:26.000Z
2022-03-28T08:26:53.000Z
Contrib-Intel/RSD-PSME-RMM/common/ipmi/include/ipmi/command/generic/reserve_sdr_repository.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
3
2019-09-05T21:47:07.000Z
2019-09-17T18:10:45.000Z
Contrib-Intel/RSD-PSME-RMM/common/ipmi/include/ipmi/command/generic/reserve_sdr_repository.hpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
11
2019-07-20T00:16:32.000Z
2022-01-11T14:17:48.000Z
/*! * @brief Declaration of Reserve SDR Repository Request/Response. * * @copyright Copyright (c) 2017-2019 Intel Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file command/generic/reserve_sdr_repository.hpp */ #pragma once #include "ipmi/request.hpp" #include "ipmi/response.hpp" namespace ipmi { namespace command { namespace generic { namespace request { /*! * @brief Request message for Reserve SDR Repository command. */ class ReserveSdrRepository : public Request { public: /*! * @brief Default constructor. */ ReserveSdrRepository(); /*! Copy constructor. */ ReserveSdrRepository(const ReserveSdrRepository&) = default; /*! Assignment operator */ ReserveSdrRepository& operator=(const ReserveSdrRepository&) = default; /*! * @brief Default destructor. */ virtual ~ReserveSdrRepository(); const char* get_command_name() const override { return "ReserveSdrRepository"; } private: void pack(IpmiInterface::ByteBuffer&) const override { /* no request data */ } }; } namespace response { /*! * @brief Response message for Reserve SDR Repository command. */ class ReserveSdrRepository : public Response { public: /*! * @brief Default constructor. */ ReserveSdrRepository(); /*! Copy constructor. */ ReserveSdrRepository(const ReserveSdrRepository&) = default; /*! Assignment operator */ ReserveSdrRepository& operator=(const ReserveSdrRepository&) = default; /*! * @brief Default destructor. */ virtual ~ReserveSdrRepository(); const char* get_command_name() const override { return "ReserveSdrRepository"; } /*! * @brief Gets reservation id. * @return Reservation id. */ std::uint16_t get_reservation_id() const { return m_reservation_id; } private: static constexpr std::size_t RESPONSE_SIZE = 3; std::uint16_t m_reservation_id{}; void unpack(const IpmiInterface::ByteBuffer& data) override; }; } } } }
22.857143
86
0.687109
opencomputeproject
632ad3b0f5994347bc712345fbeeb4f50db41acc
726
cpp
C++
Courses/C++ Without Fear (3rd Ed.) Brian Overland/Chap_5/Ex_5/5.5.1.cpp
mccrudd3n/practise
26a65c0515c9bea7583bcb8f4c0022659b48dcf5
[ "Unlicense" ]
null
null
null
Courses/C++ Without Fear (3rd Ed.) Brian Overland/Chap_5/Ex_5/5.5.1.cpp
mccrudd3n/practise
26a65c0515c9bea7583bcb8f4c0022659b48dcf5
[ "Unlicense" ]
null
null
null
Courses/C++ Without Fear (3rd Ed.) Brian Overland/Chap_5/Ex_5/5.5.1.cpp
mccrudd3n/practise
26a65c0515c9bea7583bcb8f4c0022659b48dcf5
[ "Unlicense" ]
null
null
null
#include <iostream> using namespace std; void move_rings(int n, int src, int dest, int other); void move_a_ring(int src, int dest); int main() { int n; cout << "Enter number of rings" << endl; cin >> n; if (n >= 0) { cout << "Enter a number greater than 0" << endl; cin >> n; } move_rings(n, 1, 3, 2); return 0; } void move_rings(int n, int src, int dest, int other) { if (n==1) { move_a_ring(src, dest); } else { move_rings( n- 1, src, other, dest); move_a_ring(src,dest); move_rings(n -1, other, dest, src); } } void move_a_ring(int src, int dest) { cout << "Move from " << src << " to " << dest << endl; }
22
59
0.530303
mccrudd3n
632be5bbd31bceb5066acfd2ab4400a1b791341e
1,991
cpp
C++
frameworks/permission_standard/permissioncommunicationadapter/main/cpp/src/ams_adapter.cpp
openharmony-gitee-mirror/security_permission
dd482838bfe697dad1dd40531aa8fca2bd4d6883
[ "Apache-2.0" ]
null
null
null
frameworks/permission_standard/permissioncommunicationadapter/main/cpp/src/ams_adapter.cpp
openharmony-gitee-mirror/security_permission
dd482838bfe697dad1dd40531aa8fca2bd4d6883
[ "Apache-2.0" ]
null
null
null
frameworks/permission_standard/permissioncommunicationadapter/main/cpp/src/ams_adapter.cpp
openharmony-gitee-mirror/security_permission
dd482838bfe697dad1dd40531aa8fca2bd4d6883
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ams_adapter.h" #include "permission_log.h" #include "ipc_skeleton.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" namespace OHOS { namespace Security { namespace Permission { namespace { static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_PERMISSION, "AmsAdapter"}; } sptr<AAFwk::IAbilityManager> AmsAdapter::GetAbilityManager() { if (iAbilityManager_ == nullptr) { auto abilityObj = GetSystemAbility(Constant::ABILITY_MST_SERVICE_ID); if (abilityObj == nullptr) { PERMISSION_LOG_ERROR(LABEL, "failed to get ability manager service."); return nullptr; } iAbilityManager_ = iface_cast<AAFwk::IAbilityManager>(abilityObj); } return iAbilityManager_; } sptr<IRemoteObject> AmsAdapter::GetSystemAbility(const Constant::ServiceId systemAbilityId) { if (saMgr_ == nullptr) { std::lock_guard<std::mutex> lock(saMutex_); if (saMgr_ == nullptr) { saMgr_ = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (saMgr_ == nullptr) { PERMISSION_LOG_ERROR(LABEL, "fail to get Registry."); return nullptr; } } } return saMgr_->GetSystemAbility(systemAbilityId); } } // namespace Permission } // namespace Security } // namespace OHOS
32.639344
106
0.69563
openharmony-gitee-mirror
632dee063f996faac35d807afc63239a68a815dc
4,867
hpp
C++
src/gui/src/core/interfaces/impl/iota-wallet.hpp
MatthewDarnell/iota-simplewallet
aa3449bae3023e292ad47a9fa72213e279367b7a
[ "MIT" ]
1
2020-11-19T07:18:44.000Z
2020-11-19T07:18:44.000Z
src/gui/src/core/interfaces/impl/iota-wallet.hpp
MatthewDarnell/iota-simplewallet
aa3449bae3023e292ad47a9fa72213e279367b7a
[ "MIT" ]
null
null
null
src/gui/src/core/interfaces/impl/iota-wallet.hpp
MatthewDarnell/iota-simplewallet
aa3449bae3023e292ad47a9fa72213e279367b7a
[ "MIT" ]
null
null
null
// Copyright (c) 2018-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef IOTAWALLET_HPP #define IOTAWALLET_HPP #include <interfaces/wallet.h> #include <interfaces/handler.h> #include <QObject> #include <QJsonObject> #include <QDateTime> struct FreeCStringDeleter { void operator()(char *ptr) { free(ptr); } }; using c_string_unique_ptr = std::unique_ptr<char, FreeCStringDeleter>; namespace interfaces { struct UserAccount { int index { -1 }; QString username; QString balance; bool synced; QDateTime createdAt; static UserAccount FromJson(QJsonObject obj); }; class IotaWallet : public QObject, public Wallet { // Wallet interface Q_OBJECT public: explicit IotaWallet(UserAccount account, QObject *parent = nullptr); bool encryptWallet(const SecureString &wallet_passphrase) override; bool isCrypted() override; bool lock() override; bool unlock(const SecureString &wallet_passphrase) override; bool isLocked() override; bool changeWalletPassphrase(const SecureString &old_wallet_passphrase, const SecureString &new_wallet_passphrase) override; void abortRescan() override; bool backupWallet(const std::string &filename) override; std::string getWalletName() override; bool getNewDestination(const std::string label, std::string &dest) override; bool getPubKey(const std::string &address, std::string &pub_key) override; bool getPrivKey(const std::string &address, std::string &key) override; bool isSpendable(const std::string &dest) override; bool setAddressBook(const std::string &dest, const std::string &name, const std::string &purpose) override; bool delAddressBook(const std::string &dest) override; bool getAddress(const std::string &dest, std::string *name, isminetype *is_mine, std::string *purpose) override; std::vector<WalletAddress> getAddresses() override; bool addDestData(const std::string &dest, const std::string &key, const std::string &value) override; bool eraseDestData(const std::string &dest, const std::string &key) override; std::vector<std::string> getDestValues(const std::string &prefix) override; bool generateAddresses(int count, std::string &fail_reason) override; WalletMutableTransaction createTransaction(const std::vector<CRecipient>& recipients, std::string& fail_reason) override; bool commitTransaction(WalletMutableTransaction tx, WalletOrderForm order_form, std::string &fail_reason) override; WalletTx getWalletTx(const std::string &txid) override; std::vector<WalletTx> getWalletTxs() override; uint32_t numberOfAddresses() override; bool tryGetTxStatus(const std::string &txid, WalletTxStatus &tx_status, int &num_blocks, int64_t &block_time) override; WalletTx getWalletTxDetails(const std::string &txid, WalletTxStatus &tx_status, WalletOrderForm &order_form, bool &in_mempool, int &num_blocks) override; WalletBalances getBalances() override; bool tryGetBalances(WalletBalances &balances, int &num_blocks) override; CAmount getBalance() override; CAmount getAvailableBalance() override; CAmount getRequiredFee(unsigned int tx_bytes) override; CAmount getMinimumFee(unsigned int tx_bytes, const CCoinControl &coin_control, int *returned_target, FeeReason *reason) override; unsigned int getConfirmTarget() override; bool hdEnabled() override; bool canGetAddresses() override; bool IsWalletFlagSet(uint64_t flag) override; void remove() override; std::unique_ptr<Handler> handleUnload(UnloadFn fn) override; std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override; std::unique_ptr<Handler> handleStatusChanged(StatusChangedFn fn) override; std::unique_ptr<Handler> handleAddressBookChanged(AddressBookChangedFn fn) override; std::unique_ptr<Handler> handleTransactionChanged(TransactionChangedFn fn) override; std::unique_ptr<Handler> handleBalanceChanged(BalanceChangedFn fn) override; std::unique_ptr<Handler> handleCanGetAddressesChanged(CanGetAddressesChangedFn fn) override; signals: void transactionAdded(QString txid); void transactionUpdated(QString txid); void balanceChanged(); public slots: void onAccountUpdated(UserAccount account, int milestoneIndex); void onAccountBalanceUpdated(QString balance); void onTransactionChanged(QJsonObject payload); private: void updateTransactions(); void updateUnconfirmedBalance(); private: UserAccount _account; SecureString _unlockPassword; std::map<std::string, WalletTx> _transactions; CAmount _uncofirmedBalance { 0 }; int _latestMilestoneIndex { 0 }; }; } // namespace interfaces #endif
41.598291
157
0.757345
MatthewDarnell
632e3acbee7d6ebcf18f3270d5b4b6e42b4da882
24
hpp
C++
modules/renderer/include/texture.hpp
hpnrep6/3DModelViewer
4437d9b798fe75f3f6eae33488edc73dda4aaca0
[ "MIT" ]
null
null
null
modules/renderer/include/texture.hpp
hpnrep6/3DModelViewer
4437d9b798fe75f3f6eae33488edc73dda4aaca0
[ "MIT" ]
null
null
null
modules/renderer/include/texture.hpp
hpnrep6/3DModelViewer
4437d9b798fe75f3f6eae33488edc73dda4aaca0
[ "MIT" ]
null
null
null
namespace JRenderer { }
8
21
0.75
hpnrep6
632e43a378640c79dee3bfcebf1cdae280511121
3,522
cc
C++
tests/func/test_vec_capacity.cc
kokizzu/ctl
0f2db99f4480c4932b6ba619e2bedec905335738
[ "MIT" ]
983
2020-09-26T04:47:54.000Z
2022-03-31T05:04:32.000Z
tests/func/test_vec_capacity.cc
Lisprez/ctl
435a2e6ba6cc4222e890b4c5993a750d29cb04e3
[ "MIT" ]
14
2020-11-10T00:43:49.000Z
2022-03-05T00:44:17.000Z
tests/func/test_vec_capacity.cc
Lisprez/ctl
435a2e6ba6cc4222e890b4c5993a750d29cb04e3
[ "MIT" ]
51
2020-12-16T03:57:19.000Z
2022-03-23T13:49:10.000Z
#include "../test.h" #include <stdint.h> #define P #define T uint8_t #include <vec.h> #define P #define T uint16_t #include <vec.h> #define P #define T uint32_t #include <vec.h> #define P #define T uint64_t #include <vec.h> #define P #define T float #include <vec.h> #define P #define T double #include <vec.h> #include <vector> #define ASSERT_EQUAL_SIZE(_x, _y) (assert(_x.size() == _y.size)) #define ASSERT_EQUAL_CAP(_x, _y) (assert(_x.capacity() == _y.capacity)) int main(void) { #ifdef SRAND srand(time(NULL)); #endif const size_t loops = TEST_RAND(TEST_MAX_LOOPS); for(size_t loop = 0; loop < loops; loop++) { uint8_t value = TEST_RAND(UINT8_MAX); // SMALLEST SIZE. size_t size = TEST_RAND(TEST_MAX_SIZE); enum { MODE_DIRECT, MODE_GROWTH, MODE_TOTAL }; for(size_t mode = MODE_DIRECT; mode < MODE_TOTAL; mode++) { std::vector<uint8_t> a; std::vector<uint16_t> b; std::vector<uint32_t> c; std::vector<uint64_t> d; std::vector<float> e; std::vector<double> f; vec_uint8_t aa = vec_uint8_t_init(); vec_uint16_t bb = vec_uint16_t_init(); vec_uint32_t cc = vec_uint32_t_init(); vec_uint64_t dd = vec_uint64_t_init(); vec_float ee = vec_float_init(); vec_double ff = vec_double_init(); if(mode == MODE_DIRECT) { a.resize (size); b.resize (size); c.resize (size); d.resize (size); e.resize (size); f.resize (size); vec_uint8_t_resize (&aa, size, 0); vec_uint16_t_resize (&bb, size, 0); vec_uint32_t_resize (&cc, size, 0); vec_uint64_t_resize (&dd, size, 0); vec_float_resize (&ee, size, 0.0); vec_double_resize (&ff, size, 0.0); } if(mode == MODE_GROWTH) { for(size_t pushes = 0; pushes < size; pushes++) { a.push_back (value); b.push_back (value); c.push_back (value); d.push_back (value); e.push_back (value); f.push_back (value); vec_uint8_t_push_back (&aa, value); vec_uint16_t_push_back (&bb, value); vec_uint32_t_push_back (&cc, value); vec_uint64_t_push_back (&dd, value); vec_float_push_back (&ee, value); vec_double_push_back (&ff, value); } } ASSERT_EQUAL_SIZE (a, aa); ASSERT_EQUAL_SIZE (b, bb); ASSERT_EQUAL_SIZE (c, cc); ASSERT_EQUAL_SIZE (d, dd); ASSERT_EQUAL_SIZE (e, ee); ASSERT_EQUAL_SIZE (f, ff); ASSERT_EQUAL_CAP (a, aa); ASSERT_EQUAL_CAP (b, bb); ASSERT_EQUAL_CAP (c, cc); ASSERT_EQUAL_CAP (d, dd); ASSERT_EQUAL_CAP (e, ee); ASSERT_EQUAL_CAP (f, ff); vec_uint8_t_free (&aa); vec_uint16_t_free (&bb); vec_uint32_t_free (&cc); vec_uint64_t_free (&dd); vec_float_free (&ee); vec_double_free (&ff); } } TEST_PASS(__FILE__); }
29.107438
71
0.500284
kokizzu
6330f885fb0898fec89aa4fc8c9e9aee2dead73e
2,166
cc
C++
tools/binary_size/libsupersize/caspian/grouped_path.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
tools/binary_size/libsupersize/caspian/grouped_path.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
tools/binary_size/libsupersize/caspian/grouped_path.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2019 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 "tools/binary_size/libsupersize/caspian/grouped_path.h" #include <stdint.h> #include <tuple> namespace { // Returns |s| with the last |sep| + [suffix] removed, or "" if |sep| is not // found. std::string_view RemoveLastSegment(std::string_view s, char sep) { size_t sep_idx = s.find_last_of(sep); return s.substr(0, (sep_idx == std::string_view::npos) ? 0 : sep_idx); } } // namespace namespace caspian { GroupedPath::GroupedPath() = default; GroupedPath::GroupedPath(const GroupedPath& other) = default; GroupedPath::GroupedPath(std::string_view group_in, std::string_view path_in) : group(group_in), path(path_in) {} GroupedPath::~GroupedPath() = default; std::string_view GroupedPath::ShortName(char group_separator) const { if (path.empty()) { // If there's no group separator, return entire group name; return group.substr(group.find_last_of(group_separator) + 1); } // If there's no path separator, return entire path name. return path.substr(path.find_last_of('/') + 1); } GroupedPath GroupedPath::Parent(char group_separator) const { if (path.empty()) { return GroupedPath{RemoveLastSegment(group, group_separator), path}; } return GroupedPath{group, RemoveLastSegment(path, '/')}; } bool GroupedPath::IsTopLevelPath() const { return std::string_view::npos == path.find_first_of('/'); } bool GroupedPath::operator==(const GroupedPath& other) const { return group == other.group && path == other.path; } std::string GroupedPath::ToString() const { std::string ret; ret.reserve(size()); ret += group; if (!group.empty() && !path.empty()) { ret += "/"; } ret += path; return ret; } bool GroupedPath::operator<(const GroupedPath& other) const { return std::tie(group, path) < std::tie(other.group, other.path); } std::ostream& operator<<(std::ostream& os, const GroupedPath& path) { return os << "GroupedPath(group=\"" << path.group << "\", path=\"" << path.path << "\")"; } } // namespace caspian
28.88
77
0.689289
zealoussnow
6334ea4c6061af99defb4f96c44f670d042c21f7
9,403
hh
C++
RAVL2/Math/Geometry/Euclidean/2D/Moments2d2.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Math/Geometry/Euclidean/2D/Moments2d2.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Math/Geometry/Euclidean/2D/Moments2d2.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2001, University of Surrey // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here #ifndef RAVL_MOMENTS2D2_HEDAER #define RAVL_MOMENTS2D2_HEDAER 1 //////////////////////////////////////////////////////////////////////////// //! file="Ravl/Math/Geometry/Euclidean/2D/Moments2d2.hh" //! lib=RavlMath //! date="6/8/1995" //! author="Radek Marik" //! docentry="Image.Image Processing.Region Model" //! rcsid="$Id: Moments2d2.hh 6084 2007-03-05 16:03:05Z craftit $" //! docentry="Ravl.API.Math.Geometry.2D" #include "Ravl/Types.hh" #include "Ravl/Index2d.hh" #include "Ravl/Point2d.hh" #include "Ravl/Vector2d.hh" namespace RavlN { class Matrix2dC; //! userlevel=Normal //: The moments up to 2nd order in 2D space class Moments2d2C { public: inline Moments2d2C() : m00(0.0), m10(0.0), m01(0.0), m20(0.0), m11(0.0), m02(0.0) {} //: Default constructor // Creates the moment object with all moments set to be zero. inline Moments2d2C(RealT nm00,RealT nm10,RealT nm01,RealT nm20,RealT nm11,RealT nm02) : m00(nm00), m10(nm10), m01(nm01), m20(nm20), m11(nm11), m02(nm02) {} //: Constructor from a set of values. void Reset() { m00 = m10 = m01 = m20 = m11 = m02 = 0.0; } //: Reset all counters to zero. inline void AddPixel (const Index2dC &pxl); //: Adds a pixel to the object and updates sums. inline void AddPixel (const Point2dC &pxl); //: Adds a position with a weight to the object and updates sums. inline void AddPixel (const TFVectorC<RealT,2> &pxl) { AddPixel(Point2dC(pxl)); } //: Adds a position with a weight to the object and updates sums. inline void AddPixel (const Point2dC &pxl,RealT weight); //: Adds a position with a weight to the object and updates sums. const Moments2d2C &operator+=(const Index2dC &pxl) { AddPixel(pxl); return *this; } //: Add pixel to set. const Moments2d2C &operator+=(const Point2dC &point) { AddPixel(point); return *this; } //: Add pixel to set. Vector2dC PrincipalAxisSize() const; //: Calculate the size of the principle axis. // It returns the new values for M02 and M20, // the largest is the first element of the vector. static RealT Elongatedness(const Vector2dC &principalAxisSize) { RealT sumM = principalAxisSize[0] + principalAxisSize[1]; return (sumM!=0) ? Abs((principalAxisSize[0] - principalAxisSize[1]) / sumM) : 0 ; } //: Returns the ratio of the difference and the sum of moments m02 and m20. // The value 0 means that objects is a symmetrical object, // the value 1 corresponds to a one-dimensional object. inline const Moments2d2C & Moments2d2() const { return *this; } //: Access moments. inline Moments2d2C & Moments2d2() { return *this; } //: Access moments. inline RealT M00() const { return m00; } //: Access 00 component. inline RealT M10() const { return m10; } //: Access 10 component. inline RealT M01() const { return m01; } //: Access 01 component. inline RealT M20() const { return m20; } //: Access 20 component. inline RealT M11() const { return m11; } //: Access 11 component. inline RealT M02() const { return m02; } //: Access 02 component. inline RealT & M00() { return m00; } //: Access 00 component. inline RealT & M10() { return m10; } //: Access 10 component. inline RealT & M01() { return m01; } //: Access 01 component. inline RealT & M20() { return m20; } //: Access 20 component. inline RealT & M11() { return m11; } //: Access 11 component. inline RealT & M02() { return m02; } //: Access 02 component. inline RealT Area() const { return m00; } //: Returns the moment m00, ie the area of the 2 dimensional object. inline RealT CentroidX() const { return M10()/M00(); } //: Returns the x co-ordinate of the centroid. // The M00 moment must be different 0. inline RealT CentroidY() const { return M01()/M00(); } //: Returns the y co-ordinate of the centroid. // The M00 moment must be different 0. inline RealT VarX() const { return m20/m00 - Sqr(CentroidX()); } //: Returns the variance of the x. inline RealT VarY() const { return m02/m00 - Sqr(CentroidY()); } //: Returns the variance of the y. inline RealT CentroidRow() const { return M10()/M00(); } //: Returns the row co-ordinate of the centroid. // The M00 moment must be different 0. inline RealT CentroidCol() const { return M01()/M00(); } //: Returns the col co-ordinate of the centroid. // The M00 moment must be different 0. inline RealT VarRows() const { return m20/m00 - Sqr(CentroidRow()); } //: Returns the variance along the row axis. inline RealT VarCols() const { return m02/m00 - Sqr(CentroidCol()); } //: Returns the variance along the column axis inline RealT SlopeY() const; //: Returns the slope dY/dX. The used criterion is Sum(Y-y)^2 -> min. // It means dY/dX = k, where y = k*x+q. inline RealT SlopeX() const; //: Returns the slope dX/dY. The used criterion is Sum(X-x)^2 -> min. // It means dX/dY = k, where x = k*y+q. inline RealT InterceptY() const; //: Returns the estimate of q, if y = k*x+q. // The used criterion is Sum(Y-y)^2 -> min. inline RealT InterceptX() const; //: Returns the estimate of q, if y = k*y+q. // The used criterion is Sum(X-x)^2 -> min. Matrix2dC Covariance() const; //: Return the covariance matrix. Point2dC Centroid() const { return Point2dC(CentroidRow(),CentroidCol()); } //: Calculate the centroid. Moments2d2C operator+(const Moments2d2C &m) const { return Moments2d2C(m00 + m.M00(),m10 + m.M10(),m01 + m.M01(),m20 + m.M20(),m11 + m.M11(),m02 + m.M02()); } //: Add to sets of moments together. Moments2d2C operator-(const Moments2d2C &m) const { return Moments2d2C(m00 - m.M00(),m10 - m.M10(),m01 - m.M01(),m20 - m.M20(),m11 - m.M11(),m02 - m.M02()); } //: Subtract one set of moments from another. const Moments2d2C &operator+=(const Moments2d2C &m); //: Add to sets of moments to this one. const Moments2d2C &operator-=(const Moments2d2C &m); //: Subtract a set of moments to this one. void SwapXY() { Swap(m10,m01); Swap(m20,m02); } //: Swap X and Y co-ordinates. private: RealT m00; RealT m10; RealT m01; RealT m20; RealT m11; RealT m02; friend istream & operator>>(istream & is, Moments2d2C & mom); }; ostream & operator<<(ostream & os, const Moments2d2C & mom); istream & operator>>(istream & is, Moments2d2C & mom); } #include "Ravl/Math.hh" //::Abs() namespace RavlN { inline void Moments2d2C::AddPixel (const Index2dC &pxl) { RealT a = pxl[0]; RealT b = pxl[1]; m00++; m01 += b; m10 += a; m11 += a*b; m02 += b*b; m20 += a*a; } inline void Moments2d2C::AddPixel (const Point2dC &pxl) { RealT a = pxl[0]; RealT b = pxl[1]; m00++; m01 += b; m10 += a; m11 += a*b; m02 += b*b; m20 += a*a; } void Moments2d2C::AddPixel (const Point2dC &pxl,RealT weight) { RealT a = pxl[0]; RealT b = pxl[1]; m00 += weight; RealT wa = a * weight; RealT wb = b * weight; m01 += wb; m10 += wa; m11 += a*wb; m02 += b*wb; m20 += a*wa; } inline const Moments2d2C &Moments2d2C::operator+=(const Moments2d2C &m) { m00 += m.M00(); m10 += m.M10(); m01 += m.M01(); m20 += m.M20(); m11 += m.M11(); m02 += m.M02(); return *this; } inline const Moments2d2C &Moments2d2C::operator-=(const Moments2d2C &m) { m00 -= m.M00(); m10 -= m.M10(); m01 -= m.M01(); m20 -= m.M20(); m11 -= m.M11(); m02 -= m.M02(); return *this; } inline RealT Moments2d2C::SlopeY() const { RealT det = m00 * m20 - m10 * m10; if(IsSmall(det)) throw ExceptionOutOfRangeC("Moments2d2C::SlopeY(), Determinant near zero. "); return (m00 * m11 - m10 * m01)/det; } inline RealT Moments2d2C::InterceptY() const { RealT det = m00 * m20 - m10 * m10; if(IsSmall(det)) throw ExceptionOutOfRangeC("Moments2d2C::InterceptY(), Determinant near zero. "); return (m20 * m01 - m10 * m11)/det; } inline RealT Moments2d2C::SlopeX() const { RealT det = m00 * m02 - m01 * m01; if(IsSmall(det)) throw ExceptionOutOfRangeC("Moments2d2C::SlopeX(), Determinant near zero. "); return (m00 * m11 - m01 * m10)/det; } inline RealT Moments2d2C::InterceptX() const { RealT det = m00 * m02 - m01 * m01; if(IsSmall(det)) throw ExceptionOutOfRangeC("Moments2d2C::InterceptX(), Determinant near zero. "); return (m02 * m10 - m01 * m11)/det; } } #endif
27.57478
112
0.594704
isuhao
633a167660be5788cc60862b874c510dd76439a9
855
cpp
C++
apps/src/videostitch-studio-gui/src/commands/spherescalechangedcommand.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
182
2019-04-19T12:38:30.000Z
2022-03-20T16:48:20.000Z
apps/src/videostitch-studio-gui/src/commands/spherescalechangedcommand.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
107
2019-04-23T10:49:35.000Z
2022-03-02T18:12:28.000Z
apps/src/videostitch-studio-gui/src/commands/spherescalechangedcommand.cpp
tlalexander/stitchEm
cdff821ad2c500703e6cb237ec61139fce7bf11c
[ "MIT" ]
59
2019-06-04T11:27:25.000Z
2022-03-17T23:49:49.000Z
// Copyright (c) 2012-2017 VideoStitch SAS // Copyright (c) 2018 stitchEm #include "spherescalechangedcommand.hpp" #include "widgets/outputconfigurationwidget.hpp" #include <QCoreApplication> SphereScaleChangedCommand::SphereScaleChangedCommand(double oldSphereScale, double newSphereScale, OutputConfigurationWidget* outputConfigurationWidget) : QUndoCommand(), oldSphereScale(oldSphereScale), newSphereScale(newSphereScale), outputConfigurationWidget(outputConfigurationWidget) { setText(QCoreApplication::translate("Undo command", "Sphere scale changed")); } void SphereScaleChangedCommand::undo() { outputConfigurationWidget->changeSphereScale(oldSphereScale); } void SphereScaleChangedCommand::redo() { outputConfigurationWidget->changeSphereScale(newSphereScale); }
38.863636
106
0.761404
tlalexander
633d51fd67d2c7625b3d1550c471b3612264fa25
5,646
cpp
C++
src/Kernel/ResourceImageData.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
39
2016-04-21T03:25:26.000Z
2022-01-19T14:16:38.000Z
src/Kernel/ResourceImageData.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
23
2016-06-28T13:03:17.000Z
2022-02-02T10:11:54.000Z
src/Kernel/ResourceImageData.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
14
2016-06-22T20:45:37.000Z
2021-07-05T12:25:19.000Z
#include "ResourceImageData.h" #include "Interface/ImageCodecInterface.h" #include "Interface/CodecServiceInterface.h" #include "Interface/ConfigServiceInterface.h" #include "Kernel/Logger.h" #include "Kernel/DocumentHelper.h" #include "Kernel/ConstString.h" #include "Kernel/AssertionMemoryPanic.h" #include "Kernel/FileStreamHelper.h" #include "Kernel/PixelFormatHelper.h" #include "Kernel/FileGroupHelper.h" namespace Mengine { ////////////////////////////////////////////////////////////////////////// ResourceImageData::ResourceImageData() : m_width( 0 ) , m_height( 0 ) , m_widthF( 0.f ) , m_heightF( 0.f ) , m_maxSize( 0.f, 0.f ) , m_buffer( nullptr ) { } ////////////////////////////////////////////////////////////////////////// ResourceImageData::~ResourceImageData() { } ////////////////////////////////////////////////////////////////////////// bool ResourceImageData::_compile() { const ContentInterfacePtr & content = this->getContent(); const FileGroupInterfacePtr & fileGroup = content->getFileGroup(); const FilePath & filePath = content->getFilePath(); InputStreamInterfacePtr stream = Helper::openInputStreamFile( fileGroup, filePath, false, false, MENGINE_DOCUMENT_FACTORABLE ); MENGINE_ASSERTION_MEMORY_PANIC( stream, "image file '%s' was not found" , Helper::getFileGroupFullPath( this->getContent()->getFileGroup(), this->getContent()->getFilePath() ) ); MENGINE_ASSERTION_FATAL( stream->size() != 0, "empty file '%s' codec '%s'" , Helper::getFileGroupFullPath( this->getContent()->getFileGroup(), this->getContent()->getFilePath() ) , this->getContent()->getCodecType().c_str() ); const ConstString & codecType = content->getCodecType(); ImageDecoderInterfacePtr imageDecoder = CODEC_SERVICE() ->createDecoder( codecType, MENGINE_DOCUMENT_FACTORABLE ); MENGINE_ASSERTION_MEMORY_PANIC( imageDecoder, "image decoder '%s' for file '%s' was not found" , this->getContent()->getCodecType().c_str() , Helper::getFileGroupFullPath( this->getContent()->getFileGroup(), this->getContent()->getFilePath() ) ); if( imageDecoder->prepareData( stream ) == false ) { LOGGER_ERROR( "image decoder '%s' for file '%s' was not found" , this->getContent()->getCodecType().c_str() , Helper::getFileGroupFullPath( this->getContent()->getFileGroup(), this->getContent()->getFilePath() ) ); return false; } const ImageCodecDataInfo * dataInfo = imageDecoder->getCodecDataInfo(); uint32_t width = dataInfo->width; uint32_t height = dataInfo->height; EPixelFormat format = dataInfo->format; uint32_t memorySize = Helper::getTextureMemorySize( width, height, format ); m_buffer = Helper::allocateMemoryNT<uint8_t>( memorySize, "image_data" ); uint32_t channels = Helper::getPixelFormatChannels( format ); ImageDecoderData data; data.buffer = m_buffer; data.size = memorySize; data.pitch = width * channels; data.format = format; if( imageDecoder->decode( &data ) == 0 ) { LOGGER_ERROR( "image decoder '%s' for file '%s' invalid decode" , this->getContent()->getCodecType().c_str() , Helper::getFileGroupFullPath( this->getContent()->getFileGroup(), this->getContent()->getFilePath() ) ); return false; } return true; } ////////////////////////////////////////////////////////////////////////// void ResourceImageData::_release() { Helper::deallocateMemory( m_buffer, "image_data" ); m_buffer = nullptr; } ////////////////////////////////////////////////////////////////////////// void ResourceImageData::setImageMaxSize( const mt::vec2f & _maxSize ) { m_maxSize = _maxSize; } ////////////////////////////////////////////////////////////////////////// const mt::vec2f & ResourceImageData::getImageMaxSize() const { return m_maxSize; } ////////////////////////////////////////////////////////////////////////// void ResourceImageData::setImageWidth( uint32_t _width ) { m_width = _width; m_widthF = (float)_width; } ////////////////////////////////////////////////////////////////////////// uint32_t ResourceImageData::getImageWidth() const { return m_width; } ////////////////////////////////////////////////////////////////////////// void ResourceImageData::setImageHeight( uint32_t _height ) { m_height = _height; m_heightF = (float)_height; } ////////////////////////////////////////////////////////////////////////// uint32_t ResourceImageData::getImageHeight() const { return m_height; } ////////////////////////////////////////////////////////////////////////// float ResourceImageData::getImageWidthF() const { return m_widthF; } ////////////////////////////////////////////////////////////////////////// float ResourceImageData::getImageHeightF() const { return m_heightF; } ////////////////////////////////////////////////////////////////////////// Pointer ResourceImageData::getImageBuffer() const { return m_buffer; } ////////////////////////////////////////////////////////////////////////// }
35.961783
135
0.505136
irov
633f226b759776df06943ecdcf0a51ee31c32c59
958
cpp
C++
BrotBoxEngine/MouseButtons.cpp
siretty/BrotBoxEngine
e1eb95152ffb8a7051e96a8937aa62f568b90a27
[ "MIT" ]
37
2020-06-14T18:14:08.000Z
2022-03-29T18:39:34.000Z
BrotBoxEngine/MouseButtons.cpp
HEX17/BrotBoxEngine
4f8bbe220be022423b94e3b594a3695b87705a70
[ "MIT" ]
2
2021-04-05T15:34:18.000Z
2021-05-28T00:04:56.000Z
BrotBoxEngine/MouseButtons.cpp
HEX17/BrotBoxEngine
4f8bbe220be022423b94e3b594a3695b87705a70
[ "MIT" ]
10
2020-06-25T17:07:03.000Z
2022-03-08T20:31:17.000Z
#include "BBE/MouseButtons.h" #include "BBE/Exceptions.h" bbe::String bbe::mouseButtonToString(MouseButton button) { switch (button) { case MouseButton::LEFT: return bbe::String("MB_LEFT"); case MouseButton::RIGHT: return bbe::String("MB_RIGHT"); case MouseButton::MIDDLE: return bbe::String("MB_MIDDLE"); case MouseButton::_4: return bbe::String("MB_4"); case MouseButton::_5: return bbe::String("MB_5"); case MouseButton::_6: return bbe::String("MB_6"); case MouseButton::_7: return bbe::String("MB_7"); case MouseButton::_8: return bbe::String("MB_8"); } throw NoSuchMouseButtonException(); } bool bbe::isMouseButtonValid(MouseButton button) { switch (button) { case MouseButton::LEFT : case MouseButton::RIGHT : case MouseButton::MIDDLE: case MouseButton::_4 : case MouseButton::_5 : case MouseButton::_6 : case MouseButton::_7 : case MouseButton::_8 : return true; } return false; }
21.288889
56
0.693111
siretty
6342a192baf2b2c8e02b65210518b607600111bd
2,038
cpp
C++
src/MpiOp.cpp
seanmarks/mpi_cpp
a4dda9d310d494272ace08e5e1af2a8a3dc5e029
[ "MIT" ]
null
null
null
src/MpiOp.cpp
seanmarks/mpi_cpp
a4dda9d310d494272ace08e5e1af2a8a3dc5e029
[ "MIT" ]
null
null
null
src/MpiOp.cpp
seanmarks/mpi_cpp
a4dda9d310d494272ace08e5e1af2a8a3dc5e029
[ "MIT" ]
null
null
null
// Written by Sean M. Marks (https://github.com/seanmarks) #include "MpiOp.h" MpiOp::MpiOp(): user_function_ptr_(nullptr), is_commutative_(false) {} MpiOp::MpiOp(const MpiOp& mpi_op) { this->user_function_ptr_ = mpi_op.user_function_ptr_; this->is_commutative_ = mpi_op.is_commutative_; #ifdef MPI_ENABLED if ( this->user_function_ptr_ != nullptr ) { MPI_Op_create(user_function_ptr_, is_commutative_, &mpi_op_); } #endif // ifdef MPI_ENABLED } MpiOp& MpiOp::operator=(const MpiOp& mpi_op) { if ( &mpi_op != this ) { this->user_function_ptr_ = mpi_op.user_function_ptr_; this->is_commutative_ = mpi_op.is_commutative_; #ifdef MPI_ENABLED if ( this->user_function_ptr_ != nullptr ) { MPI_Op_create(user_function_ptr_, is_commutative_, &mpi_op_); } #endif // ifdef MPI_ENABLED } return *this; } MpiOp::~MpiOp() { #ifdef MPI_ENABLED if ( user_function_ptr_ != nullptr ) { MPI_Op_free(&mpi_op_); } #endif // ifdef MPI_ENABLED }; const std::unordered_map<MpiOp::StandardOp, std::string, MpiOp::EnumClassHash> MpiOp::standard_mpi_op_names_ = { { StandardOp::Null, "Null" }, { StandardOp::Max, "Max" }, { StandardOp::Min, "Min" }, { StandardOp::Sum, "Sum" }, { StandardOp::Product, "Product" }, { StandardOp::Land, "Land" }, { StandardOp::Band, "Band" }, { StandardOp::Lor, "Lor" }, { StandardOp::Bor, "Bor" }, { StandardOp::Lxor, "Lxor" }, { StandardOp::Bxor, "Bxor" }, { StandardOp::Minloc, "Minloc" }, { StandardOp::Maxloc, "Maxloc" }, { StandardOp::Replace, "Replace" } }; const std::string& MpiOp::getName(const MpiOp::StandardOp& op) { const auto it = standard_mpi_op_names_.find(op); if ( it != standard_mpi_op_names_.end() ) { return it->second; } else { std::stringstream err_ss; err_ss << "Error in " << FANCY_FUNCTION << "\n" << " A standard MPI operation does not have a registered name." << " This should never happen.\n"; throw std::runtime_error( err_ss.str() ); } }
25.160494
79
0.653582
seanmarks
63431b7a0f2b81400ec320b0d1a5f036afc1e326
5,408
hpp
C++
src/standard_sv.hpp
Mohido/Simple_Stereo_Triangulation
17539c50fd308d0f49c9857bd5dbbbdbdcd2fa09
[ "MIT" ]
null
null
null
src/standard_sv.hpp
Mohido/Simple_Stereo_Triangulation
17539c50fd308d0f49c9857bd5dbbbdbdcd2fa09
[ "MIT" ]
null
null
null
src/standard_sv.hpp
Mohido/Simple_Stereo_Triangulation
17539c50fd308d0f49c9857bd5dbbbdbdcd2fa09
[ "MIT" ]
null
null
null
#pragma once #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <iostream> #include <stdio.h> #include <vector> #include <string> #include <algorithm> #include <cmath> #include "functions.hpp" /// <summary> /// Caculates the 3D spetial point from the given parameters. /// </summary> /// <param name="u_1">relative pixel coordinate in image plane 1</param> /// <param name="u_2">relative pixel coordinate in image plane 2</param> /// <param name="baseline">camera baseline</param> /// <param name="M_int"></param> /// <param name="c_1"></param> /// <param name="c_2"></param> /// <returns></returns> cv::Point3f standard_stereo( const cv::Point2f& u_1, const cv::Point2f& u_2, //const cv::Point3f& c_1, const cv::Point3f& c_2, const cv::Mat& M_int, const float& b, const float ppmm, const float& fl ) { /*Extracting the intrinsic important parameters*/ float fx = M_int.at<float>({ 0, 0 }); float fy = M_int.at<float>({ 1, 1 }); float ox = M_int.at<float>({ 0, 2 }); float oy = M_int.at<float>({ 1, 2 }); /*Fully using the intrinsic parameters of the camera.*/ float d = std::fabs(u_1.x - u_2.x); printf("[DEBUG]: [standard_stereo]: disparity is: (%.2f)\n", d); // d = (d == 0) ? 0.000001f : d; // To avoid infinity cv::Point3f point3d; point3d.x = (b * (u_1.x - ox)) / d; point3d.y = (b * fx * (u_1.y - oy)) / (fy * d); point3d.z = (b * fx) / d; printf("[DEBUG]: [standard_stereo]: Constructed 3D point: (%.2f, %.2f, %.2f)\n", point3d.x, point3d.y, point3d.z); return point3d; } /// <summary> /// Calculate the difference sum between 2 matrices of the same size. /// </summary> /// <param name="M1"></param> /// <param name="M2"></param> /// <returns></returns> static int sumOfAbsDiff(const cv::Mat& M1, const cv::Mat& M2) { int rdsum = 0, bdsum = 0, gdsum = 0; for (int r = 0; r < M1.size().height; r++) { for (int c = 0; c < M1.size().width; c++) { cv::Vec3b mc1 = M1.at<cv::Vec3b>({ r,c }); cv::Vec3b mc2 = M2.at<cv::Vec3b>({ r,c }); rdsum += std::abs(int(mc1[0]) - int(mc2[0])); bdsum += std::abs(int(mc1[1]) - int(mc2[1])); gdsum += std::abs(int(mc1[2]) - int(mc2[2])); } } return rdsum + bdsum + gdsum; } /// <summary> /// /// </summary> /// <param name="windowsize"></param> /// <param name="w1pos">to know which pixel we want to compare (from first image)</param> /// <param name="image1"></param> /// <param name="image2"></param> /// <returns></returns> std::pair<int, int> templateMatching( const int& w_size, const std::pair<int, int>& w1pos, const cv::Mat& image1, const cv::Mat& image2, const TemplateMatcherLoss& option = TemplateMatcherLoss::SUM_OF_ABSOLUTE_DIFF) { if (image1.size().height != image2.size().height) { throw std::runtime_error("Image heights are not the same. Template matching require both images to have the same sizes"); } const int im1_w = image1.size().width; const int im1_h = image1.size().height; const int im2_w = image2.size().width; const int im2_h = image2.size().height; cv::Mat M_w = cropWindow(w_size, w1pos, image1); int bestSum = 0; // the column of the lowest sum int smallestSum = INT_MAX; // the smallest absolute difference sum of the current subwindow. /*Use the template matching algorithm*/ for (int c = 0; c < im2_w - w_size; c++) { // per column in the second image x-axis // right image subwindow cv::Mat M_w_2 = cropWindow(w_size, { w1pos.first, c }, image2); /*Match the 2 cropped windows and use the loss option.*/ int temp = sumOfAbsDiff(M_w, M_w_2); if (temp < smallestSum) { bestSum = c; smallestSum = temp; } } //printf("[DEBUG]: [templateMatching]: Window at (%d, %d) have been matched to (%d, %d)\n\n", w1pos.first, w1pos.second, w1pos.first, bestSum); return { w1pos.first, bestSum }; } /// <summary> /// Uses the simple stereo to solve the task. /// </summary> /// <param name="filename"></param> /// <param name="matchings"></param> /// <param name="depthMap"></param> /// <param name="M_int"></param> void useSimpleStereo( const std::string& filename, const std::vector<std::pair<cv::Point2f, cv::Point2f>>& matchings, cv::Mat& depthMap, const cv::Mat& M_int, const float& baseline = BASELINE, const float& pixel_space_ratio = PIXEL_SPACE_RATIO, const float& focal_length = FOCAL_LENGTH ) { #ifdef CREATE_CLOUD std::ofstream file(filename); #endif for (const std::pair<cv::Point2f, cv::Point2f>& p_pair : matchings) { cv::Point3f point3d = standard_stereo(p_pair.first, p_pair.second, M_int, baseline, pixel_space_ratio, focal_length); if (point3d.z >= FAR_PLANE || point3d.z <= NEAR_PLANE) { printf("Point out of range\n"); continue; } double& color = depthMap.at<double>({ (int)p_pair.first.x, (int)p_pair.first.y }); double nz = (double)point3d.z / (double)FAR_PLANE; color = 1.0f - nz; #ifdef CREATE_CLOUD file << point3d.x << " " << point3d.y << " " << point3d.z << std::endl; #endif } #ifdef CREATE_CLOUD file.close(); #endif #ifdef SHOW_DEPTH_MAP cv::imshow(WINDOW_NAME, depthMap); #endif cv::waitKey(0); }
31.44186
147
0.612981
Mohido
6347e35acc79940a0ec5d49634264866130d974f
1,759
cpp
C++
src/Game/CHighScoreList.cpp
kenluck2001/2DGameFrameWork
4064b0397240f66250099995157e65f2ee3ecff9
[ "MIT" ]
1
2016-07-22T17:32:38.000Z
2016-07-22T17:32:38.000Z
src/Game/CHighScoreList.cpp
kenluck2001/2DGameFrameWork
4064b0397240f66250099995157e65f2ee3ecff9
[ "MIT" ]
null
null
null
src/Game/CHighScoreList.cpp
kenluck2001/2DGameFrameWork
4064b0397240f66250099995157e65f2ee3ecff9
[ "MIT" ]
null
null
null
// ============================= // SDL Programming // Name: ODOH KENNETH EMEKA // Student id: 0902024 // Task 18 // ============================= #include "CHighScoreList.h" #include <fstream> #include <string> #include <sstream> #include <stdexcept> //////////////////////////////////////////////////////////////////////////////// using namespace std; //////////////////////////////////////////////////////////////////////////////// const size_t MAX_NUM_SCORES = 10; //////////////////////////////////////////////////////////////////////////////// void CHighScoreList::Load( const std::string & file ) { size_t count = 0; clear(); ifstream f(file.c_str()); if ( ! f.is_open() ) throw runtime_error("Cannot open highscorefile for reading"); while( f.good() && (count++ < MAX_NUM_SCORES) ) { string tmp; getline(f,tmp); istringstream s(tmp); CHighScoreItem item; s >> item.score; s >> item.name; insert(item); } f.close(); } //////////////////////////////////////////////////////////////////////////////// void CHighScoreList::Save( const std::string & file ) { size_t count = 0; ofstream f(file.c_str()); if ( ! f.is_open() ) throw runtime_error("Cannot open highscorefile for saving"); CHighScoreList::iterator it = begin(); while ( it != end() && (count++ < MAX_NUM_SCORES) ) { f << it->score << " " << it->name << "\n"; it++; } f.flush(); f.close(); } //////////////////////////////////////////////////////////////////////////////// void CHighScoreList::AddEntry( int score, const std::string & name) { CHighScoreItem item; item.score = score; item.name = name; insert(item); } ////////////////////////////////////////////////////////////////////////////////
24.430556
80
0.430358
kenluck2001
634a66eb2fb62de35ceb1659257be7ca6d005f1d
42
cpp
C++
src/LlvmVal.cpp
djmzp/OrbLang
65b82cb614b39a1946cfa04d042880b7b36412c1
[ "MIT" ]
29
2020-11-19T16:07:45.000Z
2022-01-24T09:58:59.000Z
src/LlvmVal.cpp
djmzp/OrbLang
65b82cb614b39a1946cfa04d042880b7b36412c1
[ "MIT" ]
null
null
null
src/LlvmVal.cpp
djmzp/OrbLang
65b82cb614b39a1946cfa04d042880b7b36412c1
[ "MIT" ]
5
2021-01-06T11:46:59.000Z
2022-02-06T03:41:50.000Z
#include "LlvmVal.h" using namespace std;
14
20
0.761905
djmzp
634b5836f2522a30c4a13c13513b1b930f0a6b76
1,110
cpp
C++
homework/Shevtsov/10/main.cpp
mtrempoltsev/msu_cpp_autumn_2017
0e87491dc117670b99d2ca2f7e1c5efbc425ae1c
[ "MIT" ]
10
2017-09-21T15:17:33.000Z
2021-01-11T13:11:55.000Z
homework/Shevtsov/10/main.cpp
mtrempoltsev/msu_cpp_autumn_2017
0e87491dc117670b99d2ca2f7e1c5efbc425ae1c
[ "MIT" ]
null
null
null
homework/Shevtsov/10/main.cpp
mtrempoltsev/msu_cpp_autumn_2017
0e87491dc117670b99d2ca2f7e1c5efbc425ae1c
[ "MIT" ]
22
2017-09-21T15:45:08.000Z
2019-02-21T19:15:25.000Z
#include <iostream> #include <thread> #include <mutex> #include <condition_variable> std::mutex M; std::condition_variable threadready; // Условная переменная - позволяет блокировать один или более потоков, // пока не произойдет некое определенное действие (например, уведомлние // от другого потока) // Идея: // Ожидающий поток должен сначала выполнить unique_lock. Эта блокировка передается // методу wait(), который освобождает мьютекс и приостанавливает поток, пока не будет // получен сигнал от условной переменной. Когда это произойдет, поток пробудится и // снова выполнится lock. // функция, которая будет выполняться в потоке void thread(std::string game_command) { while(1) { std::unique_lock<std::mutex> lock(M); std::cout << game_command << std::endl; threadready.notify_one(); // уведомление об истинности условия threadready.wait(lock); // освобождение мьютекса } } int main(int argc, const char * argv[]) { // запуск потоков, двух игроков std::thread t1(thread, "ping"); std::thread t2(thread, "pong"); // синхронизация потоков t1.join(); t2.join(); return 0; }
24.666667
86
0.733333
mtrempoltsev
634b64c75154a938ff8b169543b02b5d5e81148c
4,075
cpp
C++
src/ui/widgets/WidgetList.cpp
ChillstepCoder/Vorb
f74c0cfa3abde4fed0e9ec9d936b23c5210ba2ba
[ "MIT" ]
65
2018-06-03T23:09:46.000Z
2021-07-22T22:03:34.000Z
src/ui/widgets/WidgetList.cpp
ChillstepCoder/Vorb
f74c0cfa3abde4fed0e9ec9d936b23c5210ba2ba
[ "MIT" ]
8
2018-06-20T17:21:30.000Z
2020-06-30T01:06:26.000Z
src/ui/widgets/WidgetList.cpp
ChillstepCoder/Vorb
f74c0cfa3abde4fed0e9ec9d936b23c5210ba2ba
[ "MIT" ]
34
2018-06-04T03:40:52.000Z
2022-02-15T07:02:05.000Z
#include "Vorb/stdafx.h" #include "Vorb/ui/widgets/WidgetList.h" vui::WidgetList::WidgetList() : Widget(), m_spacing(10.0f), m_maxHeight(FLT_MAX) { // Empty } vui::WidgetList::~WidgetList() { // Empty } void vui::WidgetList::initBase() { m_panel.init(this, getName() + "_panel"); m_panel.setClipping(Clipping{ ClippingState::HIDDEN, ClippingState::HIDDEN, ClippingState::HIDDEN, ClippingState::HIDDEN }); } void vui::WidgetList::dispose() { Widget::dispose(); IWidgets().swap(m_items); } void vui::WidgetList::updateDimensions(f32 dt) { Widget::updateDimensions(dt); f32 totalHeight = 0.0f; for (size_t i = 0; i < m_items.size(); ++i) { IWidget* child = m_items[i]; // We need to update the child's dimensions now, as we might otherwise get screwy scroll bars as the child isn't up-to-date with parent changes. { WidgetFlags oldFlags = child->getFlags(); child->setFlags({ oldFlags.isClicking, oldFlags.isEnabled, oldFlags.isMouseIn, oldFlags.ignoreOffset, true, // needsDimensionUpdate false, // needsZIndexReorder false, // needsDockRecalculation false, // needsClipRectRecalculation false // needsDrawableRecalculation }); child->update(0.0f); WidgetFlags newFlags = child->getFlags(); child->setFlags({ newFlags.isClicking, newFlags.isEnabled, newFlags.isMouseIn, newFlags.ignoreOffset, false, // needsDimensionUpdate oldFlags.needsZIndexReorder || newFlags.needsZIndexReorder, oldFlags.needsDockRecalculation || newFlags.needsDockRecalculation, oldFlags.needsClipRectRecalculation || newFlags.needsClipRectRecalculation, oldFlags.needsDrawableRecalculation || newFlags.needsDrawableRecalculation }); } child->setPosition(f32v2(0.0f, totalHeight + i * m_spacing)); totalHeight += child->getHeight(); } m_panel.setSize(f32v2(getWidth(), totalHeight > m_maxHeight ? m_maxHeight : totalHeight)); } void vui::WidgetList::addItem(IWidget* item) { m_panel.addWidget(item); m_items.push_back(item); m_flags.needsDrawableRecalculation = true; } bool vui::WidgetList::addItemAtIndex(size_t index, IWidget* item) { if (index > m_items.size()) return false; m_items.insert(m_items.begin() + index, item); m_panel.addWidget(item); m_flags.needsDrawableRecalculation = true; return true; } void vui::WidgetList::addItems(const IWidgets& items) { for (auto& item : items) { addItem(item); } } bool vui::WidgetList::removeItem(IWidget* item) { for (auto it = m_items.begin(); it != m_items.end(); ++it) { if (*it == item) { m_items.erase(it); m_panel.removeWidget(item); m_flags.needsDrawableRecalculation = true; return true; } } return false; } bool vui::WidgetList::removeItem(size_t index) { if (index > m_items.size()) return false; auto it = (m_items.begin() + index); m_panel.removeWidget(*it); m_items.erase(it); m_flags.needsDrawableRecalculation = true; return true; } void vui::WidgetList::setTexture(VGTexture texture) { m_panel.setTexture(texture); } void vui::WidgetList::setBackColor(const color4& color) { m_panel.setColor(color); } void vui::WidgetList::setBackHoverColor(const color4& color) { m_panel.setHoverColor(color); } void vui::WidgetList::setSpacing(f32 spacing) { m_spacing = spacing; m_flags.needsDrawableRecalculation = true; } void vui::WidgetList::setAutoScroll(bool autoScroll) { m_panel.setAutoScroll(autoScroll); } void vui::WidgetList::setMaxHeight(f32 maxHeight) { m_maxHeight = maxHeight; m_flags.needsDimensionUpdate = true; }
26.121795
152
0.628712
ChillstepCoder
634c0bede4bb3788285d7582d75feea8c10f3c1e
233
cpp
C++
A/546/main.cpp
ABGEO07/ABGEOs_CodeForces_Projects
62bf1dc50d435c1f8d2033577e98cf332373b1f8
[ "MIT" ]
null
null
null
A/546/main.cpp
ABGEO07/ABGEOs_CodeForces_Projects
62bf1dc50d435c1f8d2033577e98cf332373b1f8
[ "MIT" ]
null
null
null
A/546/main.cpp
ABGEO07/ABGEOs_CodeForces_Projects
62bf1dc50d435c1f8d2033577e98cf332373b1f8
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int k, n, w, total(0); cin >> k >> n >> w; for (int i(0); i <= w; i++) total = total + k * i; if ((total - n) > 0) cout << total - n; else cout << 0; return 0; }
11.65
28
0.493562
ABGEO07
63531c43da4d6cd926718a4b27d437150bdd83aa
2,651
cpp
C++
common/lock.cpp
raddinet/raddi
87e4996dda8ccc0591ffecbd8d717a1a2947e8a9
[ "MIT" ]
39
2018-05-20T14:08:46.000Z
2022-02-23T15:46:03.000Z
common/lock.cpp
raddinet/raddi
87e4996dda8ccc0591ffecbd8d717a1a2947e8a9
[ "MIT" ]
null
null
null
common/lock.cpp
raddinet/raddi
87e4996dda8ccc0591ffecbd8d717a1a2947e8a9
[ "MIT" ]
3
2019-02-26T21:00:19.000Z
2022-02-03T22:30:52.000Z
#include "lock.h" namespace { void WINAPI defaultCsInit (void ** object) { auto cs = new CRITICAL_SECTION; InitializeCriticalSectionAndSpinCount (cs, 32); *object = cs; } void WINAPI defaultInit (void ** object) { if (!lock::initialize ()) { defaultCsInit (object); } } void WINAPI defaultFree (void ** object) { auto cs = static_cast <CRITICAL_SECTION *> (*object); DeleteCriticalSection (cs); delete cs; } bool WINAPI defaultTry (void ** object) { return TryEnterCriticalSection (static_cast <CRITICAL_SECTION *> (*object)); } bool WINAPI failingTry (void ** object) { return false; } void WINAPI defaultAcquire (void ** object) { EnterCriticalSection (static_cast <CRITICAL_SECTION *> (*object)); } void WINAPI defaultRelease (void ** object) { LeaveCriticalSection (static_cast <CRITICAL_SECTION *> (*object)); } void WINAPI defaultNoOp (void ** object) {} template <typename P> bool Load (HMODULE h, P & pointer, const char * name) { if (P p = reinterpret_cast <P> (GetProcAddress (h, name))) { pointer = p; return true; } else return false; } } void (WINAPI * lock::pInit) (void **) = defaultInit; void (WINAPI * lock::pFree) (void **) = defaultFree; void (WINAPI * lock::pAcquireShared) (void **) = defaultAcquire; void (WINAPI * lock::pAcquireExclusive) (void **) = defaultAcquire; bool (WINAPI * lock::pTryAcquireShared) (void **) = defaultTry; bool (WINAPI * lock::pTryAcquireExclusive) (void **) = defaultTry; void (WINAPI * lock::pReleaseShared) (void **) = defaultRelease; void (WINAPI * lock::pReleaseExclusive) (void **) = defaultRelease; bool lock::initialize () noexcept { if (auto h = GetModuleHandle (L"KERNEL32")) { if (Load (h, pAcquireShared, "AcquireSRWLockShared")) { Load (h, pReleaseShared, "ReleaseSRWLockShared"); Load (h, pAcquireExclusive, "AcquireSRWLockExclusive"); Load (h, pReleaseExclusive, "ReleaseSRWLockExclusive"); // Vista does not have TryAcquire for SRW locks, but we cannot mix CSs and SRWs if (!Load (h, pTryAcquireShared, "TryAcquireSRWLockShared") || !Load (h, pTryAcquireExclusive, "TryAcquireSRWLockExclusive")) { pTryAcquireShared = failingTry; pTryAcquireExclusive = failingTry; } pInit = defaultNoOp; pFree = defaultNoOp; return true; } } pInit = defaultCsInit; return false; }
36.315068
139
0.612976
raddinet
6353231b679b3c06924d1ffb4cd1d140be4ff834
38
cpp
C++
BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise-3.7_cosx.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise-3.7_cosx.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/beginning_with_cpp/token_structure_controlstructure/exercise-3.7_cosx.cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
// // Created by rahul on 21/7/19. //
9.5
31
0.552632
jattramesh
6353c29a3c7fe363c05bd1534b30355b5b51dd5f
4,180
cpp
C++
Project3/test.cpp
jehalladay/Theory-of-Algorithms
fa35ed1a3c40e45a3b97c93a44e96532b91fb1b5
[ "MIT" ]
null
null
null
Project3/test.cpp
jehalladay/Theory-of-Algorithms
fa35ed1a3c40e45a3b97c93a44e96532b91fb1b5
[ "MIT" ]
null
null
null
Project3/test.cpp
jehalladay/Theory-of-Algorithms
fa35ed1a3c40e45a3b97c93a44e96532b91fb1b5
[ "MIT" ]
null
null
null
/* Project 3 - Hashtable and Heapsort James Halladay Theory of Algorithms 10/9/2021 This program will test the various functions and methods used to create this project */ #include <iostream> #include <string> #include <fstream> #include "hash.h" #include "heap.h" #include "utility.h" using namespace std; const string MODIFY_DATE = "10-11-21"; // Here we will place function prototypes that execute the tests void init_test1(); void init_test2(); void init_test3(); /* Our program runs tests in three phases: 1: Tests to see if all files are linking and compiling properly 2: Runs the individual tests for each file to test the functions they contain 3: Runs tests on functions and methods as they work together in this file's test function */ int main() { init_test1(); heaptest(); hashtest1(); // utilitytest1(); // cout << endl << "Testing hash.cpp" << endl; // hashtest2(); cout << endl << "Testing utility.cpp" << endl; utilitytest2(); cout << endl << "Testing test.cpp" << endl; // init_test2(); init_test3(); cout << endl << "Ending execution of test.cpp" << endl; return 0; } /* Function is for testing that test.cpp is linking and compiling properly */ void init_test1() { cout << endl << "Hello, World! from test.cpp " << "\t\tLast Modified: " << MODIFY_DATE << endl; } /* Function is for testing that the functions in hash.cpp, heap.cpp, and utility.cpp are working and interacting properly Basic: only tests that functions and methods are working as intended */ void init_test2() { Hashtable hash_table = read_file("A Scandal In Bohemia.txt", .5); cout << "Testing Hashtable and read_file:" << endl; cout << "\t\tHashtable Size:\t\t\t" << hash_table.get_size() << endl; cout << "\t\tHashtable Capacity:\t\t" << hash_table.get_capacity() << endl; cout << "\t\tHashtable Load Factor:\t\t" << hash_table.get_load_factor() << endl; cout << "\t\tHashtable Max Load Factor:\t" << hash_table.get_max_load_factor() << endl; hash_table = read_file("A Scandal In Bohemia.txt", .7); cout << "Testing Hashtable and read_file:" << endl; cout << "\t\tHashtable Size:\t\t\t" << hash_table.get_size() << endl; cout << "\t\tHashtable Capacity:\t\t" << hash_table.get_capacity() << endl; cout << "\t\tHashtable Load Factor:\t\t" << hash_table.get_load_factor() << endl; cout << "\t\tHashtable Max Load Factor:\t" << hash_table.get_max_load_factor() << endl; hash_table = read_file("A Scandal In Bohemia.txt", .8); cout << "Testing Hashtable and read_file:" << endl; cout << "\t\tHashtable Size:\t\t\t" << hash_table.get_size() << endl; cout << "\t\tHashtable Capacity:\t\t" << hash_table.get_capacity() << endl; cout << "\t\tHashtable Load Factor:\t\t" << hash_table.get_load_factor() << endl; cout << "\t\tHashtable Max Load Factor:\t" << hash_table.get_max_load_factor() << endl; cout << "Testing the pop method:" << endl; element e = hash_table.pop(); cout << "\t\tElement: " << e.entry << endl; cout << "\t\tElement: " << e.frequency << endl; cout << "\t\tElement: " << e.key << endl; cout << "Finished test.cpp tests" << endl; } void init_test3() { Hashtable hash_table = read_file("A Scandal In Bohemia.txt", .5); cout << "Testing Hashtable and read_file:" << endl; cout << "\t\tHashtable Size:\t\t\t" << hash_table.get_size() << endl; cout << "\t\tHashtable Capacity:\t\t" << hash_table.get_capacity() << endl; cout << "\t\tHashtable Load Factor:\t\t" << hash_table.get_load_factor() << endl; cout << "\t\tHashtable Max Load Factor:\t" << hash_table.get_max_load_factor() << endl; vector<element> word_list = Heap().heap_sort(hash_table); cout << "Word:\t\t\t\t" << word_list[0].entry << endl; cout << "Frequency:\t\t\t" << word_list[0].frequency << endl; cout << "Size of Wordlist:\t" << word_list.size() << endl; }
33.44
102
0.615311
jehalladay
6353f342631d0cf7cb7ca49235e5e5311823921b
2,153
cc
C++
content/browser/renderer_host/input/synthetic_pointer_action.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
content/browser/renderer_host/input/synthetic_pointer_action.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
content/browser/renderer_host/input/synthetic_pointer_action.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2015 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/renderer_host/input/synthetic_pointer_action.h" #include "base/logging.h" #include "third_party/WebKit/public/web/WebInputEvent.h" #include "ui/events/latency_info.h" namespace content { SyntheticPointerAction::SyntheticPointerAction( const SyntheticPointerActionParams& params) : params_(params) {} SyntheticPointerAction::SyntheticPointerAction( const SyntheticPointerActionParams& params, SyntheticPointer* synthetic_pointer) : params_(params), synthetic_pointer_(synthetic_pointer) {} SyntheticPointerAction::~SyntheticPointerAction() {} SyntheticGesture::Result SyntheticPointerAction::ForwardInputEvents( const base::TimeTicks& timestamp, SyntheticGestureTarget* target) { if (params_.gesture_source_type == SyntheticGestureParams::DEFAULT_INPUT) params_.gesture_source_type = target->GetDefaultSyntheticGestureSourceType(); DCHECK_NE(params_.gesture_source_type, SyntheticGestureParams::DEFAULT_INPUT); ForwardTouchOrMouseInputEvents(timestamp, target); return SyntheticGesture::GESTURE_FINISHED; } void SyntheticPointerAction::ForwardTouchOrMouseInputEvents( const base::TimeTicks& timestamp, SyntheticGestureTarget* target) { switch (params_.pointer_action_type()) { case SyntheticPointerActionParams::PointerActionType::PRESS: synthetic_pointer_->Press(params_.position().x(), params_.position().y(), target, timestamp); break; case SyntheticPointerActionParams::PointerActionType::MOVE: synthetic_pointer_->Move(params_.index(), params_.position().x(), params_.position().y(), target, timestamp); break; case SyntheticPointerActionParams::PointerActionType::RELEASE: synthetic_pointer_->Release(params_.index(), target, timestamp); break; default: NOTREACHED(); break; } synthetic_pointer_->DispatchEvent(target, timestamp); } } // namespace content
35.883333
80
0.748723
Wzzzx
636003c01d42140517efea949c39a554c92031c4
6,134
cpp
C++
src/RichText.cpp
ApertaTeam/utengine
e641a76b6c0042a4b581f1ec51798b74f2bb5293
[ "MIT" ]
1
2019-06-19T10:19:33.000Z
2019-06-19T10:19:33.000Z
src/RichText.cpp
ApertaTeam/utengine
e641a76b6c0042a4b581f1ec51798b74f2bb5293
[ "MIT" ]
null
null
null
src/RichText.cpp
ApertaTeam/utengine
e641a76b6c0042a4b581f1ec51798b74f2bb5293
[ "MIT" ]
1
2019-06-19T09:00:15.000Z
2019-06-19T09:00:15.000Z
#include "RichText.h" #include <sstream> #include <vector> #include <stdlib.h> #include <cmath> #include <iostream> namespace UT { RichText::RichText() { this->font = NULL; this->rawText = ""; this->renderPosition = { 0, 0 }; this->monospacing = -1; this->renderOffset = { 0, 0 }; this->ignoreTags = false; this->wavyAngle = 0; this->scale = 1.0; this->textTypeFlags = static_cast<char>(TextType::Normal); this->colorPresets = std::unordered_map<std::string, int32_t>(); colorPresets.insert(std::pair<std::string, int32_t>("Yellow", 0xFFFF00FF)); colorPresets.insert(std::pair<std::string, int32_t>("Black", 0x000000FF)); colorPresets.insert(std::pair<std::string, int32_t>("White", 0xFFFFFFFF)); } void RichText::Update(float delta) { wavyAngle -= 0.3; } void RichText::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); int x = renderPosition.x, y = renderPosition.y; std::vector<int32_t> colorStack; sf::Color formatColor = sf::Color(255, 255, 255); bool cancelNext = false; float localWavyAngle = wavyAngle; for (int i = 0; i < rawText.size(); i++) { bool verifiedTag = false; switch (rawText.at(i)) { case '\n': y += (font->GetGlyph('A').texture.height + font->GetGlyph('A').offset + (monospacing == -1 ? 5 : monospacing * 2)) * scale; x = renderPosition.x; verifiedTag = true; break; case '\\': if (!ignoreTags) { if ((size_t)i + 1 < rawText.size()) { if (rawText[(size_t)i + 1] == 'i') { y += (font->GetGlyph('A').texture.height + font->GetGlyph('A').offset) * scale; if (monospacing == -1) { x = renderPosition.x + (font->GetGlyph('*').shift + font->GetGlyph(' ').shift) * scale; } else { x = renderPosition.x + (font->GetGlyph('*').texture.width + font->GetGlyph(' ').texture.width + monospacing * 2) * scale; } i += 1; verifiedTag = true; break; } } cancelNext = true; verifiedTag = true; } break; case '[': if (!cancelNext && !ignoreTags) { std::string temp = rawText.substr((size_t)i + 1, rawText.substr((size_t)i + 1).find_first_of(']')); std::string tempData = temp.substr(temp.find_first_of(":") + 1); bool verifiedTag = false; if (temp[0] == 'c') { if (colorPresets.count(tempData)) { formatColor = sf::Color(colorPresets.at(tempData)); colorStack.push_back(colorPresets.at(tempData)); } else { int32_t hexColor = std::stoul((tempData.length() < 8) ? tempData + "FF" : tempData, 0, 16); formatColor = sf::Color(hexColor); colorStack.push_back(hexColor); } } else if (temp[0] == '/') { if (temp[1] == 'c') { if (colorStack.size() > 1) { colorStack.pop_back(); formatColor = sf::Color((colorStack.back())); } else { formatColor = sf::Color(255, 255, 255); } } } i += temp.length() + 2; verifiedTag = true; } else { cancelNext = false; } break; default: break; } if (verifiedTag) { continue; } if(i < rawText.length() && font->HasGlyph(rawText.at(i))) { sf::Vector2f localRenderOffset = { 0, 0 }; if (textTypeFlags & static_cast<char>(TextType::Shaky)) { localRenderOffset.x += (std::rand() % 2 + 1) - (std::rand() % 2 + 1); localRenderOffset.y += (std::rand() % 2 + 1) - (std::rand() % 2 + 1); } if (textTypeFlags & static_cast<char>(TextType::Wavy)) { localRenderOffset.x += (std::cos(localWavyAngle) * 0.75); localRenderOffset.y += (std::sin(localWavyAngle) * 1.75); } auto glyph = font->GetGlyph(rawText.at(i)); auto sprite = font->GetGlyphSprite(rawText.at(i)); sprite.setPosition(x + localRenderOffset.x, y + localRenderOffset.y); sprite.setScale({ scale, scale }); sprite.color = formatColor; if (monospacing == -1) { x += (glyph.shift) * scale; } else { x += (glyph.texture.width + monospacing) * scale; } localWavyAngle--; target.draw(sprite, states); } } } }
34.077778
153
0.3955
ApertaTeam
636cb1c86daef7a48964faa4c74f074c64edc9d1
306
hpp
C++
math/totient.hpp
matumoto1234/library
a2c80516a8afe5876696c139fe0e837d8a204f69
[ "Unlicense" ]
2
2021-06-24T11:21:08.000Z
2022-03-15T05:57:25.000Z
math/totient.hpp
matumoto1234/library
a2c80516a8afe5876696c139fe0e837d8a204f69
[ "Unlicense" ]
102
2021-10-30T21:30:00.000Z
2022-03-26T18:39:47.000Z
math/totient.hpp
matumoto1234/library
a2c80516a8afe5876696c139fe0e837d8a204f69
[ "Unlicense" ]
null
null
null
#pragma once #include "./base.hpp" namespace math { ll totient(ll n) { ll res = n; for (ll i = 2; i * i <= n; i++) { if (n % i == 0) { res -= res / i; while (n % i == 0) n /= i; } } if (n > 1) res -= res / n; return res; } } // namespace math
17
37
0.395425
matumoto1234
636fabe2c052b4b43579806cf9463cf3c67c6d95
466
cpp
C++
detail/os/reactor/iocp/wsa_activator.cpp
wembikon/baba.io
87bec680c1febb64356af59e7e499c2b2b64d30c
[ "MIT" ]
null
null
null
detail/os/reactor/iocp/wsa_activator.cpp
wembikon/baba.io
87bec680c1febb64356af59e7e499c2b2b64d30c
[ "MIT" ]
1
2020-06-12T10:22:09.000Z
2020-06-12T10:22:09.000Z
detail/os/reactor/iocp/wsa_activator.cpp
wembikon/baba.io
87bec680c1febb64356af59e7e499c2b2b64d30c
[ "MIT" ]
null
null
null
/** * MIT License * Copyright (c) 2020 Adrian T. Visarra **/ #include "os/reactor/iocp/wsa_activator.h" #include "baba/logger.h" #include <cstdlib> namespace baba::os { wsa_activator::wsa_activator() : _data{0} { if (int result = WSAStartup(MAKEWORD(2, 2), &_data); result != 0) { LOGFTL("WSAStartup() failed. result={}", result); std::abort(); } } wsa_activator::~wsa_activator() { WSACleanup(); } } // namespace baba::os
20.26087
70
0.61588
wembikon
6372daa8a7657bd5527e7d405f63b87b60020e6d
1,775
cpp
C++
Dataset/Leetcode/train/13/890.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/13/890.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/13/890.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: int XXX(string s) { int temp1=0; int temp=0; int sum =0; for(int i=0; i<s.length();i++) { switch(s[i]) { case 'I': temp=1; if(i<(s.length()-1)&&s[i+1]=='V') { temp=4; i++; } if(i<(s.length()-1)&&s[i+1]=='X') { temp=9; i++; } break; case 'V': temp=5; break; case 'X': temp=10; if(i<(s.length()-1)&&s[i+1]=='L') { temp=40; i++; } if(i<(s.length()-1)&&s[i+1]=='C') { temp=90; i++; } break; case 'L': temp=50; break; case 'C': temp=100; if(i<(s.length()-1)&&s[i+1]=='D') { temp=400; i++; } if(i<(s.length()-1)&&s[i+1]=='M') { temp=900; i++; } break; case 'D': temp=500; break; case 'M': temp=1000; break; } sum=sum+temp; } return sum; } };
23.051948
53
0.19493
kkcookies99
63764c869d04378fabcef48ae6faa69e5a49aa8b
963
hpp
C++
src/Homie/Boot/BootConfig.hpp
neo164/wi-fi-iot
dad284b235c5540897585e81c56be58136121b52
[ "MIT" ]
null
null
null
src/Homie/Boot/BootConfig.hpp
neo164/wi-fi-iot
dad284b235c5540897585e81c56be58136121b52
[ "MIT" ]
null
null
null
src/Homie/Boot/BootConfig.hpp
neo164/wi-fi-iot
dad284b235c5540897585e81c56be58136121b52
[ "MIT" ]
null
null
null
#pragma once #include <functional> #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #include <DNSServer.h> #include <ArduinoJson.h> #include "Boot.hpp" #include "../Config.hpp" #include "../Constants.hpp" #include "../Limits.hpp" #include "../Datatypes/Interface.hpp" #include "../Timer.hpp" #include "../Helpers.hpp" #include "../Logger.hpp" #include "../Strings.hpp" namespace HomieInternals { class BootConfig : public Boot { public: BootConfig(); ~BootConfig(); void setup(); void loop(); private: ESP8266WebServer _http; DNSServer _dns; unsigned char _ssidCount; bool _wifiScanAvailable; Timer _wifiScanTimer; bool _lastWifiScanEnded; char* _jsonWifiNetworks; bool _flaggedForReboot; unsigned long _flaggedForRebootAt; void _onDeviceInfoRequest(); void _onNetworksRequest(); void _onConfigRequest(); void _generateNetworksJson(); }; }
22.928571
40
0.669782
neo164
637798f0f22b2ed2ed3b8043dd7b9a62996f97a9
10,542
cpp
C++
libs/libsmlibraries/tests/testlibsmlibraries/testbcp47languages.cpp
simonmeaden/EPubEdit
52f4fa0bab9f271db3b06b7d87575cc23a0bdf9c
[ "MIT" ]
null
null
null
libs/libsmlibraries/tests/testlibsmlibraries/testbcp47languages.cpp
simonmeaden/EPubEdit
52f4fa0bab9f271db3b06b7d87575cc23a0bdf9c
[ "MIT" ]
null
null
null
libs/libsmlibraries/tests/testlibsmlibraries/testbcp47languages.cpp
simonmeaden/EPubEdit
52f4fa0bab9f271db3b06b7d87575cc23a0bdf9c
[ "MIT" ]
null
null
null
#include "testbcp47languages.h" namespace { BCP47LanguagesTest::BCP47LanguagesTest() : configDir( QDir(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation))) , libraryDir(QDir(Paths::join( QStandardPaths::writableLocation(QStandardPaths::AppDataLocation), "library"))) , configFile( QFile(Paths::join(configDir.path(), "epubedit", "languages.yaml"))) {} void BCP47LanguagesTest::SetUp() { languages.readFromLocalFile(configFile); } void BCP47LanguagesTest::TearDown() {} TEST_F(BCP47LanguagesTest, FileLoaded) { auto date = languages.fileDate(); ASSERT_TRUE(date.toString(Qt::ISODate) == "2021-08-06"); } TEST_F(BCP47LanguagesTest, Languages) { // Nonexistant language auto language = languages.languageFromDescription("Arrrrgh"); ASSERT_TRUE(language.isNull()); language = languages.languageFromDescription("Abkhazian"); ASSERT_FALSE(language.isNull()) << "Language not empty"; ASSERT_TRUE(language->type() == BCP47Language::LANGUAGE); ASSERT_TRUE(language->subtag() == "ab"); ASSERT_TRUE(language->description() == "Abkhazian"); ASSERT_TRUE(language->dateAdded().toString(Qt::ISODate) == "2005-10-16"); ASSERT_TRUE(language->suppressScriptLang() == "Cyrl"); ASSERT_TRUE(language->macrolanguageName() == ""); language = languages.languageFromDescription("Chuanqiandian Cluster Miao"); ASSERT_FALSE(language.isNull()) << "Language not empty"; ASSERT_TRUE(language->type() == BCP47Language::LANGUAGE); ASSERT_TRUE(language->subtag() == "cqd"); ASSERT_TRUE(language->description() == "Chuanqiandian Cluster Miao"); ASSERT_TRUE(language->dateAdded().toString(Qt::ISODate) == "2009-07-29"); ASSERT_TRUE(language->suppressScriptLang() == ""); ASSERT_TRUE(language->macrolanguageName() == "hmn"); // Multi description languages. Both descriptions should point to // the same BCP47Language node. language = languages.languageFromDescription("Bengali"); auto language2 = languages.languageFromDescription("Bangla"); ASSERT_TRUE(language == language2); ASSERT_FALSE(language.isNull()) << "Language not empty"; ASSERT_TRUE(language->type() == BCP47Language::LANGUAGE); ASSERT_TRUE(language->subtag() == "bn"); ASSERT_TRUE(language->descriptions().at(0) == "Bengali"); ASSERT_TRUE(language->descriptions().at(1) == "Bangla"); ASSERT_TRUE(language->dateAdded().toString(Qt::ISODate) == "2005-10-16"); ASSERT_TRUE(language->suppressScriptLang() == "Beng"); ASSERT_TRUE(language->macrolanguageName() == ""); // // Multi value script language = languages.languageFromDescription("Church Slavic"); ASSERT_FALSE(language.isNull()) << "Language not empty"; ASSERT_TRUE(language->type() == BCP47Language::LANGUAGE); ASSERT_TRUE(language->subtag() == "cu"); ASSERT_TRUE(language->description() == "Church Slavic"); ASSERT_TRUE(language->dateAdded().toString(Qt::ISODate) == "2005-10-16"); // No suppress script lang for this item ASSERT_TRUE(language->suppressScriptLang() == ""); ASSERT_TRUE(language->macrolanguageName() == ""); for (auto& description : language->descriptions()) { if (description == "Naxi Geba") continue; language2 = languages.languageFromDescription(description); ASSERT_TRUE(language == language2); } } TEST_F(BCP47LanguagesTest, Scripts) { // // Multi value script auto language = languages.scriptFromDescription("Naxi Geba"); ASSERT_FALSE(language.isNull()) << "Language not empty"; ASSERT_TRUE(language->type() == BCP47Language::SCRIPT); ASSERT_TRUE(language->subtag() == "Nkgb"); ASSERT_TRUE(language->description() == "Naxi Geba"); ASSERT_TRUE(language->dateAdded().toString(Qt::ISODate) == "2009-03-13"); // No suppress script lang for this item ASSERT_TRUE(language->suppressScriptLang() == ""); for (auto& description : language->descriptions()) { if (description == "Naxi Geba") continue; auto language2 = languages.scriptFromDescription(description); ASSERT_TRUE(language == language2); } } TEST_F(BCP47LanguagesTest, Variants) { // // Multi value script auto language = languages.variantFromDescription("ALA-LC Romanization, 1997 edition"); ASSERT_FALSE(language.isNull()) << "Language not empty"; ASSERT_TRUE(language->type() == BCP47Language::VARIANT); ASSERT_TRUE(language->subtag() == "alalc97"); ASSERT_TRUE(language->description() == "ALA-LC Romanization, 1997 edition"); ASSERT_TRUE(language->dateAdded().toString(Qt::ISODate) == "2009-12-09"); // No suppress script lang for this item ASSERT_TRUE(language->suppressScriptLang() == ""); ASSERT_TRUE(language->macrolanguageName() == ""); ASSERT_TRUE( language->comments() == "Romanizations recommended by the American Library Association\n and the " "Library of Congress, in \"ALA-LC Romanization Tables:\n Transliteration " "Schemes for Non-Roman Scripts\" (1997), ISBN\n 978-0-8444-0940-5."); } TEST_F(BCP47LanguagesTest, PrimaryLanguage) { auto values = languages.languageDescriptions(); ASSERT_FALSE(values.isEmpty()); for (auto& name : values) { // First check that all of the names have an associated language. auto language = languages.languageFromDescription(name); ASSERT_FALSE(language.isNull()); ASSERT_TRUE(language->type() == BCP47Language::LANGUAGE) << QObject::tr("Language: %1, %2") .arg(language->typeString(), language->description()) .toStdString(); } values = languages.languageSubtags(); ASSERT_FALSE(values.isEmpty()); for (auto& subtag : values) { // First check that all of the names have an associated language. auto language = languages.languageFromSubtag(subtag); ASSERT_FALSE(language.isNull()); ASSERT_TRUE(language->type() == BCP47Language::LANGUAGE) << QObject::tr("Language: %1, %2") .arg(language->typeString(), language->description()) .toStdString(); } auto language = languages.languageFromSubtag("alu"); ASSERT_FALSE(language.isNull()); } TEST_F(BCP47LanguagesTest, Region) { auto values = languages.regionDescriptions(); ASSERT_FALSE(values.isEmpty()); for (auto& name : values) { // First check that all of the names have an associated regions. auto language = languages.regionFromDescription(name); ASSERT_FALSE(language.isNull()); ASSERT_TRUE(language->type() == BCP47Language::REGION); } values = languages.regionSubtags(); ASSERT_FALSE(values.isEmpty()); for (auto& subtag : values) { // First check that all of the names have an associated language. auto language = languages.regionFromSubtag(subtag); ASSERT_FALSE(language.isNull()); ASSERT_TRUE(language->type() == BCP47Language::REGION); } } TEST_F(BCP47LanguagesTest, Variant) { auto values = languages.variantDescriptions(); ASSERT_FALSE(values.isEmpty()); for (auto& name : values) { // First check that all of the names have an associated variant. auto language = languages.variantFromDescription(name); ASSERT_FALSE(language.isNull()); ASSERT_TRUE(language->type() == BCP47Language::VARIANT); } values = languages.variantSubtags(); ASSERT_FALSE(values.isEmpty()); for (auto& subtag : values) { // First check that all of the names have an associated language. auto language = languages.variantFromSubtag(subtag); ASSERT_FALSE(language.isNull()); ASSERT_TRUE(language->type() == BCP47Language::VARIANT); } } TEST_F(BCP47LanguagesTest, ExtLang) { auto values = languages.extlangDescriptions(); ASSERT_FALSE(values.isEmpty()); for (auto& name : values) { // First check that all of the names have an associated extlang. auto language = languages.extlangFromDescription(name); ASSERT_FALSE(language.isNull()); ASSERT_TRUE(language->type() == BCP47Language::EXTLANG); } values = languages.extlangSubtags(); ASSERT_FALSE(values.isEmpty()); for (auto& subtag : values) { // First check that all of the names have an associated language. auto language = languages.extlangFromSubtag(subtag); ASSERT_FALSE(language.isNull()); ASSERT_TRUE(language->type() == BCP47Language::EXTLANG); } } TEST_F(BCP47LanguagesTest, Script) { auto values = languages.scriptDescriptions(); ASSERT_FALSE(values.isEmpty()); for (auto& name : values) { // First check that all of the names have an associated extlang. auto language = languages.scriptFromDescription(name); ASSERT_FALSE(language.isNull()); ASSERT_TRUE(language->type() == BCP47Language::SCRIPT); } values = languages.scriptSubtags(); ASSERT_FALSE(values.isEmpty()); for (auto& subtag : values) { // First check that all of the names have an associated language. auto language = languages.scriptFromSubtag(subtag); ASSERT_FALSE(language.isNull()); ASSERT_TRUE(language->type() == BCP47Language::SCRIPT); } } TEST_F(BCP47LanguagesTest, Grandfathered) { auto values = languages.grandfatheredDescriptions(); ASSERT_FALSE(values.isEmpty()); for (auto& name : values) { // First check that all of the names have an associated extlang. auto language = languages.grandfatheredFromDescription(name); ASSERT_FALSE(language.isNull()); ASSERT_TRUE(language->type() == BCP47Language::GRANDFATHERED); } values = languages.grandfatheredTags(); ASSERT_FALSE(values.isEmpty()); for (auto& subtag : values) { // First check that all of the names have an associated language. auto language = languages.grandfatheredFromTag(subtag); ASSERT_FALSE(language.isNull()); ASSERT_TRUE(language->type() == BCP47Language::GRANDFATHERED); } } TEST_F(BCP47LanguagesTest, Redundant) { auto values = languages.redundantDescriptions(); ASSERT_FALSE(values.isEmpty()); for (auto& name : values) { // First check that all of the names have an associated extlang. auto language = languages.redundantFromDescription(name); ASSERT_FALSE(language.isNull()); ASSERT_TRUE(language->type() == BCP47Language::REDUNDANT); } values = languages.redundantTags(); ASSERT_FALSE(values.isEmpty()); for (auto& subtag : values) { // First check that all of the names have an associated language. auto language = languages.redundantFromTag(subtag); ASSERT_FALSE(language.isNull()); ASSERT_TRUE(language->type() == BCP47Language::REDUNDANT); } } TEST_F(BCP47LanguagesTest, TestPrimaryLanguage) { auto types = languages.isPrimaryLanguage("en"); types = languages.isPrimaryLanguage("EN"); } } // end of anonymous namespace
36.477509
80
0.712294
simonmeaden
6377d2fb0384303102edd14d113ae597fddb47db
28,333
hpp
C++
src/matrix.hpp
degarashi/frea
bb598245c2ab710cc816e98d7361e5863af5fd7e
[ "MIT" ]
null
null
null
src/matrix.hpp
degarashi/frea
bb598245c2ab710cc816e98d7361e5863af5fd7e
[ "MIT" ]
null
null
null
src/matrix.hpp
degarashi/frea
bb598245c2ab710cc816e98d7361e5863af5fd7e
[ "MIT" ]
null
null
null
#pragma once #include "vector.hpp" #include "angle.hpp" #include "lubee/src/meta/compare.hpp" #include "lubee/src/ieee754.hpp" #include "exception.hpp" namespace frea { template <class VW, int M> using wrapM_t = wrapM_spec<VW, M, VW::size>; // ベクトル演算レジスタクラスをM方向に束ねたもの /*! \tparam VW 各行のベクトル型 \tparam M 行数 \tparam S 本来の型 */ template <class VW, int M, class S> class wrapM : public lubee::op::PlusMinus<S>, public lubee::op::Ne<S> { public: using op_t = lubee::op::PlusMinus<S>; constexpr static bool is_integral = VW::is_integral; constexpr static int dim_m = M, dim_n = VW::size, dim_min = lubee::Arithmetic<dim_m, dim_n>::less, bit_width = VW::bit_width; using Chk_SizeM = std::enable_if_t<(dim_m>0)>*; using spec_t = S; using vec_t = VW; using value_t = typename vec_t::value_t; using column_t = typename vec_t::template type_cn<dim_m>; //! 要素数の読み替え template <int M2, int N2> using type_cn = wrapM_t<typename vec_t::template type_cn<N2>, M2>; private: template <class Dst, class Vec, class WM, int N> static void _MultipleLine(Dst&, const Vec&, const WM&, lubee::IConst<N>, lubee::IConst<N>) noexcept {} template <class Dst, class Vec, class WM, int N, int Z> static void _MultipleLine(Dst& dst, const Vec& v, const WM& m, lubee::IConst<N>, lubee::IConst<Z>) noexcept { const auto val = v.template pickAt<N>(); const Dst tv(val); dst += tv * m.v[N]; _MultipleLine(dst, v, m, lubee::IConst<N+1>(), lubee::IConst<Z>()); } template <int At, std::size_t... Idx> auto _getColumn(std::index_sequence<Idx...>) const noexcept { return column_t((v[Idx].template pickAt<At>())...); } template <int At, std::size_t... Idx> void _setColumn(const column_t& c, std::index_sequence<Idx...>) noexcept { const auto dummy = [](auto&&...){}; dummy(((v[Idx].template setAt<At>(c.template pickAt<Idx>())), 0)...); } template <class... Ts> static void _Dummy(Ts&&...) noexcept {} template <std::size_t... Idx, std::size_t... IdxE> static spec_t _Diagonal(const value_t& v, std::index_sequence<Idx...>, std::index_sequence<IdxE...>) noexcept { spec_t ret; _Dummy((ret.v[Idx].template initAt<Idx>(v), 0)...); _Dummy((ret.v[IdxE+dim_min] = vec_t::Zero())...); return ret; } template <class VW2, int N2, class S2> auto _mul(const wrapM<VW2,N2,S2>& m, std::true_type) const noexcept { using WM = std::decay_t<decltype(m)>; static_assert(WM::dim_m == dim_n, ""); wrapM_t<VW2, dim_m> ret; // 一旦メモリに展開する(m -> other) value_t other[WM::dim_m][WM::dim_n]; for(int i=0 ; i<WM::dim_m ; i++) m.v[i].template store<false>(other[i], lubee::IConst<WM::dim_n-1>()); for(int i=0 ; i<dim_m ; i++) { value_t result[WM::dim_n] = {}, ths[dim_n]; // メモリに展開(this[i] -> ths) v[i].template store<false>(ths, lubee::IConst<dim_n-1>()); for(int j=0 ; j<WM::dim_n ; j++) { auto& dst = result[j]; for(int k=0 ; k<dim_n ; k++) dst += ths[k] * other[k][j]; } // 結果を書き込み ret.v[i] = VW2(result, std::false_type()); } return ret; } template <class VW2, int N2, class S2> auto _mul(const wrapM<VW2,N2,S2>& m, std::false_type) const noexcept { using WM = std::decay_t<decltype(m)>; static_assert(WM::dim_m == dim_n, ""); wrapM_t<VW2, dim_m> ret; for(int i=0 ; i<dim_m ; i++) { ret.v[i] = VW2::Zero(); _MultipleLine(ret.v[i], v[i], m, lubee::IConst<0>(), lubee::IConst<WM::dim_m>()); } return ret; } template <std::size_t... Idx, ENABLE_IF(sizeof...(Idx) == dim_m)> column_t _mul_vecR(std::index_sequence<Idx...>, const vec_t& vc) const noexcept { return column_t(v[Idx].dot(vc)...); } template <std::size_t... Idx, ENABLE_IF(sizeof...(Idx) == dim_n)> auto _mul_vecL(std::index_sequence<Idx...>, const column_t& vc) const noexcept { vec_t ret = vec_t::Zero(); _MultipleLine(ret, vc, *this, lubee::IConst<0>(), lubee::IConst<dim_m>()); return ret; } public: vec_t v[dim_m]; wrapM() = default; template <bool A> wrapM(const value_t* src, lubee::BConst<A>) noexcept { for(int i=0 ; i<dim_m ; i++) { v[i] = vec_t(src, lubee::BConst<A>()); src += A ? vec_t::capacity : vec_t::size; } } decltype(auto) operator [] (const int n) noexcept { return v[n]; } decltype(auto) operator [] (const int n) const noexcept { return v[n]; } #define DEF_OP2(op) \ template <class T, \ ENABLE_IF((HasMethod_asInternal_t<T>{}))> \ auto operator op (const T& t) const noexcept { \ return *this op t.asInternal(); \ } #define DEF_OP(op) \ DEF_OP2(op) \ template <class VW2, class S2> \ spec_t operator op (const wrapM<VW2,M,S2>& m) const noexcept { \ spec_t ret; \ for(int i=0 ; i<dim_m ; i++) \ ret.v[i] = v[i] op m.v[i]; \ return ret; \ } \ spec_t operator op (const value_t& t) const noexcept { \ spec_t ret; \ const vec_t tmp(t); \ for(int i=0 ; i<dim_m ; i++) \ ret.v[i] = v[i] op tmp; \ return ret; \ } \ using op_t::operator op; DEF_OP(+) DEF_OP(-) #undef DEF_OP DEF_OP2(*) DEF_OP2(/) #undef DEF_OP2 template <class VW2, class S2> spec_t& operator = (const wrapM<VW2,dim_m,S2>& m) noexcept { for(int i=0 ; i<dim_m ; i++) v[i] = m.v[i]; return *this; } auto operator * (const value_t& t) const noexcept { spec_t ret; vec_t tmp(t); for(int i=0 ; i<dim_m ; i++) ret.v[i] = v[i] * tmp; return ret; } template <class T = value_t, ENABLE_IF(std::is_floating_point<T>{})> auto operator / (const value_t& t) const noexcept { return *this * (1 / t); } template <class T = value_t, ENABLE_IF(std::is_integral<T>{})> auto operator / (const value_t& t) const noexcept { spec_t ret; const vec_t tmp(t); for(int i=0 ; i<dim_m ; i++) ret.v[i] = v[i] / tmp; return ret; } template <class Wr, ENABLE_IF(is_wrapM<Wr>{})> auto operator * (const Wr& m) const noexcept { return _mul(m, IsTuple_t<typename Wr::vec_t>()); } // 右からベクトルを掛ける column_t operator * (const vec_t& vc) const noexcept { return _mul_vecR(std::make_index_sequence<dim_m>(), vc); } // 左からベクトルを掛ける auto _pre_mul(const column_t& vc) const noexcept { return _mul_vecL(std::make_index_sequence<dim_n>(), vc); } bool operator == (const wrapM& m) const noexcept { for(int i=0 ; i<dim_m ; i++) { if(v[i] != m.v[i]) return false; } return true; } template <class VD> void store(VD* dst) const noexcept { for(auto& t : v) { t.template store<VD::align>(dst->m, lubee::IConst<dim_n-1>()); ++dst; } } template <int N2> constexpr static bool same_capacity = type_cn<dim_m, N2>::vec_t::capacity == vec_t::capacity; // そのままポインタの読み変えが出来るケース template <int ToM, int ToN, ENABLE_IF((ToM<=dim_m && ToN<=dim_n && same_capacity<ToN>))> decltype(auto) convert() const noexcept { return reinterpret_cast<const type_cn<ToM, ToN>&>(*this); } template <int ToM, int ToN, ENABLE_IF((ToM<=dim_m && ToN<=dim_n && same_capacity<ToN>))> decltype(auto) convertI(const value_t&) const noexcept { return convert<ToM, ToN>(); } // 大きいサイズへの変換 // 隙間をゼロで埋める template <int ToM, int ToN, ENABLE_IF((ToM>dim_m || ToN>dim_n || !same_capacity<ToN>))> auto convert() const noexcept { using ret_t = type_cn<ToM, ToN>; ret_t ret; for(int i=0 ; i<dim_m ; i++) ret.v[i] = v[i].template convert<ToN>(); for(int i=dim_m ; i<ToM ; i++) ret.v[i] = ret_t::vec_t::Zero(); return ret; } // 大きいサイズへの変換 // 隙間をゼロで埋め、対角成分のみ任意の値を書き込む template <int ToM, int ToN, ENABLE_IF((ToM>dim_m || ToN>dim_n || !same_capacity<ToN>))> auto convertI(const value_t& v) const noexcept { using ret_t = type_cn<ToM, ToN>; auto ret = ret_t::Diagonal(v); for(int i=0 ; i<dim_m ; i++) ret.v[i] = ret.v[i].template maskL<dim_n-1>() | this->v[i].template convert<ToN>(); return ret; } static spec_t Identity() noexcept { return Diagonal(1); } static spec_t Diagonal(const value_t& v) noexcept { return _Diagonal(v, std::make_index_sequence<dim_min>(), std::make_index_sequence<dim_m-dim_min>() ); } template <int At> const auto& getRow() const noexcept { static_assert(At < dim_m, "invalid position"); return v[At]; } template <int At> auto& getRow() noexcept { static_assert(At < dim_m, "invalid position"); return v[At]; } template <int At> auto getColumn() const noexcept { static_assert(At < dim_n, "invalid position"); return _getColumn<At>(std::make_index_sequence<dim_m>()); } template <int At> void setRow(const vec_t& r) noexcept { static_assert(At < dim_m, "invalid position"); v[At] = r; } template <int At> void setColumn(const column_t& c) noexcept { static_assert(At < dim_n, "invalid position"); _setColumn<At>(c, std::make_index_sequence<dim_m>()); } bool isZero(const value_t& th) const noexcept { for(int i=0 ; i<dim_m ; i++) { if(!v[i].isZero(th)) return false; } return true; } void linearNormalize() noexcept { *this = linearNormalization(); } spec_t linearNormalization() const noexcept { spec_t ret; for(int i=0 ; i<dim_m ; i++) ret.v[i] = v[i].linearNormalization(); return ret; } }; template <class VW, int M, int N> struct wrapM_spec : wrapM<VW, M, wrapM_spec<VW,M,N>> { using base_t = wrapM<VW, M, wrapM_spec<VW,M,N>>; using base_t::base_t; wrapM_spec() = default; wrapM_spec(const base_t& b): base_t(b) {} }; #define DEF_FUNC(cls, name, nameC) \ void name() noexcept(noexcept(std::declval<cls>().nameC())) { \ *this = nameC(); \ } template <class R, int M, int N, bool A> using SMat_t = MatT_spec<SVec_t<R, N, A>, M, N>; template <class T, int M, int N> using RMat_t = MatT_spec<RVec_t<T, N>, M, N>; template <class T, int M, int N, bool A> using Mat_t = MatT_spec<Vec_t<T, N, A>, M, N>; //! 正方行列のみのメンバ関数を定義 template <class VW, int S> class wrapM_spec<VW,S,S> : public wrapM<VW, S, wrapM_spec<VW,S,S>> { private: using base_t = wrapM<VW, S, wrapM_spec<VW,S,S>>; using this_t = wrapM_spec; public: using value_t = typename base_t::value_t; private: using mat_t = Mat_t<value_t, base_t::dim_m, base_t::dim_n, true>; // InfoにTranspose関数が用意されていればtrue template <class VW2, std::size_t... Idx, class B, class = decltype(VW2::I::Transpose(std::declval<B>().v[Idx].m...))> static std::true_type hasmem(std::index_sequence<Idx...>); // そうでなければfalse template <class VW2, class B> static std::false_type hasmem(...); //! 効率の良い転置アルゴリズムが使用可能な場合はそれを使用 template <std::size_t... Idx> auto _transposition(std::true_type, std::index_sequence<Idx...>) const noexcept { auto ret = *this; VW::I::Transpose((ret.v[Idx].m)...); return ret; } //! 効率の良い転置アルゴリズムが定義されていない場合は地道に要素を交換する template <std::size_t... Idx> auto _transposition(std::false_type, std::index_sequence<Idx...>) const noexcept { typename base_t::value_t tmp[S][S]; const auto dummy = [](auto...) {}; dummy((base_t::v[Idx].template store<false>(tmp[Idx], lubee::IConst<base_t::dim_n-1>()), 0)...); dummy(([&tmp](const int i){ for(int j=i+1 ; j<base_t::dim_n ; j++) { std::swap(tmp[i][j], tmp[j][i]); } }(Idx), 0)...); return this_t((const typename base_t::value_t*)tmp, std::false_type()); } public: using vec_t = typename base_t::vec_t; using base_t::base_t; wrapM_spec() = default; wrapM_spec(const base_t& b): base_t(b) {} auto transposition() const& noexcept { const auto idx = std::make_index_sequence<S>(); return _transposition(decltype(this->hasmem<VW, base_t>(idx))(), idx); } // ----------- アダプタ関数群 ----------- value_t calcDeterminant() const noexcept { return mat_t(*this).calcDeterminant(); } this_t inversion() const { return mat_t(*this).inversion(); } this_t inversion(const value_t& det) const { return mat_t(*this).inversion(det); } DEF_FUNC(wrapM_spec, inverse, inversion) DEF_FUNC(wrapM_spec, transpose, transposition) }; #undef DEF_FUNC template <bool C, class T> using ConstIf = std::conditional_t<C, std::add_const_t<T>, T>; template <class D, bool C> class ItrM : public std::iterator< std::input_iterator_tag, ConstIf<C, typename D::value_t> > { private: using base_t = std::iterator<std::input_iterator_tag, ConstIf<C, typename D::value_t>>; using D_t = ConstIf<C, D>; D_t& _target; int _cursor; constexpr static int dim_n = D::dim_n; public: ItrM(D_t& t, const int cur) noexcept: _target(t), _cursor(cur) {} typename base_t::reference operator * () const noexcept { return _target.m[_cursor/dim_n][_cursor%dim_n]; } ItrM& operator ++ () noexcept { ++_cursor; return *this; } ItrM operator ++ (int) noexcept { const int cur = _cursor++; return ItrM(_target, cur); } typename base_t::pointer operator -> () const noexcept { return &(*this); } bool operator == (const ItrM& itr) const noexcept { return _cursor == itr._cursor; } bool operator != (const ItrM& itr) const noexcept { return _cursor != itr._cursor; } }; template <class V, int M> class DataM { public: using value_t = typename V::value_t; using vec_t = V; constexpr static int dim_m = M, dim_n = vec_t::size, bit_width = vec_t::bit_width; constexpr static bool align = vec_t::align, is_integral = vec_t::is_integral; using column_t = typename vec_t::template type_cn<dim_m>; private: void _init(vec_t*) noexcept {} template <class... Ts> void _init(vec_t* dst, const vec_t& v, const Ts&... ts) noexcept { *dst = v; _init(dst+1, ts...); } template <std::size_t... Idx> void _initA(std::index_sequence<Idx...>, const value_t *src) noexcept { static_assert(sizeof...(Idx) == dim_n, ""); for(int i=0 ; i<dim_m ; i++) { m[i] = vec_t(src[Idx]...); src += dim_n; } } template <class Ar, class V2, int M2> friend void serialize(Ar&, DataM<V2,M2>&); public: vec_t m[dim_m]; DataM() = default; // --- iterator interface --- auto begin() noexcept { return ItrM<DataM, false>(*this, 0); } auto end() noexcept { return ItrM<DataM, false>(*this, dim_m*dim_n); } auto begin() const noexcept { return ItrM<DataM, true>(*this, 0); } auto end() const noexcept { return ItrM<DataM, true>(*this, dim_m*dim_n); } auto cbegin() const noexcept { return ItrM<DataM, true>(*this, 0); } auto cend() const noexcept { return ItrM<DataM, true>(*this, dim_m*dim_n); } vec_t& operator [](const int n) noexcept { return m[n]; } const vec_t& operator [](const int n) const noexcept { return m[n]; } // vec_tの配列[dim_m]で初期化 template <class... Ts, ENABLE_IF((sizeof...(Ts)==dim_m))> DataM(const Ts&... ts) noexcept { _init(m, ts...); } // value_tの配列で初期化 template <class... Ts, ENABLE_IF((sizeof...(Ts)==dim_m*dim_n))> DataM(const Ts&... ts) noexcept { const value_t tmp[dim_m*dim_n] = {static_cast<value_t>(ts)...}; _initA(std::make_index_sequence<dim_n>(), tmp); } // 全て同一のvalue_tで初期化 explicit DataM(const value_t& t0) noexcept { vec_t tmp(t0); for(auto& v : m) v = tmp; } // from 内部形式 DataM(const wrapM_spec<typename V::wrap_t, M, V::size>& w) noexcept { w.store(m); } std::ostream& print(std::ostream& os) const { os << '['; bool bF = true; for(int i=0 ; i<dim_m ; i++) { if(!bF) os << ", "; this->m[i].print(os); bF = false; } return os << ']'; } }; #define AsI(t) wrap_t(reinterpret_cast<const value_t*>((t).m), lubee::BConst<align>()) template <class V, int M, class S> struct MatT : DataM<V,M>, lubee::op::Operator_Ne<S> { using op_t = lubee::op::Operator_Ne<S>; using spec_t = S; using base_t = DataM<V,M>; using base_t::base_t; using vec_t = V; using wrap_t = wrapM_t<typename V::wrap_t, M>; using value_t = typename V::value_t; constexpr static int dim_m = base_t::dim_m, dim_n = base_t::dim_n, dim_min = lubee::Arithmetic<dim_m,dim_n>::less; constexpr static int size = dim_m, lower_size = dim_n; constexpr static bool align = base_t::align; using column_t = typename V::template type_cn<dim_m>; using vec_min = typename vec_t::template type_cn<dim_min>; using Chk_SizeM = std::enable_if_t<(dim_m>0)>*; //! 要素数, アラインメントの読み替え template <int M2, int N2, bool A=align> using type_cn = Mat_t<value_t, M2, N2, A>; MatT() = default; constexpr MatT(const base_t& b) noexcept: base_t(b) {} MatT(const wrap_t& w) noexcept { for(int i=0 ; i<dim_m ; i++) base_t::m[i] = w.v[i]; } //! 指定した行と列を省いた物を出力 auto cutRC(const int row, const int clm) const noexcept { type_cn<dim_m-1, dim_n-1> ret; constexpr int width = dim_n, height = dim_m; // 左上 for(int i=0 ; i<row ; i++) { for(int j=0 ; j<clm ; j++) ret.m[i][j] = this->m[i][j]; } // 右上 for(int i=0 ; i<row ; i++) { for(int j=clm+1 ; j<width ; j++) ret.m[i][j-1] = this->m[i][j]; } // 左下 for(int i=row+1 ; i<height ; i++) { for(int j=0 ; j<clm ; j++) ret.m[i-1][j] = this->m[i][j]; } // 右下 for(int i=row+1 ; i<height ; i++) { for(int j=clm+1 ; j<width ; j++) ret.m[i-1][j-1] = this->m[i][j]; } return ret; } // ---------- < 行の基本操作 > ---------- //! 行を入れ替える void rowSwap(const int r0, const int r1) noexcept { std::swap(this->m[r0], this->m[r1]); } //! ある行を定数倍する void rowMul(const int r0, const value_t& s) noexcept { this->m[r0] *= s; } //! ある行を定数倍した物を別の行へ足す void rowMulAdd(const int r0, const value_t& s, const int r1) noexcept { this->m[r1] += this->m[r0] * s; } // ---------- < 列の基本操作 > ---------- //! 列を入れ替える void clmSwap(const int c0, const int c1) noexcept { for(int i=0 ; i<dim_m ; i++) std::swap(this->m[i][c0], this->m[i][c1]); } //! ある列を定数倍する void clmMul(const int c0, const value_t& s) noexcept { for(int i=0 ; i<dim_m ; i++) this->m[i][c0] *= s; } //! ある列を定数倍した物を別の行へ足す void clmMulAdd(const int c0, const value_t& s, const int c1) noexcept { for(int i=0 ; i<dim_m ; i++) this->m[i][c1] += this->m[i][c0] * s; } //! ある行の要素が全てゼロか判定 bool isZeroRow(const int n, const value_t& th) const noexcept { return this->m[n].isZero(th); } bool isZero(const value_t& th) const noexcept { return AsI(*this).isZero(th); } //! 各行を正規化する (最大の係数が1になるように) void linearNormalize() noexcept { *this = AsI(*this).linearNormalization(); } spec_t linearNormalization() const noexcept { return AsI(*this).linearNormalization(); } //! 被約階段行列かどうか判定 bool isEchelon(const value_t& th) const noexcept { int edge = 0; for(int i=0 ; i<dim_m ; i++) { // 前回の行のエッジより左側がゼロ以外ならFalse for(int j=0 ; j<edge ; j++) { if(std::abs(this->m[i][j]) >= th) return false; } // 行の先頭(=1)を探す for(; edge<dim_n ; edge++) { const auto v = this->m[i][edge]; if(std::abs(v) < th) { // ゼロなので更に右を探索 } else if(std::abs(v-1) < th) { // 1なのでここが先頭 break; } else return false; } if(edge < dim_n) { ++edge; } else { // 先頭は既に右端なのでこれ以降の行は全てゼロである if(!this->m[i].isZero(th)) return false; } } return true; } //! 被約階段行列にする /*! \return 0の行数 */ int rowReduce(const value_t& th) noexcept { int rbase = 0, cbase = 0; for(;;) { // 行の先端が0でなく、かつ絶対値が最大の行を探す int idx = -1; value_t absmax = 0; for(int i=rbase ; i<dim_m ; i++) { value_t v = std::abs(this->m[i][cbase]); if(absmax < v) { if(std::abs(v) >= th) { absmax = v; idx = i; } } } if(idx < 0) { // 無かったので次の列へ ++cbase; if(cbase == dim_n) { // 終了 break; } continue; } // 基準行でなければ入れ替え if(idx > rbase) rowSwap(idx, rbase); // 基点で割って1にする rowMul(rbase, 1/this->m[rbase][cbase]); this->m[rbase][cbase] = 1; // 精度の問題で丁度1にならない事があるので強制的に1をセット // 他の行の同じ列を0にする for(int i=0 ; i<dim_m ; i++) { if(i==rbase) continue; value_t scale = -this->m[i][cbase]; rowMulAdd(rbase, scale, i); this->m[i][cbase] = 0; // 上と同じく精度の問題により0をセット } // 次の行,列へ移る ++rbase; ++cbase; if(rbase == dim_m || cbase == dim_n) { // 最後の行まで処理し終わるか,全て0の行しか無ければ終了 break; } } return dim_m - rbase; } static MatT Diagonal(const value_t& v) noexcept { return wrap_t::Diagonal(v); } template <class... Ts, ENABLE_IF((sizeof...(Ts)==dim_min))> static MatT Diagonal(const value_t& v0, const Ts&... ts); static MatT Identity() noexcept { return wrap_t::Diagonal(1); } template <int At> const auto& getRow() const noexcept { static_assert(At < dim_m, "invalid position"); return this->m[At]; } template <int At> auto& getRow() noexcept { static_assert(At < dim_m, "invalid position"); return this->m[At]; } template <int At> column_t getColumn() const noexcept { static_assert(At < dim_n, "invalid position"); column_t ret; for(int i=0 ; i<dim_m ; i++) ret[i] = this->m[i][At]; return ret; } template <int At> void setRow(const vec_t& v) noexcept { static_assert(At < dim_m, "invalid position"); this->m[At] = v; } template <int At> void setColumn(const column_t& c) noexcept { static_assert(At < dim_n, "invalid position"); for(int i=0 ; i<dim_m ; i++) this->m[i][At] = c[i]; } constexpr operator wrap_t() const noexcept { return AsI(*this); } wrap_t asInternal() const noexcept { return AsI(*this); } #define DEF_OP(op) \ template <class Num> \ auto operator op (const Num& num) const noexcept { \ return AsI(*this) op num; \ } \ using op_t::operator op; DEF_OP(+) DEF_OP(-) DEF_OP(*) DEF_OP(/) DEF_OP(&) DEF_OP(|) DEF_OP(^) #undef DEF_OP bool operator == (const MatT& m) const noexcept { return AsI(*this) == m; } // ベクトルを左から掛ける auto _pre_mul(const column_t& vc) const noexcept { return vc * AsI(*this); } static spec_t Translation(const vec_t& v) noexcept { spec_t ret = Identity(); ret.template getRow<dim_m-1>() = v; return ret; } static spec_t Scaling(const vec_min& v) noexcept { spec_t ret(0); for(int i=0 ; i<vec_min::size ; i++) ret.m[i][i] = v[i]; return ret; } //! サイズ変換 //! 足りない要素はゼロで埋める template <int M2, int N2> auto convert() const noexcept { return AsI(*this).template convert<M2,N2>(); } //! サイズ変換 //! 足りない要素はゼロで埋め、対角線上要素を任意の値で初期化 template <int M2, int N2> auto convertI(const value_t& vi) const noexcept { return AsI(*this).template convertI<M2,N2>(vi); } // -------- Luaへのエクスポート用 -------- MatT luaAddF(const float s) const noexcept { return *this + s; } MatT luaAddM(const MatT& m) const noexcept { return *this * m; } MatT luaSubF(const float s) const noexcept { return *this - s; } MatT luaSubM(const MatT& m) const noexcept { return *this - m; } MatT luaMulF(const float s) const noexcept { return *this * s; } MatT luaMulM(const MatT& m) const noexcept { return *this * m; } typename vec_t::template type_cn<dim_m> luaMulV(const vec_t& v) const noexcept { return *this * v; } MatT luaDivF(const float s) const noexcept { return *this / s; } bool luaEqual(const MatT& m) const noexcept { return *this == m; } std::string luaToString() const { return lubee::ToString(*this); } }; #undef AsI template <class V, int M, class S> const int MatT<V,M,S>::size; template <class V, int M, class S> const bool MatT<V,M,S>::align; template <class V, int M, int N, class S> struct MatT_dspec : MatT<V,M,S> { using base_t = MatT<V,M,S>; using base_t::base_t; MatT_dspec() = default; MatT_dspec(const base_t& b): base_t(b) {} }; // 正方行列のみのメンバ関数を定義 template <class V, int N, class S> class MatT_dspec<V,N,N,S> : public MatT<V,N,S> { public: using base_t = MatT<V,N,S>; using base_t::base_t; MatT_dspec() = default; MatT_dspec(const base_t& b): base_t(b) {} using spec_t = S; using value_t = typename V::value_t; using this_t = MatT_dspec; private: value_t _calcDeterminant(lubee::IConst<2>) const noexcept { // 公式で計算 const Mat_t<value_t, 2, 2, false> m(*this); return m[0][0]*m[1][1] - m[0][1]*m[1][0]; } template <int N2, ENABLE_IF((N2>2))> value_t _calcDeterminant(lubee::IConst<N2>) const noexcept { value_t res = 0, s = 1; // 部分行列を使って計算 for(int i=0 ; i<N2 ; i++) { const auto mt = this->cutRC(0,i); res += this->m[0][i] * mt.calcDeterminant() * s; s *= -1; } return res; } spec_t _inversion(const value_t& di, lubee::IConst<2>) const noexcept { spec_t ret; ret.m[0][0] = this->m[1][1] * di; ret.m[1][0] = -this->m[1][0] * di; ret.m[0][1] = -this->m[0][1] * di; ret.m[1][1] = this->m[0][0] * di; return ret; } template <int N2, ENABLE_IF((N2>2))> spec_t _inversion(const value_t& di, lubee::IConst<N2>) const noexcept { spec_t ret; const value_t c_val[2] = {1,-1}; for(int i=0 ; i<base_t::dim_m ; i++) { for(int j=0 ; j<base_t::dim_n ; j++) { auto in_mat = this->cutRC(i,j); const value_t in_di = in_mat.calcDeterminant(); ret.m[j][i] = c_val[(i+j)&1] * in_di * di; } } return ret; } constexpr static auto ZeroThreshold = lubee::Threshold<value_t>(0.6, 1); public: value_t calcDeterminant() const noexcept { return _calcDeterminant(lubee::IConst<base_t::dim_m>()); } spec_t inversion() const { return inversion(calcDeterminant()); } spec_t inversion(const value_t& det) const { constexpr auto Th = ZeroThreshold; if(std::abs(det) < Th) throw NoInverseMatrix(); return _inversion(1/det, lubee::IConst<base_t::dim_m>()); } void invert() { *this = inversion(); } // -------- アダプタ関数群(wrapM) -------- spec_t transposition() const noexcept { return this->asInternal().transposition(); } void transpose() noexcept { *this = transposition(); } // -------- Luaへのエクスポート用 -------- spec_t luaInvert() const { return inversion(); } }; template <class V, int M, int N> struct MatT_spec : MatT_dspec<V,M,N, MatT_spec<V,M,N>> { using base_t = MatT_dspec<V,M,N, MatT_spec<V,M,N>>; using base_t::base_t; MatT_spec() = default; MatT_spec(const base_t& b): base_t(b) {} }; template <class W, ENABLE_IF((is_wrapM<W>{}))> inline std::ostream& operator << (std::ostream& os, const W& w) { const Mat_t<typename W::value_t, W::dim_m, W::dim_n, true> m(w); return os << m; } template <class M, ENABLE_IF((is_matrix<M>{}))> inline std::ostream& operator << (std::ostream& os, const M& m) { os << "Mat" << M::dim_m << M::dim_n << ": "; return m.print(os); } } namespace std { template <class V, int M> struct hash<frea::DataM<V,M>> { std::size_t operator()(const frea::DataM<V,M>& d) const noexcept { const std::hash<typename frea::DataM<V,M>::vec_t> h; std::size_t ret = 0; for(int i=0 ; i<M ; i++) ret ^= h(d.m[i]); return ret; } }; template <class V, int M, int N> struct hash<frea::MatT_spec<V,M,N>> { using mat_t = frea::MatT_spec<V,M,N>; std::size_t operator()(const mat_t& m) const noexcept { using base_t = typename mat_t::base_t::base_t::base_t; return hash<base_t>()(static_cast<const base_t&>(m)); } }; } #include "include/mat_d2.hpp" #include "include/mat_d3.hpp" #include "include/mat_d4.hpp" namespace frea { #if SSE >= 2 #define DEF_RM(n) \ using RMat##n = RMat_t<float, n, n>; DEF_RM(2) DEF_RM(3) DEF_RM(4) #undef DEF_RM #endif #define DEF_M(n) \ using Mat##n = Mat_t<float, n, n, false>; \ using IMat##n = Mat_t<int32_t, n, n, false>; \ using DMat##n = Mat_t<double, n, n, false>; \ using AMat##n = Mat_t<float, n, n, true>; DEF_M(2) DEF_M(3) DEF_M(4) #undef DEF_M }
29.421599
114
0.60156
degarashi
6379528fa1e38bf77ede17d16b81d8d5b6e5f177
334
cpp
C++
2676/2676.cpp14.cpp
isac322/BOJ
35959dd1a63d75ebca9ed606051f7a649d5c0c7b
[ "MIT" ]
14
2017-05-02T02:00:42.000Z
2021-11-16T07:25:29.000Z
2676/2676.cpp14.cpp
isac322/BOJ
35959dd1a63d75ebca9ed606051f7a649d5c0c7b
[ "MIT" ]
1
2017-12-25T14:18:14.000Z
2018-02-07T06:49:44.000Z
2676/2676.cpp14.cpp
isac322/BOJ
35959dd1a63d75ebca9ed606051f7a649d5c0c7b
[ "MIT" ]
9
2016-03-03T22:06:52.000Z
2020-04-30T22:06:24.000Z
#include <cstdio> int main() { int t, n, m; scanf("%d", &t); while (t--) { scanf("%d%d", &n, &m); if (n < 0 || m < 0 || m > n) puts("0"); else if (!m || n == m) puts("1"); else { int dif = m - 1; if (m > n / 2) m = n - 1 - m; for (int i = 0, c = n - 3; i < dif; i++, c -= 2) n += c; printf("%d\n", n); } } }
19.647059
59
0.374251
isac322
6380d83a6ab7344c5e7f4711fa2df71dbf93c7fb
174
cxx
C++
projects/TemplateAnalysis/examples/inspect-autovar/test-005.cxx
ouankou/rose
76f2a004bd6d8036bc24be2c566a14e33ba4f825
[ "BSD-3-Clause" ]
488
2015-01-09T08:54:48.000Z
2022-03-30T07:15:46.000Z
projects/TemplateAnalysis/examples/inspect-autovar/test-005.cxx
WildeGeist/rose
17db6454e8baba0014e30a8ec23df1a11ac55a0c
[ "BSD-3-Clause" ]
174
2015-01-28T18:41:32.000Z
2022-03-31T16:51:05.000Z
projects/TemplateAnalysis/examples/inspect-autovar/test-005.cxx
WildeGeist/rose
17db6454e8baba0014e30a8ec23df1a11ac55a0c
[ "BSD-3-Clause" ]
146
2015-04-27T02:48:34.000Z
2022-03-04T07:32:53.000Z
template <typename T> struct A { void foo() { T v; } }; template <typename T> struct B { typedef T type; }; void bar() { A<float> v; B< A<int> >::type w; }
9.157895
22
0.534483
ouankou
6382661cb6f4376c759b0f4840a3018570268b4d
204
hpp
C++
src/GUI/Console.hpp
370rokas/MediaServer
9a74d2a77a2af499ebf9357c2bdb6e70375ad072
[ "MIT" ]
1
2022-03-11T20:09:27.000Z
2022-03-11T20:09:27.000Z
src/GUI/Console.hpp
370rokas/MediaServer
9a74d2a77a2af499ebf9357c2bdb6e70375ad072
[ "MIT" ]
null
null
null
src/GUI/Console.hpp
370rokas/MediaServer
9a74d2a77a2af499ebf9357c2bdb6e70375ad072
[ "MIT" ]
null
null
null
// // Created by rokas on 3/12/22. // #ifndef WUSEMEDIASERVER_CONSOLE_HPP #define WUSEMEDIASERVER_CONSOLE_HPP class Console { public: void Run(); private: }; #endif //WUSEMEDIASERVER_CONSOLE_HPP
12
36
0.740196
370rokas
63836f176f9bfa85e118a527b5c73e7f8980c5ed
4,501
cpp
C++
src/nnfusion/core/kernels/cuda_gpu/util/gpu_util.cpp
lynex/nnfusion
6332697c71b6614ca6f04c0dac8614636882630d
[ "MIT" ]
639
2020-09-05T10:00:59.000Z
2022-03-30T08:42:39.000Z
src/nnfusion/core/kernels/cuda_gpu/util/gpu_util.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
252
2020-09-09T05:35:36.000Z
2022-03-29T04:58:41.000Z
src/nnfusion/core/kernels/cuda_gpu/util/gpu_util.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
104
2020-09-05T10:01:08.000Z
2022-03-23T10:59:13.000Z
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include "gpu_util.hpp" #include "nnfusion/util/util.hpp" using namespace std; using namespace nnfusion; namespace { // Unsigned integer exponentiation by squaring adapted // from https://stackoverflow.com/a/101613/882253 uint64_t powU64(uint64_t base, uint64_t exp) { uint64_t result = 1; do { if (exp & 1) { result *= base; } exp >>= 1; if (!exp) { break; } base *= base; } while (true); return result; } // Most significant bit search via de bruijn multiplication // Adopted from https://stackoverflow.com/a/31718095/882253 // Additional ref: http://supertech.csail.mit.edu/papers/debruijn.pdf uint32_t msbDeBruijnU32(uint32_t v) { static const int multiply_de_Bruijn_bit_position[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31}; v |= v >> 1; // first round down to one less than a power of 2 v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; return multiply_de_Bruijn_bit_position[static_cast<uint32_t>(v * 0x07C4ACDDU) >> 27]; } // perform msb on upper 32 bits if the first 32 bits are filled // otherwise do normal de bruijn mutliplication on the 32 bit word int msbU64(uint64_t val) { if (val > 0x00000000FFFFFFFFul) { return 32 + msbDeBruijnU32(static_cast<uint32_t>(val >> 32)); } // Number is no more than 32 bits, // so calculate number of bits in the bottom half. return msbDeBruijnU32(static_cast<uint32_t>(val & 0xFFFFFFFF)); } // Magic numbers and shift amounts for integer division // Suitable for when nmax*magic fits in 32 bits // Translated from http://www.hackersdelight.org/hdcodetxt/magicgu.py.txt std::pair<uint64_t, uint64_t> magicU32(uint64_t nmax, uint64_t d) { uint64_t nc = ((nmax + 1) / d) * d - 1; uint64_t nbits = msbU64(nmax) + 1; for (uint64_t p = 0; p < 2 * nbits + 1; p++) { uint64_t pow2 = powU64(2, p); if (pow2 > nc * (d - 1 - (pow2 - 1) % d)) { uint64_t m = (pow2 + d - 1 - (pow2 - 1) % d) / d; return std::pair<uint64_t, uint64_t>{m, p}; } } NNFUSION_CHECK_FAIL() << "Magic for unsigned integer division could not be found."; } // Magic numbers and shift amounts for integer division // Suitable for when nmax*magic fits in 64 bits and the shift // lops off the lower 32 bits std::pair<uint64_t, uint64_t> magicU64(uint64_t d) { // 3 is a special case that only ends up in the high bits // if the nmax is 0xffffffff // we can't use 0xffffffff for all cases as some return a 33 bit // magic number uint64_t nmax = (d == 3) ? 0xffffffff : 0x7fffffff; uint64_t magic, shift; std::tie(magic, shift) = magicU32(nmax, d); if (magic != 1) { shift -= 32; } return std::pair<uint64_t, uint64_t>{magic, shift}; } } std::pair<uint64_t, uint64_t> kernels::cuda::idiv_magic_u32(uint64_t max_numerator, uint64_t divisor) { return magicU32(max_numerator, divisor); } std::pair<uint64_t, uint64_t> kernels::cuda::idiv_magic_u64(uint64_t divisor) { return magicU64(divisor); } uint32_t kernels::cuda::idiv_ceil(int n, int d) { // compiler fused modulo and division return n / d + (n % d > 0); }
33.842105
93
0.565874
lynex
638a64d0087e85458287c8af5b72311314ac2c05
2,448
hpp
C++
vm/test/test_vm_native_library.hpp
marnen/rubinius
05b3f9789d01bada0604a7f09921c956bc9487e7
[ "BSD-3-Clause" ]
1
2016-05-08T16:58:14.000Z
2016-05-08T16:58:14.000Z
vm/test/test_vm_native_library.hpp
taf2/rubinius
493bfa2351fc509ca33d3bb03991c2e9c2b6dafa
[ "BSD-3-Clause" ]
null
null
null
vm/test/test_vm_native_library.hpp
taf2/rubinius
493bfa2351fc509ca33d3bb03991c2e9c2b6dafa
[ "BSD-3-Clause" ]
null
null
null
#include <cstdlib> #include "native_libraries.hpp" #include "builtin/exception.hpp" #include <cxxtest/TestSuite.h> using namespace rubinius; class TestNativeLibrary : public CxxTest::TestSuite { public: VM* state_; const char* lib_name_; void setUp() { state_ = new VM(); lib_name_ = ::getenv("LIBRUBY"); } void tearDown() { delete state_; } void test_find_symbol_in_this_process() { String* name = String::create(state_, "strlen"); /* libc */ TS_ASSERT(NativeLibrary::find_symbol(state_, name, Qnil)); } void test_find_symbol_in_this_process_throws_on_unloaded_library() { String* name = String::create(state_, "ruby_version"); /* libruby.1.8 */ TS_ASSERT_THROWS(NativeLibrary::find_symbol(state_, name, Qnil), RubyException); } void test_find_symbol_in_this_process_throws_on_nonexisting_symbol() { String* name = String::create(state_, "nonesuch_just_made__u___p__yep____"); TS_ASSERT_THROWS(NativeLibrary::find_symbol(state_, name, Qnil), RubyException); } /** * \file * * @todo This only works under the assumption that anyone running * these tests has MRI installed. We could be more creative * but frankly it requires too much code in C++. This code * _must_ exercise a library that has not been loaded into * the current image (@see test_find_symbol_in_this_process) * because whether the call to load e.g. libc succeeds is * platform-dependent. --rue */ void test_find_symbol_in_library() { if(lib_name_) { String* lib = String::create(state_, lib_name_); String* name = String::create(state_, "ruby_version"); TS_ASSERT(NativeLibrary::find_symbol(state_, name, lib)); } } void test_find_symbol_in_library_throws_on_nonexisting_library() { String* lib = String::create(state_, "blah"); String* name = String::create(state_, "ruby_version"); TS_ASSERT_THROWS(NativeLibrary::find_symbol(state_, name, lib), RubyException); } void test_find_symbol_in_library_throws_on_nonexisting_symbol() { if(lib_name_) { String* lib = String::create(state_, lib_name_); String* name = String::create(state_, "python_version"); TS_ASSERT_THROWS(NativeLibrary::find_symbol(state_, name, lib), RubyException); } } };
28.465116
80
0.665033
marnen
638c78a037194448ecae1ba50747e6a9ba4e3c4f
1,056
hpp
C++
rds_gui_ros/src/rds_gui_ros_node.hpp
epfl-lasa/rds
574b3881dbaf4fdcd785dd96ba4c451928454b40
[ "MIT" ]
12
2020-08-18T09:01:50.000Z
2022-03-17T19:53:30.000Z
rds_gui_ros/src/rds_gui_ros_node.hpp
epfl-lasa/rds
574b3881dbaf4fdcd785dd96ba4c451928454b40
[ "MIT" ]
null
null
null
rds_gui_ros/src/rds_gui_ros_node.hpp
epfl-lasa/rds
574b3881dbaf4fdcd785dd96ba4c451928454b40
[ "MIT" ]
1
2021-08-25T13:12:55.000Z
2021-08-25T13:12:55.000Z
#ifndef RDS_GUI_ROS_NODE_HPP #define RDS_GUI_ROS_NODE_HPP #include <rds/gui.hpp> #include <rds/geometry.hpp> #include <rds_network_ros/ToGui.h> #include <ros/ros.h> struct RDSGUIROSNode { RDSGUIROSNode(ros::NodeHandle* n); void toGuiMessageCallback(const rds_network_ros::ToGui::ConstPtr& to_gui_msg); GUI gui_command_space; float m_gui_work_space_size; GUI gui_work_space; ros::Subscriber to_gui_subscriber; bool m_draw_orca_circle; std::vector<AdditionalPrimitives2D::Arrow> command_space_arrows; std::vector<Geometry2D::HalfPlane2> command_space_halfplanes; std::vector<Geometry2D::Vec2> solver_space_points; std::vector<Geometry2D::HalfPlane2> solver_space_halfplanes; //std::vector<Geometry2D::Vec2> work_space_points; std::vector<AdditionalPrimitives2D::Circle> work_space_circles; std::vector<AdditionalPrimitives2D::Arrow> work_space_arrows; std::vector<Geometry2D::Capsule> work_space_capsules; GuiColor green, blue, red, magenta, cyan, yellow, orange, blue_fade, white, purple, color_nominal, color_corrected; }; #endif
28.540541
116
0.805871
epfl-lasa
638ca6cb52621f723ba8044101e0cd0594c94b99
35,119
cpp
C++
Source/WebKit/UIProcess/WebStorage/StorageManager.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
1
2021-05-27T07:29:31.000Z
2021-05-27T07:29:31.000Z
WebKit2-7604.1.38.0.7/WebKit2-7604.1.38.0.7/UIProcess/Storage/StorageManager.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
9
2020-04-18T18:47:18.000Z
2020-04-18T18:52:41.000Z
Source/WebKit/UIProcess/WebStorage/StorageManager.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2013-2016 Apple 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: * 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h" #include "StorageManager.h" #include "LocalStorageDatabase.h" #include "LocalStorageDatabaseTracker.h" #include "StorageAreaMapMessages.h" #include "StorageManagerMessages.h" #include "WebProcessProxy.h" #include <WebCore/SecurityOriginData.h> #include <WebCore/SecurityOriginHash.h> #include <WebCore/StorageMap.h> #include <WebCore/TextEncoding.h> #include <memory> #include <wtf/WorkQueue.h> #include <wtf/threads/BinarySemaphore.h> using namespace WebCore; namespace WebKit { class StorageManager::StorageArea : public ThreadSafeRefCounted<StorageManager::StorageArea> { public: static Ref<StorageArea> create(LocalStorageNamespace*, const SecurityOriginData&, unsigned quotaInBytes); ~StorageArea(); const WebCore::SecurityOriginData& securityOrigin() const { return m_securityOrigin; } void addListener(IPC::Connection&, uint64_t storageMapID); void removeListener(IPC::Connection&, uint64_t storageMapID); Ref<StorageArea> clone() const; void setItem(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& value, const String& urlString, bool& quotaException); void removeItem(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& urlString); void clear(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& urlString); const HashMap<String, String>& items() const; void clear(); bool isSessionStorage() const { return !m_localStorageNamespace; } private: explicit StorageArea(LocalStorageNamespace*, const SecurityOriginData&, unsigned quotaInBytes); void openDatabaseAndImportItemsIfNeeded() const; void dispatchEvents(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& oldValue, const String& newValue, const String& urlString) const; // Will be null if the storage area belongs to a session storage namespace. LocalStorageNamespace* m_localStorageNamespace; mutable RefPtr<LocalStorageDatabase> m_localStorageDatabase; mutable bool m_didImportItemsFromDatabase { false }; SecurityOriginData m_securityOrigin; unsigned m_quotaInBytes; RefPtr<StorageMap> m_storageMap; HashSet<std::pair<RefPtr<IPC::Connection>, uint64_t>> m_eventListeners; }; class StorageManager::LocalStorageNamespace : public ThreadSafeRefCounted<LocalStorageNamespace> { public: static Ref<LocalStorageNamespace> create(StorageManager*, uint64_t storageManagerID); ~LocalStorageNamespace(); StorageManager* storageManager() const { return m_storageManager; } Ref<StorageArea> getOrCreateStorageArea(SecurityOriginData&&); void didDestroyStorageArea(StorageArea*); void clearStorageAreasMatchingOrigin(const SecurityOriginData&); void clearAllStorageAreas(); private: explicit LocalStorageNamespace(StorageManager*, uint64_t storageManagerID); StorageManager* m_storageManager; uint64_t m_storageNamespaceID; unsigned m_quotaInBytes; // We don't hold an explicit reference to the StorageAreas; they are kept alive by the m_storageAreasByConnection map in StorageManager. HashMap<SecurityOriginData, StorageArea*> m_storageAreaMap; }; class StorageManager::TransientLocalStorageNamespace : public ThreadSafeRefCounted<TransientLocalStorageNamespace> { public: static Ref<TransientLocalStorageNamespace> create() { return adoptRef(*new TransientLocalStorageNamespace()); } ~TransientLocalStorageNamespace() { } Ref<StorageArea> getOrCreateStorageArea(SecurityOriginData&& securityOrigin) { return *m_storageAreaMap.ensure(securityOrigin, [this, securityOrigin]() mutable { return StorageArea::create(nullptr, WTFMove(securityOrigin), m_quotaInBytes); }).iterator->value.copyRef(); } Vector<SecurityOriginData> origins() const { Vector<SecurityOriginData> origins; for (const auto& storageArea : m_storageAreaMap.values()) { if (!storageArea->items().isEmpty()) origins.append(storageArea->securityOrigin()); } return origins; } void clearStorageAreasMatchingOrigin(const SecurityOriginData& securityOrigin) { for (auto& storageArea : m_storageAreaMap.values()) { if (storageArea->securityOrigin() == securityOrigin) storageArea->clear(); } } void clearAllStorageAreas() { for (auto& storageArea : m_storageAreaMap.values()) storageArea->clear(); } private: explicit TransientLocalStorageNamespace() { } const unsigned m_quotaInBytes = 5 * 1024 * 1024; HashMap<SecurityOriginData, RefPtr<StorageArea>> m_storageAreaMap; }; auto StorageManager::StorageArea::create(LocalStorageNamespace* localStorageNamespace, const SecurityOriginData& securityOrigin, unsigned quotaInBytes) -> Ref<StorageManager::StorageArea> { return adoptRef(*new StorageArea(localStorageNamespace, securityOrigin, quotaInBytes)); } StorageManager::StorageArea::StorageArea(LocalStorageNamespace* localStorageNamespace, const SecurityOriginData& securityOrigin, unsigned quotaInBytes) : m_localStorageNamespace(localStorageNamespace) , m_securityOrigin(securityOrigin) , m_quotaInBytes(quotaInBytes) , m_storageMap(StorageMap::create(m_quotaInBytes)) { } StorageManager::StorageArea::~StorageArea() { ASSERT(m_eventListeners.isEmpty()); if (m_localStorageDatabase) m_localStorageDatabase->close(); if (m_localStorageNamespace) m_localStorageNamespace->didDestroyStorageArea(this); } void StorageManager::StorageArea::addListener(IPC::Connection& connection, uint64_t storageMapID) { ASSERT(!m_eventListeners.contains(std::make_pair(&connection, storageMapID))); m_eventListeners.add(std::make_pair(&connection, storageMapID)); } void StorageManager::StorageArea::removeListener(IPC::Connection& connection, uint64_t storageMapID) { ASSERT(isSessionStorage() || m_eventListeners.contains(std::make_pair(&connection, storageMapID))); m_eventListeners.remove(std::make_pair(&connection, storageMapID)); } Ref<StorageManager::StorageArea> StorageManager::StorageArea::clone() const { ASSERT(!m_localStorageNamespace); auto storageArea = StorageArea::create(nullptr, m_securityOrigin, m_quotaInBytes); storageArea->m_storageMap = m_storageMap; return storageArea; } void StorageManager::StorageArea::setItem(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& value, const String& urlString, bool& quotaException) { openDatabaseAndImportItemsIfNeeded(); String oldValue; auto newStorageMap = m_storageMap->setItem(key, value, oldValue, quotaException); if (newStorageMap) m_storageMap = WTFMove(newStorageMap); if (quotaException) return; if (m_localStorageDatabase) m_localStorageDatabase->setItem(key, value); dispatchEvents(sourceConnection, sourceStorageAreaID, key, oldValue, value, urlString); } void StorageManager::StorageArea::removeItem(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& urlString) { openDatabaseAndImportItemsIfNeeded(); String oldValue; auto newStorageMap = m_storageMap->removeItem(key, oldValue); if (newStorageMap) m_storageMap = WTFMove(newStorageMap); if (oldValue.isNull()) return; if (m_localStorageDatabase) m_localStorageDatabase->removeItem(key); dispatchEvents(sourceConnection, sourceStorageAreaID, key, oldValue, String(), urlString); } void StorageManager::StorageArea::clear(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& urlString) { openDatabaseAndImportItemsIfNeeded(); if (!m_storageMap->length()) return; m_storageMap = StorageMap::create(m_quotaInBytes); if (m_localStorageDatabase) m_localStorageDatabase->clear(); dispatchEvents(sourceConnection, sourceStorageAreaID, String(), String(), String(), urlString); } const HashMap<String, String>& StorageManager::StorageArea::items() const { openDatabaseAndImportItemsIfNeeded(); return m_storageMap->items(); } void StorageManager::StorageArea::clear() { m_storageMap = StorageMap::create(m_quotaInBytes); if (m_localStorageDatabase) { m_localStorageDatabase->close(); m_localStorageDatabase = nullptr; } for (auto it = m_eventListeners.begin(), end = m_eventListeners.end(); it != end; ++it) it->first->send(Messages::StorageAreaMap::ClearCache(), it->second); } void StorageManager::StorageArea::openDatabaseAndImportItemsIfNeeded() const { if (!m_localStorageNamespace) return; // We open the database here even if we've already imported our items to ensure that the database is open if we need to write to it. if (!m_localStorageDatabase) m_localStorageDatabase = LocalStorageDatabase::create(m_localStorageNamespace->storageManager()->m_queue.copyRef(), m_localStorageNamespace->storageManager()->m_localStorageDatabaseTracker.copyRef(), m_securityOrigin); if (m_didImportItemsFromDatabase) return; m_localStorageDatabase->importItems(*m_storageMap); m_didImportItemsFromDatabase = true; } void StorageManager::StorageArea::dispatchEvents(IPC::Connection* sourceConnection, uint64_t sourceStorageAreaID, const String& key, const String& oldValue, const String& newValue, const String& urlString) const { for (HashSet<std::pair<RefPtr<IPC::Connection>, uint64_t>>::const_iterator it = m_eventListeners.begin(), end = m_eventListeners.end(); it != end; ++it) { uint64_t storageAreaID = it->first == sourceConnection ? sourceStorageAreaID : 0; it->first->send(Messages::StorageAreaMap::DispatchStorageEvent(storageAreaID, key, oldValue, newValue, urlString), it->second); } } Ref<StorageManager::LocalStorageNamespace> StorageManager::LocalStorageNamespace::create(StorageManager* storageManager, uint64_t storageNamespaceID) { return adoptRef(*new LocalStorageNamespace(storageManager, storageNamespaceID)); } // FIXME: The quota value is copied from GroupSettings.cpp. // We should investigate a way to share it with WebCore. StorageManager::LocalStorageNamespace::LocalStorageNamespace(StorageManager* storageManager, uint64_t storageNamespaceID) : m_storageManager(storageManager) , m_storageNamespaceID(storageNamespaceID) , m_quotaInBytes(5 * 1024 * 1024) { } StorageManager::LocalStorageNamespace::~LocalStorageNamespace() { ASSERT(m_storageAreaMap.isEmpty()); } auto StorageManager::LocalStorageNamespace::getOrCreateStorageArea(SecurityOriginData&& securityOrigin) -> Ref<StorageArea> { auto& slot = m_storageAreaMap.add(securityOrigin, nullptr).iterator->value; if (slot) return *slot; auto storageArea = StorageArea::create(this, WTFMove(securityOrigin), m_quotaInBytes); slot = &storageArea.get(); return storageArea; } void StorageManager::LocalStorageNamespace::didDestroyStorageArea(StorageArea* storageArea) { ASSERT(m_storageAreaMap.contains(storageArea->securityOrigin())); m_storageAreaMap.remove(storageArea->securityOrigin()); if (!m_storageAreaMap.isEmpty()) return; ASSERT(m_storageManager->m_localStorageNamespaces.contains(m_storageNamespaceID)); m_storageManager->m_localStorageNamespaces.remove(m_storageNamespaceID); } void StorageManager::LocalStorageNamespace::clearStorageAreasMatchingOrigin(const SecurityOriginData& securityOrigin) { for (const auto& originAndStorageArea : m_storageAreaMap) { if (originAndStorageArea.key == securityOrigin) originAndStorageArea.value->clear(); } } void StorageManager::LocalStorageNamespace::clearAllStorageAreas() { for (auto* storageArea : m_storageAreaMap.values()) storageArea->clear(); } class StorageManager::SessionStorageNamespace : public ThreadSafeRefCounted<SessionStorageNamespace> { public: static Ref<SessionStorageNamespace> create(unsigned quotaInBytes); ~SessionStorageNamespace(); bool isEmpty() const { return m_storageAreaMap.isEmpty(); } IPC::Connection* allowedConnection() const { return m_allowedConnection.get(); } void setAllowedConnection(IPC::Connection*); Ref<StorageArea> getOrCreateStorageArea(SecurityOriginData&&); void cloneTo(SessionStorageNamespace& newSessionStorageNamespace); Vector<SecurityOriginData> origins() const { Vector<SecurityOriginData> origins; for (const auto& storageArea : m_storageAreaMap.values()) { if (!storageArea->items().isEmpty()) origins.append(storageArea->securityOrigin()); } return origins; } void clearStorageAreasMatchingOrigin(const SecurityOriginData& securityOrigin) { for (auto& storageArea : m_storageAreaMap.values()) { if (storageArea->securityOrigin() == securityOrigin) storageArea->clear(); } } void clearAllStorageAreas() { for (auto& storageArea : m_storageAreaMap.values()) storageArea->clear(); } private: explicit SessionStorageNamespace(unsigned quotaInBytes); RefPtr<IPC::Connection> m_allowedConnection; unsigned m_quotaInBytes; HashMap<SecurityOriginData, RefPtr<StorageArea>> m_storageAreaMap; }; Ref<StorageManager::SessionStorageNamespace> StorageManager::SessionStorageNamespace::create(unsigned quotaInBytes) { return adoptRef(*new SessionStorageNamespace(quotaInBytes)); } StorageManager::SessionStorageNamespace::SessionStorageNamespace(unsigned quotaInBytes) : m_quotaInBytes(quotaInBytes) { } StorageManager::SessionStorageNamespace::~SessionStorageNamespace() { } void StorageManager::SessionStorageNamespace::setAllowedConnection(IPC::Connection* allowedConnection) { ASSERT(!allowedConnection || !m_allowedConnection); m_allowedConnection = allowedConnection; } auto StorageManager::SessionStorageNamespace::getOrCreateStorageArea(SecurityOriginData&& securityOrigin) -> Ref<StorageArea> { return *m_storageAreaMap.ensure(securityOrigin, [this, securityOrigin]() mutable { return StorageArea::create(nullptr, WTFMove(securityOrigin), m_quotaInBytes); }).iterator->value.copyRef(); } void StorageManager::SessionStorageNamespace::cloneTo(SessionStorageNamespace& newSessionStorageNamespace) { ASSERT_UNUSED(newSessionStorageNamespace, newSessionStorageNamespace.isEmpty()); for (auto& pair : m_storageAreaMap) newSessionStorageNamespace.m_storageAreaMap.add(pair.key, pair.value->clone()); } Ref<StorageManager> StorageManager::create(const String& localStorageDirectory) { return adoptRef(*new StorageManager(localStorageDirectory)); } StorageManager::StorageManager(const String& localStorageDirectory) : m_queue(WorkQueue::create("com.apple.WebKit.StorageManager")) , m_localStorageDatabaseTracker(LocalStorageDatabaseTracker::create(m_queue.copyRef(), localStorageDirectory)) { // Make sure the encoding is initialized before we start dispatching things to the queue. UTF8Encoding(); } StorageManager::~StorageManager() { } void StorageManager::createSessionStorageNamespace(uint64_t storageNamespaceID, unsigned quotaInBytes) { m_queue->dispatch([this, protectedThis = makeRef(*this), storageNamespaceID, quotaInBytes]() mutable { ASSERT(!m_sessionStorageNamespaces.contains(storageNamespaceID)); m_sessionStorageNamespaces.set(storageNamespaceID, SessionStorageNamespace::create(quotaInBytes)); }); } void StorageManager::destroySessionStorageNamespace(uint64_t storageNamespaceID) { m_queue->dispatch([this, protectedThis = makeRef(*this), storageNamespaceID] { ASSERT(m_sessionStorageNamespaces.contains(storageNamespaceID)); m_sessionStorageNamespaces.remove(storageNamespaceID); }); } void StorageManager::setAllowedSessionStorageNamespaceConnection(uint64_t storageNamespaceID, IPC::Connection* allowedConnection) { m_queue->dispatch([this, protectedThis = makeRef(*this), connection = RefPtr<IPC::Connection>(allowedConnection), storageNamespaceID]() mutable { ASSERT(m_sessionStorageNamespaces.contains(storageNamespaceID)); m_sessionStorageNamespaces.get(storageNamespaceID)->setAllowedConnection(connection.get()); }); } void StorageManager::cloneSessionStorageNamespace(uint64_t storageNamespaceID, uint64_t newStorageNamespaceID) { m_queue->dispatch([this, protectedThis = makeRef(*this), storageNamespaceID, newStorageNamespaceID] { SessionStorageNamespace* sessionStorageNamespace = m_sessionStorageNamespaces.get(storageNamespaceID); if (!sessionStorageNamespace) { // FIXME: We can get into this situation if someone closes the originating page from within a // createNewPage callback. We bail for now, but we should really find a way to keep the session storage alive // so we we'll clone the session storage correctly. return; } SessionStorageNamespace* newSessionStorageNamespace = m_sessionStorageNamespaces.get(newStorageNamespaceID); ASSERT(newSessionStorageNamespace); sessionStorageNamespace->cloneTo(*newSessionStorageNamespace); }); } void StorageManager::processWillOpenConnection(WebProcessProxy&, IPC::Connection& connection) { connection.addWorkQueueMessageReceiver(Messages::StorageManager::messageReceiverName(), m_queue.get(), this); } void StorageManager::processDidCloseConnection(WebProcessProxy&, IPC::Connection& connection) { connection.removeWorkQueueMessageReceiver(Messages::StorageManager::messageReceiverName()); m_queue->dispatch([this, protectedThis = makeRef(*this), connection = Ref<IPC::Connection>(connection)]() mutable { Vector<std::pair<RefPtr<IPC::Connection>, uint64_t>> connectionAndStorageMapIDPairsToRemove; for (auto& storageArea : m_storageAreasByConnection) { if (storageArea.key.first != connection.ptr()) continue; storageArea.value->removeListener(*storageArea.key.first, storageArea.key.second); connectionAndStorageMapIDPairsToRemove.append(storageArea.key); } for (auto& pair : connectionAndStorageMapIDPairsToRemove) m_storageAreasByConnection.remove(pair); }); } void StorageManager::getSessionStorageOrigins(Function<void(HashSet<WebCore::SecurityOriginData>&&)>&& completionHandler) { m_queue->dispatch([this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)]() mutable { HashSet<SecurityOriginData> origins; for (const auto& sessionStorageNamespace : m_sessionStorageNamespaces.values()) { for (auto& origin : sessionStorageNamespace->origins()) origins.add(origin); } RunLoop::main().dispatch([origins = WTFMove(origins), completionHandler = WTFMove(completionHandler)]() mutable { completionHandler(WTFMove(origins)); }); }); } void StorageManager::deleteSessionStorageOrigins(Function<void()>&& completionHandler) { m_queue->dispatch([this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)]() mutable { for (auto& sessionStorageNamespace : m_sessionStorageNamespaces.values()) sessionStorageNamespace->clearAllStorageAreas(); RunLoop::main().dispatch(WTFMove(completionHandler)); }); } void StorageManager::deleteSessionStorageEntriesForOrigins(const Vector<WebCore::SecurityOriginData>& origins, Function<void()>&& completionHandler) { Vector<WebCore::SecurityOriginData> copiedOrigins; copiedOrigins.reserveInitialCapacity(origins.size()); for (auto& origin : origins) copiedOrigins.uncheckedAppend(origin.isolatedCopy()); m_queue->dispatch([this, protectedThis = makeRef(*this), copiedOrigins = WTFMove(copiedOrigins), completionHandler = WTFMove(completionHandler)]() mutable { for (auto& origin : copiedOrigins) { for (auto& sessionStorageNamespace : m_sessionStorageNamespaces.values()) sessionStorageNamespace->clearStorageAreasMatchingOrigin(origin); } RunLoop::main().dispatch(WTFMove(completionHandler)); }); } void StorageManager::getLocalStorageOrigins(Function<void(HashSet<WebCore::SecurityOriginData>&&)>&& completionHandler) { m_queue->dispatch([this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)]() mutable { HashSet<SecurityOriginData> origins; for (auto& origin : m_localStorageDatabaseTracker->origins()) origins.add(origin); for (auto& transientLocalStorageNamespace : m_transientLocalStorageNamespaces.values()) { for (auto& origin : transientLocalStorageNamespace->origins()) origins.add(origin); } RunLoop::main().dispatch([origins = WTFMove(origins), completionHandler = WTFMove(completionHandler)]() mutable { completionHandler(WTFMove(origins)); }); }); } void StorageManager::getLocalStorageOriginDetails(Function<void (Vector<LocalStorageDatabaseTracker::OriginDetails>)>&& completionHandler) { m_queue->dispatch([this, protectedThis = makeRef(*this), completionHandler = WTFMove(completionHandler)]() mutable { auto originDetails = m_localStorageDatabaseTracker->originDetails(); RunLoop::main().dispatch([originDetails = WTFMove(originDetails), completionHandler = WTFMove(completionHandler)]() mutable { completionHandler(WTFMove(originDetails)); }); }); } void StorageManager::deleteLocalStorageEntriesForOrigin(SecurityOriginData&& securityOrigin) { m_queue->dispatch([this, protectedThis = makeRef(*this), copiedOrigin = securityOrigin.isolatedCopy()]() mutable { for (auto& localStorageNamespace : m_localStorageNamespaces.values()) localStorageNamespace->clearStorageAreasMatchingOrigin(copiedOrigin); for (auto& transientLocalStorageNamespace : m_transientLocalStorageNamespaces.values()) transientLocalStorageNamespace->clearStorageAreasMatchingOrigin(copiedOrigin); m_localStorageDatabaseTracker->deleteDatabaseWithOrigin(copiedOrigin); }); } void StorageManager::deleteLocalStorageOriginsModifiedSince(std::chrono::system_clock::time_point time, Function<void()>&& completionHandler) { m_queue->dispatch([this, protectedThis = makeRef(*this), time, completionHandler = WTFMove(completionHandler)]() mutable { auto deletedOrigins = m_localStorageDatabaseTracker->deleteDatabasesModifiedSince(time); for (const auto& origin : deletedOrigins) { for (auto& localStorageNamespace : m_localStorageNamespaces.values()) localStorageNamespace->clearStorageAreasMatchingOrigin(origin); } for (auto& transientLocalStorageNamespace : m_transientLocalStorageNamespaces.values()) transientLocalStorageNamespace->clearAllStorageAreas(); RunLoop::main().dispatch(WTFMove(completionHandler)); }); } void StorageManager::deleteLocalStorageEntriesForOrigins(const Vector<WebCore::SecurityOriginData>& origins, Function<void()>&& completionHandler) { Vector<SecurityOriginData> copiedOrigins; copiedOrigins.reserveInitialCapacity(origins.size()); for (auto& origin : origins) copiedOrigins.uncheckedAppend(origin.isolatedCopy()); m_queue->dispatch([this, protectedThis = makeRef(*this), copiedOrigins = WTFMove(copiedOrigins), completionHandler = WTFMove(completionHandler)]() mutable { for (auto& origin : copiedOrigins) { for (auto& localStorageNamespace : m_localStorageNamespaces.values()) localStorageNamespace->clearStorageAreasMatchingOrigin(origin); for (auto& transientLocalStorageNamespace : m_transientLocalStorageNamespaces.values()) transientLocalStorageNamespace->clearStorageAreasMatchingOrigin(origin); m_localStorageDatabaseTracker->deleteDatabaseWithOrigin(origin); } RunLoop::main().dispatch(WTFMove(completionHandler)); }); } void StorageManager::createLocalStorageMap(IPC::Connection& connection, uint64_t storageMapID, uint64_t storageNamespaceID, SecurityOriginData&& securityOriginData) { std::pair<RefPtr<IPC::Connection>, uint64_t> connectionAndStorageMapIDPair(&connection, storageMapID); // FIXME: This should be a message check. ASSERT((HashMap<std::pair<RefPtr<IPC::Connection>, uint64_t>, RefPtr<StorageArea>>::isValidKey(connectionAndStorageMapIDPair))); HashMap<std::pair<RefPtr<IPC::Connection>, uint64_t>, RefPtr<StorageArea>>::AddResult result = m_storageAreasByConnection.add(connectionAndStorageMapIDPair, nullptr); // FIXME: These should be a message checks. ASSERT(result.isNewEntry); ASSERT((HashMap<uint64_t, RefPtr<LocalStorageNamespace>>::isValidKey(storageNamespaceID))); LocalStorageNamespace* localStorageNamespace = getOrCreateLocalStorageNamespace(storageNamespaceID); // FIXME: This should be a message check. ASSERT(localStorageNamespace); auto storageArea = localStorageNamespace->getOrCreateStorageArea(WTFMove(securityOriginData)); storageArea->addListener(connection, storageMapID); result.iterator->value = WTFMove(storageArea); } void StorageManager::createTransientLocalStorageMap(IPC::Connection& connection, uint64_t storageMapID, uint64_t storageNamespaceID, SecurityOriginData&& topLevelOriginData, SecurityOriginData&& origin) { // FIXME: This should be a message check. ASSERT(m_storageAreasByConnection.isValidKey({ &connection, storageMapID })); // See if we already have session storage for this connection/origin combo. // If so, update the map with the new ID, otherwise keep on trucking. for (auto it = m_storageAreasByConnection.begin(), end = m_storageAreasByConnection.end(); it != end; ++it) { if (it->key.first != &connection) continue; Ref<StorageArea> area = *it->value; if (!area->isSessionStorage()) continue; if (!origin.securityOrigin()->isSameSchemeHostPort(area->securityOrigin().securityOrigin().get())) continue; area->addListener(connection, storageMapID); m_storageAreasByConnection.remove(it); m_storageAreasByConnection.add({ &connection, storageMapID }, WTFMove(area)); return; } auto& slot = m_storageAreasByConnection.add({ &connection, storageMapID }, nullptr).iterator->value; // FIXME: This should be a message check. ASSERT(!slot); TransientLocalStorageNamespace* transientLocalStorageNamespace = getOrCreateTransientLocalStorageNamespace(storageNamespaceID, WTFMove(topLevelOriginData)); auto storageArea = transientLocalStorageNamespace->getOrCreateStorageArea(WTFMove(origin)); storageArea->addListener(connection, storageMapID); slot = WTFMove(storageArea); } void StorageManager::createSessionStorageMap(IPC::Connection& connection, uint64_t storageMapID, uint64_t storageNamespaceID, SecurityOriginData&& securityOriginData) { // FIXME: This should be a message check. ASSERT(m_sessionStorageNamespaces.isValidKey(storageNamespaceID)); SessionStorageNamespace* sessionStorageNamespace = m_sessionStorageNamespaces.get(storageNamespaceID); if (!sessionStorageNamespace) { // We're getting an incoming message from the web process that's for session storage for a web page // that has already been closed, just ignore it. return; } // FIXME: This should be a message check. ASSERT(m_storageAreasByConnection.isValidKey({ &connection, storageMapID })); auto& slot = m_storageAreasByConnection.add({ &connection, storageMapID }, nullptr).iterator->value; // FIXME: This should be a message check. ASSERT(!slot); // FIXME: This should be a message check. ASSERT(&connection == sessionStorageNamespace->allowedConnection()); auto storageArea = sessionStorageNamespace->getOrCreateStorageArea(WTFMove(securityOriginData)); storageArea->addListener(connection, storageMapID); slot = WTFMove(storageArea); } void StorageManager::destroyStorageMap(IPC::Connection& connection, uint64_t storageMapID) { std::pair<RefPtr<IPC::Connection>, uint64_t> connectionAndStorageMapIDPair(&connection, storageMapID); // FIXME: This should be a message check. ASSERT(m_storageAreasByConnection.isValidKey(connectionAndStorageMapIDPair)); auto it = m_storageAreasByConnection.find(connectionAndStorageMapIDPair); if (it == m_storageAreasByConnection.end()) { // The connection has been removed because the last page was closed. return; } it->value->removeListener(connection, storageMapID); // Don't remove session storage maps. The web process may reconnect and expect the data to still be around. if (it->value->isSessionStorage()) return; m_storageAreasByConnection.remove(connectionAndStorageMapIDPair); } void StorageManager::getValues(IPC::Connection& connection, uint64_t storageMapID, uint64_t storageMapSeed, HashMap<String, String>& values) { StorageArea* storageArea = findStorageArea(connection, storageMapID); if (!storageArea) { // This is a session storage area for a page that has already been closed. Ignore it. return; } values = storageArea->items(); connection.send(Messages::StorageAreaMap::DidGetValues(storageMapSeed), storageMapID); } void StorageManager::setItem(IPC::Connection& connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& value, const String& urlString) { StorageArea* storageArea = findStorageArea(connection, storageMapID); if (!storageArea) { // This is a session storage area for a page that has already been closed. Ignore it. return; } bool quotaError; storageArea->setItem(&connection, sourceStorageAreaID, key, value, urlString, quotaError); connection.send(Messages::StorageAreaMap::DidSetItem(storageMapSeed, key, quotaError), storageMapID); } void StorageManager::removeItem(IPC::Connection& connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& key, const String& urlString) { StorageArea* storageArea = findStorageArea(connection, storageMapID); if (!storageArea) { // This is a session storage area for a page that has already been closed. Ignore it. return; } storageArea->removeItem(&connection, sourceStorageAreaID, key, urlString); connection.send(Messages::StorageAreaMap::DidRemoveItem(storageMapSeed, key), storageMapID); } void StorageManager::clear(IPC::Connection& connection, uint64_t storageMapID, uint64_t sourceStorageAreaID, uint64_t storageMapSeed, const String& urlString) { StorageArea* storageArea = findStorageArea(connection, storageMapID); if (!storageArea) { // This is a session storage area for a page that has already been closed. Ignore it. return; } storageArea->clear(&connection, sourceStorageAreaID, urlString); connection.send(Messages::StorageAreaMap::DidClear(storageMapSeed), storageMapID); } void StorageManager::applicationWillTerminate() { BinarySemaphore semaphore; m_queue->dispatch([this, &semaphore] { Vector<std::pair<RefPtr<IPC::Connection>, uint64_t>> connectionAndStorageMapIDPairsToRemove; for (auto& connectionStorageAreaPair : m_storageAreasByConnection) { connectionStorageAreaPair.value->removeListener(*connectionStorageAreaPair.key.first, connectionStorageAreaPair.key.second); connectionAndStorageMapIDPairsToRemove.append(connectionStorageAreaPair.key); } for (auto& connectionStorageAreaPair : connectionAndStorageMapIDPairsToRemove) m_storageAreasByConnection.remove(connectionStorageAreaPair); semaphore.signal(); }); semaphore.wait(WallTime::infinity()); } StorageManager::StorageArea* StorageManager::findStorageArea(IPC::Connection& connection, uint64_t storageMapID) const { std::pair<IPC::Connection*, uint64_t> connectionAndStorageMapIDPair(&connection, storageMapID); if (!m_storageAreasByConnection.isValidKey(connectionAndStorageMapIDPair)) return nullptr; return m_storageAreasByConnection.get(connectionAndStorageMapIDPair); } StorageManager::LocalStorageNamespace* StorageManager::getOrCreateLocalStorageNamespace(uint64_t storageNamespaceID) { if (!m_localStorageNamespaces.isValidKey(storageNamespaceID)) return nullptr; auto& slot = m_localStorageNamespaces.add(storageNamespaceID, nullptr).iterator->value; if (!slot) slot = LocalStorageNamespace::create(this, storageNamespaceID); return slot.get(); } StorageManager::TransientLocalStorageNamespace* StorageManager::getOrCreateTransientLocalStorageNamespace(uint64_t storageNamespaceID, WebCore::SecurityOriginData&& topLevelOrigin) { if (!m_transientLocalStorageNamespaces.isValidKey({ storageNamespaceID, topLevelOrigin })) return nullptr; auto& slot = m_transientLocalStorageNamespaces.add({ storageNamespaceID, WTFMove(topLevelOrigin) }, nullptr).iterator->value; if (!slot) slot = TransientLocalStorageNamespace::create(); return slot.get(); } } // namespace WebKit
40.274083
226
0.749822
ijsf
b0cb1dd84798548af5cb2e00bdcf13311013f1ed
1,419
hpp
C++
source/framework/core/include/lue/framework/core/debug.hpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
2
2021-02-26T22:45:56.000Z
2021-05-02T10:28:48.000Z
source/framework/core/include/lue/framework/core/debug.hpp
pcraster/lue
e64c18f78a8b6d8a602b7578a2572e9740969202
[ "MIT" ]
262
2016-08-11T10:12:02.000Z
2020-10-13T18:09:16.000Z
source/framework/core/include/lue/framework/core/debug.hpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
1
2020-03-11T09:49:41.000Z
2020-03-11T09:49:41.000Z
#pragma once #include <hpx/future.hpp> #include <fmt/format.h> #include <string> namespace lue { hpx::future<std::string> system_description(); void write_debug_message (std::string const& message); template< typename Class> std::string describe (Class const& instance); template< typename Count, typename Idx> void validate_idxs( Count const* count, Idx const idx) { if(idx >= *count) { throw std::runtime_error(fmt::format( "Index out of bounds ({} >= {})", idx, *count)); } } template< typename Count, typename Idx, typename... Idxs> void validate_idxs( Count* count, Idx const idx, Idxs... idxs) { if(idx >= *count) { throw std::runtime_error(fmt::format( "Index out of bounds ({} >= {})", idx, *count)); } validate_idxs(++count, idxs...); } template< typename Shape, typename... Idxs> void validate_idxs( Shape const& shape, Idxs... idxs) { if(sizeof...(idxs) != std::size(shape)) { throw std::runtime_error(fmt::format( "Number of indices does not match rank of array ({} != {})", sizeof...(idxs), std::size(shape))); } // Verify each index is within the extent of the corresponding // array extent validate_idxs(shape.data(), idxs...); } } // namespace lue
19.175676
72
0.569415
computationalgeography
b0cc3f4253c3add683bfa3768d9ed44bcf883f99
279
cpp
C++
CPP/HelloCpp2/chapter_20/Inheritance2.cpp
hrntsm/study-language
922578a5321d70c26b935e6052f400125e15649c
[ "MIT" ]
1
2022-02-06T10:50:42.000Z
2022-02-06T10:50:42.000Z
CPP/HelloCpp2/chapter_20/Inheritance2.cpp
hrntsm/study-language
922578a5321d70c26b935e6052f400125e15649c
[ "MIT" ]
null
null
null
CPP/HelloCpp2/chapter_20/Inheritance2.cpp
hrntsm/study-language
922578a5321d70c26b935e6052f400125e15649c
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; class Kitty { public: void nyan() { cout << "Kitty on your lap\n";} }; class Di_Gi_Gharat : public Kitty{ public: void nyan() {cout << "Di Gi Gharat\n";} } obj; int main(){ obj.nyan(); obj.Kitty::nyan(); return 0; }
14.684211
49
0.602151
hrntsm
b0cc4ae220c4645885fe9741eae45887b880a64f
4,321
cpp
C++
Source/10.0.18362.0/ucrt/mbstring/mbsnbicm.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
2
2021-01-27T10:19:30.000Z
2021-02-09T06:24:30.000Z
Source/10.0.18362.0/ucrt/mbstring/mbsnbicm.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
null
null
null
Source/10.0.18362.0/ucrt/mbstring/mbsnbicm.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
1
2021-01-27T10:19:36.000Z
2021-01-27T10:19:36.000Z
/*** *mbsnbicmp.c - Compare n bytes of strings, ignoring case (MBCS) * * Copyright (c) Microsoft Corporation. All rights reserved. * *Purpose: * Compare n bytes of strings, ignoring case (MBCS) * *******************************************************************************/ #ifndef _MBCS #error This file should only be compiled with _MBCS defined #endif #include <corecrt_internal_mbstring.h> #include <locale.h> #include <string.h> #pragma warning(disable:__WARNING_POTENTIAL_BUFFER_OVERFLOW_NULLTERMINATED) // 26018 /*** * _mbsnbicmp - Compare n bytes of strings, ignoring case (MBCS) * *Purpose: * Compares up to n bytes of two strings for ordinal order. * Strings are compared on a character basis, not a byte basis. * Case of characters is not considered. * *Entry: * unsigned char *s1, *s2 = strings to compare * size_t n = maximum number of bytes to compare * *Exit: * Returns <0 if s1 < s2 * Returns 0 if s1 == s2 * Returns >0 if s1 > s2 * Returns _NLSCMPERROR is something went wrong * *Exceptions: * Input parameters are validated. Refer to the validation section of the function. * *******************************************************************************/ int __cdecl _mbsnbicmp_l( const unsigned char *s1, const unsigned char *s2, size_t n, _locale_t plocinfo ) { unsigned short c1, c2; _LocaleUpdate _loc_update(plocinfo); if (n==0) return(0); if (_loc_update.GetLocaleT()->mbcinfo->ismbcodepage == 0) return _strnicmp((const char *)s1, (const char *)s2, n); /* validation section */ _VALIDATE_RETURN(s1 != nullptr, EINVAL, _NLSCMPERROR); _VALIDATE_RETURN(s2 != nullptr, EINVAL, _NLSCMPERROR); while (n--) { c1 = *s1++; if ( _ismbblead_l(c1, _loc_update.GetLocaleT()) ) { if (n==0) { c1 = 0; /* 'naked' lead - end of string */ c2 = _ismbblead_l(*s2, _loc_update.GetLocaleT()) ? 0 : *s2; goto test; } if (*s1 == '\0') c1 = 0; else { c1 = ((c1<<8) | *s1++); if ( ((c1 >= _MBUPPERLOW1_MT(_loc_update.GetLocaleT())) && (c1 <= _MBUPPERHIGH1_MT(_loc_update.GetLocaleT()))) ) c1 += _MBCASEDIFF1_MT(_loc_update.GetLocaleT()); else if ( ((c1 >= _MBUPPERLOW2_MT(_loc_update.GetLocaleT())) && (c1 <= _MBUPPERHIGH2_MT(_loc_update.GetLocaleT()))) ) c1 += _MBCASEDIFF2_MT(_loc_update.GetLocaleT()); } } else c1 = _mbbtolower_l(c1, _loc_update.GetLocaleT()); c2 = *s2++; if ( _ismbblead_l(c2, _loc_update.GetLocaleT()) ) { if (n==0) { c2 = 0; /* 'naked' lead - end of string */ goto test; } n--; if (*s2 == '\0') c2 = 0; else { c2 = ((c2<<8) | *s2++); if ( ((c2 >= _MBUPPERLOW1_MT(_loc_update.GetLocaleT())) && (c2 <= _MBUPPERHIGH1_MT(_loc_update.GetLocaleT()))) ) c2 += _MBCASEDIFF1_MT(_loc_update.GetLocaleT()); else if ( ((c2 >= _MBUPPERLOW2_MT(_loc_update.GetLocaleT())) && (c2 <= _MBUPPERHIGH2_MT(_loc_update.GetLocaleT()))) ) c2 += _MBCASEDIFF2_MT(_loc_update.GetLocaleT()); } } else c2 = _mbbtolower_l(c2, _loc_update.GetLocaleT()); test: if (c1 != c2) return( (c1 > c2) ? 1 : -1); if (c1 == 0) return(0); } return(0); } int (__cdecl _mbsnbicmp)( const unsigned char *s1, const unsigned char *s2, size_t n ) { return _mbsnbicmp_l(s1, s2, n, nullptr); }
32.246269
88
0.466559
825126369
b0d50eca9eba291146ff50b299354b6cfe439952
3,002
cpp
C++
implementations/Bullet/MotionState.cpp
ronsaldo/abstract-physics
dbc23a57bfa369139c786071b2a6db4e84bb16fe
[ "MIT" ]
10
2016-12-11T04:54:18.000Z
2022-02-27T18:12:18.000Z
implementations/Bullet/MotionState.cpp
ronsaldo/abstract-physics
dbc23a57bfa369139c786071b2a6db4e84bb16fe
[ "MIT" ]
null
null
null
implementations/Bullet/MotionState.cpp
ronsaldo/abstract-physics
dbc23a57bfa369139c786071b2a6db4e84bb16fe
[ "MIT" ]
null
null
null
#include "MotionState.hpp" #include "Utility.hpp" namespace APhyBullet { BulletMotionState::BulletMotionState(btMotionState *handle) : handle(handle) { } BulletMotionState::~BulletMotionState() { delete handle; } aphy_transform BulletMotionState::getTransform() { btTransform transform; handle->getWorldTransform(transform); return convertTransform(transform); } aphy_error BulletMotionState::getTransformInto(aphy_transform* result) { CHECK_POINTER(result); *result = getTransform(); return APHY_OK; } aphy_vector3 BulletMotionState::getTranslation() { btTransform transform; handle->getWorldTransform(transform); return convertVector(transform.getOrigin()); } aphy_error BulletMotionState::getTranslationInto(aphy_vector3* result) { CHECK_POINTER(result); *result = getTranslation(); return APHY_OK; } aphy_matrix3x3 BulletMotionState::getMatrix() { btTransform transform; handle->getWorldTransform(transform); return convertMatrix(transform.getBasis()); } aphy_error BulletMotionState::getMatrixInto(aphy_matrix3x3* result) { CHECK_POINTER(result); *result = getMatrix(); return APHY_OK; } aphy_quaternion BulletMotionState::getQuaternion() { btTransform transform; handle->getWorldTransform(transform); return convertQuaternion(transform.getRotation()); } aphy_error BulletMotionState::getQuaternionInto(aphy_quaternion* result) { CHECK_POINTER(result); *result = getQuaternion(); return APHY_OK; } aphy_error BulletMotionState::setTransform(aphy_transform value) { // TODO: Implement this. return APHY_OK; } aphy_error BulletMotionState::setTransformFrom(aphy_transform* value) { CHECK_POINTER(value); return setTransform(*value); } aphy_error BulletMotionState::setTranslation(aphy_vector3 value) { btTransform oldTransform; handle->getWorldTransform(oldTransform); oldTransform.setOrigin(convertAPhyVector(value)); handle->setWorldTransform(oldTransform); return APHY_OK; } aphy_error BulletMotionState::setTranslationFrom(aphy_vector3* value) { CHECK_POINTER(value); return setTranslation(*value); } aphy_error BulletMotionState::setMatrix(aphy_matrix3x3 value) { btTransform oldTransform; handle->getWorldTransform(oldTransform); oldTransform.setBasis(convertAPhyMatrix(value)); handle->setWorldTransform(oldTransform); return APHY_OK; } aphy_error BulletMotionState::setMatrixFrom(aphy_matrix3x3* value) { CHECK_POINTER(value); return setMatrix(*value); } aphy_error BulletMotionState::setQuaternion(aphy_quaternion value) { btTransform oldTransform; handle->getWorldTransform(oldTransform); oldTransform.setRotation(convertAPhyQuaternion(value)); handle->setWorldTransform(oldTransform); return APHY_OK; } aphy_error BulletMotionState::setQuaternionFrom(aphy_quaternion* value) { CHECK_POINTER(value); return setQuaternion(*value); } } // End of namespace APhyBullet
22.916031
72
0.763824
ronsaldo
b0d98e82d35ae57ab6a8db0755b711319ed10ba6
1,218
cpp
C++
Plugins/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp
gaoxiaojun/minircp
fe20201a768515cd0387f0b76a16c0c766cf939d
[ "BSD-3-Clause" ]
5
2015-02-05T10:58:41.000Z
2019-04-17T15:04:07.000Z
Plugins/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp
wyyrepo/MITK
d0837f3d0d44f477b888ec498e9a2ed407e79f20
[ "BSD-3-Clause" ]
141
2015-03-03T06:52:01.000Z
2020-12-10T07:28:14.000Z
Plugins/org.blueberry.core.runtime/src/berryIBerryPreferences.cpp
wyyrepo/MITK
d0837f3d0d44f477b888ec498e9a2ed407e79f20
[ "BSD-3-Clause" ]
4
2015-02-19T06:48:13.000Z
2020-06-19T16:20:25.000Z
/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "berryIBerryPreferences.h" namespace berry { IBerryPreferences::~IBerryPreferences () { } IBerryPreferences::ChangeEvent::ChangeEvent(IBerryPreferences* source, const QString& property, const QString& oldValue, const QString& newValue) : m_Source(source) , m_Property(property) , m_OldValue(oldValue) , m_NewValue(newValue) { } IBerryPreferences* IBerryPreferences::ChangeEvent::GetSource() const { return m_Source; } QString IBerryPreferences::ChangeEvent::GetProperty() const { return m_Property; } QString IBerryPreferences::ChangeEvent::GetOldValue() const { return m_OldValue; } QString IBerryPreferences::ChangeEvent::GetNewValue() const { return m_NewValue; } }
22.145455
95
0.665846
gaoxiaojun
b0db5924fca9ef1988ac57895c13e266691e9fae
1,684
cpp
C++
Samples/SampleEditorUI/SampleEditorUI.cpp
AlexSabourinDev/IceBox
9226e15fc5e78e68c0d92ceea51996fdeab36ca7
[ "MIT" ]
3
2020-09-22T15:56:07.000Z
2022-02-08T23:54:50.000Z
Samples/SampleEditorUI/SampleEditorUI.cpp
AlexSabourinDev/IceBox
9226e15fc5e78e68c0d92ceea51996fdeab36ca7
[ "MIT" ]
37
2020-09-21T17:00:17.000Z
2022-02-10T00:30:59.000Z
Samples/SampleEditorUI/SampleEditorUI.cpp
AlexSabourinDev/IceBox
9226e15fc5e78e68c0d92ceea51996fdeab36ca7
[ "MIT" ]
3
2020-10-04T00:46:31.000Z
2022-02-09T00:05:36.000Z
#include <IBEngine/IBRenderer.h> #include <IBEngine/IBRendererFrontend.h> #include <IBEngine/IBSerialization.h> #include <IBEngine/IBLogging.h> #include <IBEngine/IBPlatform.h> #include <imgui/imgui.h> int main() { IB::WindowDesc winDesc = {}; winDesc.Name = "Ice Box"; winDesc.Width = 1024; winDesc.Height = 720; winDesc.OnWindowMessage = [](void *data, IB::WindowMessage message, IB::WindowMessagePlatformData const* platformData) { if (IB::imGuiPlatformMessage(platformData)) { return true; } switch (message.Type) { case IB::WindowMessage::Close: IB::sendQuitMessage(); return true; } return false;; }; IB::Window::Handle window = IB::createWindow(winDesc); IB::RendererDesc rendererDesc = {}; rendererDesc.Window = window; IB::initRenderer(rendererDesc); IB::PlatformMessage message = IB::PlatformMessage::None; while (message != IB::PlatformMessage::Quit) { IB::consumeMessageQueue([](void *data, IB::PlatformMessage message) { *reinterpret_cast<IB::PlatformMessage *>(data) = message; }, &message); IB::newImGuiFrame(); ImGui::Begin("Hello, world!"); ImGui::Text("This is some useful text."); ImGui::End(); ImGui::Render(); IB::ViewDesc viewDesc = {}; // TODO: Call imGui::CloneOutput instead of ImGui::GetDrawData in order to double buffer our rendering. viewDesc.ImGuiDrawData = ImGui::GetDrawData(); IB::drawView(viewDesc); } IB::killRenderer(); IB::destroyWindow(window); }
26.730159
122
0.610451
AlexSabourinDev
b0e087b548cb6df0d04f44e3f91c2daa82296873
438
cpp
C++
src/publisher/distributions_publisher.cpp
doge-of-the-day/cslibs_mapping
f8c9790ef0148c26792ad5af7086db792f693955
[ "BSD-3-Clause" ]
36
2018-11-13T09:45:17.000Z
2022-01-04T00:46:45.000Z
src/publisher/distributions_publisher.cpp
doge-of-the-day/cslibs_mapping
f8c9790ef0148c26792ad5af7086db792f693955
[ "BSD-3-Clause" ]
7
2019-04-29T08:15:19.000Z
2022-02-20T17:07:09.000Z
src/publisher/distributions_publisher.cpp
doge-of-the-day/cslibs_mapping
f8c9790ef0148c26792ad5af7086db792f693955
[ "BSD-3-Clause" ]
19
2018-05-19T06:45:49.000Z
2022-01-04T00:46:50.000Z
#include "distributions_publisher.h" #include <class_loader/register_macro.hpp> CLASS_LOADER_REGISTER_CLASS(cslibs_mapping::publisher::DistributionsPublisher, cslibs_mapping::publisher::Publisher) CLASS_LOADER_REGISTER_CLASS(cslibs_mapping::publisher::DistributionsPublisher_d, cslibs_mapping::publisher::Publisher) CLASS_LOADER_REGISTER_CLASS(cslibs_mapping::publisher::DistributionsPublisher_f, cslibs_mapping::publisher::Publisher)
62.571429
118
0.874429
doge-of-the-day
b0e36556bc0154e91df605d98e8963ae2ad0f877
4,032
cpp
C++
activemq-cpp/src/test/decaf/util/zip/CheckedOutputStreamTest.cpp
novomatic-tech/activemq-cpp
d6f76ede90d21b7ee2f0b5d4648e440e66d63003
[ "Apache-2.0" ]
87
2015-03-02T17:58:20.000Z
2022-02-11T02:52:52.000Z
activemq-cpp/src/test/decaf/util/zip/CheckedOutputStreamTest.cpp
novomatic-tech/activemq-cpp
d6f76ede90d21b7ee2f0b5d4648e440e66d63003
[ "Apache-2.0" ]
3
2017-06-14T15:21:50.000Z
2020-08-03T19:51:57.000Z
activemq-cpp/src/test/decaf/util/zip/CheckedOutputStreamTest.cpp
novomatic-tech/activemq-cpp
d6f76ede90d21b7ee2f0b5d4648e440e66d63003
[ "Apache-2.0" ]
71
2015-04-28T06:04:04.000Z
2022-03-15T13:34:06.000Z
/* * 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 "CheckedOutputStreamTest.h" #include <decaf/util/zip/CheckedOutputStream.h> #include <decaf/util/zip/Adler32.h> #include <decaf/util/zip/CRC32.h> #include <decaf/io/ByteArrayOutputStream.h> using namespace std; using namespace decaf; using namespace decaf::io; using namespace decaf::lang; using namespace decaf::lang::exceptions; using namespace decaf::util; using namespace decaf::util::zip; //////////////////////////////////////////////////////////////////////////////// CheckedOutputStreamTest::CheckedOutputStreamTest() { } //////////////////////////////////////////////////////////////////////////////// CheckedOutputStreamTest::~CheckedOutputStreamTest() { } //////////////////////////////////////////////////////////////////////////////// void CheckedOutputStreamTest::testConstructor() { ByteArrayOutputStream baos; CRC32 check; CheckedOutputStream chkOut( &baos, &check ); CPPUNIT_ASSERT_EQUAL_MESSAGE( "the checkSum value of the constructor is not 0", 0LL, chkOut.getChecksum()->getValue() ); } //////////////////////////////////////////////////////////////////////////////// void CheckedOutputStreamTest::testGetChecksum() { unsigned char byteArray[] = { 1, 2, 3, 'e', 'r', 't', 'g', 3, 6 }; ByteArrayOutputStream baos; Adler32 check; CheckedOutputStream chkOut( &baos, &check ); chkOut.write( byteArray[4] ); // ran JDK and found that checkSum value is 7536755 CPPUNIT_ASSERT_EQUAL_MESSAGE( "the checkSum value for writeI is incorrect", 7536755LL, chkOut.getChecksum()->getValue()); chkOut.getChecksum()->reset(); chkOut.write( byteArray, 9, 5, 4 ); // ran JDK and found that checkSum value is 51708133 CPPUNIT_ASSERT_EQUAL_MESSAGE( "the checkSum value for writeBII is incorrect ", 51708133LL, chkOut.getChecksum()->getValue() ); } //////////////////////////////////////////////////////////////////////////////// void CheckedOutputStreamTest::testWriteI() { static const int SIZE = 9; unsigned char byteArray[] = { 1, 2, 3, 'e', 'r', 't', 'g', 3, 6 }; ByteArrayOutputStream baos; CRC32 check; CheckedOutputStream chkOut( &baos, &check ); for( int ix = 0; ix < SIZE; ++ix ) { chkOut.write( byteArray[ix] ); } CPPUNIT_ASSERT_MESSAGE( "the checkSum value is zero, no bytes are written to the output file", chkOut.getChecksum()->getValue() != 0 ); } //////////////////////////////////////////////////////////////////////////////// void CheckedOutputStreamTest::testWriteBIII() { static const int SIZE = 9; unsigned char byteArray[] = { 1, 2, 3, 'e', 'r', 't', 'g', 3, 6 }; ByteArrayOutputStream baos; CRC32 check; CheckedOutputStream chkOut( &baos, &check ); chkOut.write( byteArray, SIZE, 4, 5 ); CPPUNIT_ASSERT_MESSAGE( "the checkSum value is zero, no bytes are written to the output file", chkOut.getChecksum()->getValue() != 0 ); CPPUNIT_ASSERT_THROW_MESSAGE( "Should have thrown an IndexOutOfBoundsException", chkOut.write( byteArray, SIZE, 4, 6 ), IndexOutOfBoundsException ); }
36
98
0.599454
novomatic-tech
b0e6163b32274371f06357425c6645c9ce4a2eda
5,262
cpp
C++
src/Orbit/Graphics/Geometry/Mesh.cpp
Gaztin/Orb
4589f3f0165d287482ab4b367f02633ea4e7c9a5
[ "Zlib" ]
41
2018-08-02T06:28:07.000Z
2022-01-20T01:23:42.000Z
src/Orbit/Graphics/Geometry/Mesh.cpp
Gaztin/Orb
4589f3f0165d287482ab4b367f02633ea4e7c9a5
[ "Zlib" ]
4
2020-02-11T22:10:31.000Z
2020-07-06T19:36:09.000Z
src/Orbit/Graphics/Geometry/Mesh.cpp
Gaztin/Orb
4589f3f0165d287482ab4b367f02633ea4e7c9a5
[ "Zlib" ]
4
2018-11-18T10:19:57.000Z
2021-07-14T02:58:40.000Z
/* * Copyright (c) 2020 Sebastian Kylander https://gaztin.com/ * * This software is provided 'as-is', without any express or implied warranty. In no event will * the authors be held liable for any damages arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, including commercial * applications, and to alter it and redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not claim that you wrote the * original software. If you use this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be misrepresented as * being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "Mesh.h" #include "Orbit/Core/Utility/Utility.h" #include "Orbit/Graphics/API/OpenGL/OpenGLFunctions.h" #include "Orbit/Graphics/Context/RenderContext.h" #include "Orbit/Graphics/Geometry/Geometry.h" ORB_NAMESPACE_BEGIN Mesh::Mesh( std::string_view name ) : name_( name ) { } Geometry Mesh::ToGeometry( void ) const { Geometry geometry( vertex_layout_ ); auto& vb_details = vertex_buffer_->GetDetails(); switch( vb_details.index() ) { #if( ORB_HAS_D3D11 ) case( unique_index_v< Private::_VertexBufferDetailsD3D11, Private::VertexBufferDetails > ): { auto& context = std::get< Private::_RenderContextDetailsD3D11 >( RenderContext::GetInstance().GetPrivateDetails() ); auto& vb_d3d11 = std::get< Private::_VertexBufferDetailsD3D11 >( vb_details ); D3D11_BUFFER_DESC temp_vb_desc; D3D11_MAPPED_SUBRESOURCE temp_vb_mapped; ComPtr< ID3D11Buffer > temp_vb; vb_d3d11.buffer->GetDesc( &temp_vb_desc ); temp_vb_desc.Usage = D3D11_USAGE_DEFAULT; temp_vb_desc.BindFlags = D3D11_BIND_UNORDERED_ACCESS; temp_vb_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; context.device->CreateBuffer( &temp_vb_desc, nullptr, &temp_vb.ptr_ ); context.device_context->CopyResource( temp_vb.ptr_, vb_d3d11.buffer.ptr_ ); context.device_context->Map( temp_vb.ptr_, 0, D3D11_MAP_READ, 0, &temp_vb_mapped ); ////////////////////////////////////////////////////////////////////////// if( index_buffer_ ) { auto& ib_d3d11 = std::get< Private::_IndexBufferDetailsD3D11 >( index_buffer_->GetDetails() ); D3D11_BUFFER_DESC temp_ib_desc; D3D11_MAPPED_SUBRESOURCE temp_ib_mapped; ComPtr< ID3D11Buffer > temp_ib; ib_d3d11.buffer->GetDesc( &temp_ib_desc ); temp_ib_desc.Usage = D3D11_USAGE_DEFAULT; temp_ib_desc.BindFlags = D3D11_BIND_UNORDERED_ACCESS; temp_ib_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; context.device->CreateBuffer( &temp_ib_desc, nullptr, &temp_ib.ptr_ ); context.device_context->CopyResource( temp_ib.ptr_, ib_d3d11.buffer.ptr_ ); context.device_context->Map( temp_ib.ptr_, 0, D3D11_MAP_READ, 0, &temp_ib_mapped ); // Supply geometry with vertex and index data geometry.SetFromData( { static_cast< const uint8_t* >( temp_vb_mapped.pData ), vertex_buffer_->GetTotalSize() }, { static_cast< const uint8_t* >( temp_ib_mapped.pData ), index_buffer_->GetSize() }, index_buffer_->GetFormat() ); context.device_context->Unmap( temp_ib.ptr_, 0 ); } else { // Supply geometry with just vertex data geometry.SetFromData( { static_cast< const uint8_t* >( temp_vb_mapped.pData ), temp_vb_desc.ByteWidth } ); } context.device_context->Unmap( temp_vb.ptr_, 0 ); } break; #endif // ORB_HAS_D3D11 #if( ORB_HAS_OPENGL ) case( unique_index_v< Private::_VertexBufferDetailsOpenGL, Private::VertexBufferDetails > ): { auto& vb_opengl = std::get< Private::_VertexBufferDetailsOpenGL >( vb_details ); const size_t vb_size = ( vertex_buffer_->GetCount() * vertex_layout_.GetStride() ); glBindBuffer( OpenGLBufferTarget::Array, vb_opengl.id ); const void* vb_src = glMapBufferRange( OpenGLBufferTarget::Array, 0, vb_size, OpenGLMapAccess::ReadBit ); if( index_buffer_ ) { auto& ib_opengl = std::get< Private::_IndexBufferDetailsOpenGL >( index_buffer_->GetDetails() ); const size_t ib_size = index_buffer_->GetSize(); glBindBuffer( OpenGLBufferTarget::ElementArray, ib_opengl.id ); const void* ib_src = glMapBufferRange( OpenGLBufferTarget::ElementArray, 0, ib_size, OpenGLMapAccess::ReadBit ); // Supply geometry with vertex and index data geometry.SetFromData( { static_cast< const uint8_t* >( vb_src ), vb_size }, { static_cast< const uint8_t* >( ib_src ), ib_size }, index_buffer_->GetFormat() ); glUnmapBuffer( OpenGLBufferTarget::ElementArray ); glBindBuffer( OpenGLBufferTarget::ElementArray, 0 ); } else { // Supply geometry with just vertex data geometry.SetFromData( { static_cast< const uint8_t* >( vb_src ), vb_size } ); } glUnmapBuffer( OpenGLBufferTarget::Array ); glBindBuffer( OpenGLBufferTarget::Array, 0 ); } break; #endif // ORB_HAS_OPENGL } return geometry; } ORB_NAMESPACE_END
38.691176
231
0.710376
Gaztin
b0e6c5e241c6030a779d5fa4994f246e926a6d0f
3,149
cpp
C++
libhpx/network/SMPNetwork.cpp
luglio/hpx5
6cbeebb8e730ee9faa4487dba31a38e3139e1ce7
[ "BSD-3-Clause" ]
1
2019-11-05T21:11:32.000Z
2019-11-05T21:11:32.000Z
libhpx/network/SMPNetwork.cpp
ldalessa/hpx
c8888c38f5c12c27bfd80026d175ceb3839f0b40
[ "BSD-3-Clause" ]
null
null
null
libhpx/network/SMPNetwork.cpp
ldalessa/hpx
c8888c38f5c12c27bfd80026d175ceb3839f0b40
[ "BSD-3-Clause" ]
3
2019-06-21T07:05:43.000Z
2020-11-21T15:24:04.000Z
// ============================================================================= // High Performance ParalleX Library (libhpx) // // Copyright (c) 2013-2017, Trustees of Indiana University, // All rights reserved. // // This software may be modified and distributed under the terms of the BSD // license. See the COPYING file for details. // // This software was created at the Indiana University Center for Research in // Extreme Scale Technologies (CREST). // ============================================================================= #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "SMPNetwork.h" #include "libhpx/debug.h" #include "libhpx/libhpx.h" #include <cstring> namespace { using libhpx::Network; using libhpx::network::SMPNetwork; using BootNetwork = libhpx::boot::Network; } SMPNetwork::SMPNetwork(const BootNetwork& boot) : Network() { if (boot.getNRanks() > 1) { dbg_error("SMP network does not support multiple ranks.\n"); } } void SMPNetwork::memget(void *to, hpx_addr_t from, size_t size, hpx_addr_t lsync, hpx_addr_t rsync) { dbg_error("SMP string implementation called\n"); } void SMPNetwork::memget(void *to, hpx_addr_t from, size_t size, hpx_addr_t lsync) { dbg_error("SMP string implementation called\n"); } void SMPNetwork::memget(void *to, hpx_addr_t from, size_t size) { dbg_error("SMP string implementation called\n"); } void SMPNetwork::memput(hpx_addr_t to, const void *from, size_t size, hpx_addr_t lsync, hpx_addr_t rsync) { dbg_error("SMP string implementation called\n"); } void SMPNetwork::memput(hpx_addr_t to, const void *from, size_t size, hpx_addr_t rsync) { dbg_error("SMP string implementation called\n"); } void SMPNetwork::memput(hpx_addr_t to, const void *from, size_t size) { dbg_error("SMP string implementation called\n"); } void SMPNetwork::memcpy(hpx_addr_t to, hpx_addr_t from, size_t size, hpx_addr_t lsync) { dbg_error("SMP string implementation called\n"); } void SMPNetwork::memcpy(hpx_addr_t to, hpx_addr_t from, size_t size) { dbg_error("SMP string implementation called\n"); } int SMPNetwork::type() const { return HPX_NETWORK_SMP; } void SMPNetwork::progress(int) { } void SMPNetwork::deallocate(const hpx_parcel_t* p) { dbg_error("The SMP network has not network-managed parcels\n"); } int SMPNetwork::send(hpx_parcel_t *p, hpx_parcel_t *ssync) { dbg_error("SMP network send called\n"); } hpx_parcel_t * SMPNetwork::probe(int nrx) { return NULL; } void SMPNetwork::flush() { } void SMPNetwork::pin(const void *addr, size_t n, void *key) { } void SMPNetwork::unpin(const void *addr, size_t n) { } int SMPNetwork::wait(hpx_addr_t lco, int reset) { return (reset) ? hpx_lco_wait_reset(lco) : hpx_lco_wait(lco); } int SMPNetwork::get(hpx_addr_t lco, size_t n, void *to, int reset) { return (reset) ? hpx_lco_get_reset(lco, n, to) : hpx_lco_get(lco, n, to); } int SMPNetwork::init(void **) { return LIBHPX_OK; } int SMPNetwork::sync(void *in, size_t in_size, void *out, void *c) { void *sendbuf = in; int count = in_size; std::memcpy(out, sendbuf, count); return LIBHPX_OK; }
20.057325
82
0.683709
luglio
b0e83b9727f6a352103a42c6c52790b966114a8e
11,662
cpp
C++
src/EOIconManager.cpp
obones/EVEopenHAB
8e1c603e0c4ebf2b108685dbf5548e3a17a1561c
[ "MIT" ]
null
null
null
src/EOIconManager.cpp
obones/EVEopenHAB
8e1c603e0c4ebf2b108685dbf5548e3a17a1561c
[ "MIT" ]
null
null
null
src/EOIconManager.cpp
obones/EVEopenHAB
8e1c603e0c4ebf2b108685dbf5548e3a17a1561c
[ "MIT" ]
null
null
null
/* @file EOIconManager.cpp @brief Contains the Icon manager definitions @date 2021-09-17 @author Olivier Sannier @section LICENSE MIT License Copyright (c) 2021 Olivier Sannier 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 <esp32HTTPrequest.h> #include <EVE.h> #include "EOIconManager.h" #include "EOSettings.h" #include "EOConstants.h" #include "EODownloadManager.h" #include "reload_color.png.h" #define ICON_HEIGHT 64 #define ICON_WIDTH 64 #define ICON_BYTES_PER_PIXEL 2 #define ICON_BYTE_COUNT (ICON_WIDTH * ICON_HEIGHT * ICON_BYTES_PER_PIXEL) // We are loading PNG files and the datasheet clearly states that the top 42K of RAM_G will be used as a temporary buffer #define RAM_G_MAX_USABLE_ADDRESS (EVE_RAM_G + EVE_RAM_G_SIZE - 42*1024) #define RAM_G_BOTTOM 0 namespace EVEopenHAB { IconManager::IconManager() { reloadIconAddress = RAM_G_MAX_USABLE_ADDRESS - reload_color_png_byte_count; } void IconManager::MainLoop() { if (!staticIconsLoaded) { EVE_cmd_loadimage(reloadIconAddress, EVE_OPT_NODL, reload_color_png, sizeof(reload_color_png)); staticIconsLoaded = true; } startRetrieval(); { std::lock_guard<std::mutex> lock(recordsMutex); for (int recordIndex = 0; recordIndex < records.size(); recordIndex++) { iconRecord& record = records[recordIndex]; switch (record.bitmapState) { case BitmapState::Allocated: if (record.buffer == nullptr) { /*Serial.print("Setting memory for "); Serial.print(recordIndex); Serial.print(" - address = "); Serial.print(record.address); Serial.print(" - byte count = "); Serial.print(ICON_BYTE_COUNT); Serial.println();*/ //EVE_cmd_memzero(record.address, ICON_BYTE_COUNT); EVE_cmd_memset(record.address, 0xF0, ICON_BYTE_COUNT); while (EVE_busy()); record.bitmapState = BitmapState::Initialized; break; } // break is inside the test because if record.buffer is already available, we want to // fall through the call to load image, saving a useless call to memzero case BitmapState::Initialized: if (record.buffer != nullptr) { /*Serial.print("Loading image for "); Serial.print(recordIndex); Serial.print(" - address = "); Serial.print(record.address); Serial.println();*/ EVE_cmd_loadimage(record.address, EVE_OPT_NODL, record.buffer, record.bufferLength); record.bitmapState = BitmapState::Loaded; // Release memory now that the image is transferred to EVE, use a local reference to avoid having record.buffer point to deleted memory uint8_t* buffer = record.buffer; record.buffer = nullptr; delete buffer; } break; case BitmapState::Loaded: break; // nothing, the image has already been transferred and loaded via LOADIMAGE } } } } void IconManager::Reset() { for (int recordIndex = 0; recordIndex < records.size(); recordIndex++) { iconRecord& record = records[recordIndex]; delete(record.buffer); } records.clear(); } IconManager* IconManager::Instance() { static IconManager instance; return &instance; } void iconRequestReadyStateChange(void* optParm, esp32HTTPrequest* request, int readyState) { if (readyState == 4) { /*Serial.println(F("Received a response, processing...")); Serial.print(F(" HTTP response code: ")); Serial.println(request->responseHTTPcode());*/ request->setDebug(false); IconManager* manager = static_cast<IconManager*>(optParm); if (request->responseHTTPcode() == 200) { Serial.println("Icon download success"); std::lock_guard<std::mutex> lock(manager->recordsMutex); IconManager::iconRecord& record = manager->records[manager->indexBeingRetrieved]; record.bufferLength = request->available(); uint8_t *localBuffer = new byte[record.bufferLength]; /*Serial.print(F(" For record ")); Serial.print(manager->indexBeingRetrieved); Serial.print(F(" - name = ")); Serial.print(record.name); Serial.println(); Serial.print(F(" Buffer length = ")); Serial.print(record.bufferLength); Serial.println();*/ request->responseRead(localBuffer, record.bufferLength); record.buffer = localBuffer; } else { Serial.printf("Icon download failed: %d\r\n", request->responseHTTPcode()); } manager->indexBeingRetrieved = -1; } } void IconManager::startRetrieval() { int recordIndex = 0; while (indexBeingRetrieved < 0 && recordIndex < records.size()) { { std::lock_guard<std::mutex> lock(recordsMutex); iconRecord& record = records[recordIndex]; if (record.buffer == nullptr && record.bitmapState < BitmapState::Loaded) { //Serial.printf("--> no buffer for record, preparing request (%d will be %d)\r\n", indexBeingRetrieved, recordIndex); indexBeingRetrieved = recordIndex; String url = BASE_URL; url += "/icon/"; url += record.name; url += "?state="; url += record.state; url += "&format=png&iconset="; url += ICON_SET_NAME; Serial.print("Requesting icon url = "); Serial.println(url); DownloadManager::Instance().Enqueue(url, iconRequestReadyStateChange, this); } } recordIndex++; } } int8_t IconManager::GetIconIndex(const char* name, const char* state) { /*Serial.print("Getting icon index for name = "); Serial.print(reinterpret_cast<uint32_t>(name)); Serial.print(" - state = "); Serial.print(reinterpret_cast<uint32_t>(state)); Serial.println();*/ int8_t result = -1; { std::lock_guard<std::mutex> lock(recordsMutex); // Try to find a preexisting icon for (int recordIndex = 0; recordIndex < records.size(); recordIndex++) { iconRecord& record = records[recordIndex]; if (strcmp(record.name, name) == 0 && strcmp(record.state, state) == 0) return recordIndex + 1; } // If not found, allocate a new one, downards from the top of RAM_G //uint32_t newAddress = RAM_G_MAX_USABLE_ADDRESS - ICON_BYTE_COUNT * (records.size() + 1); // If not found, allocate a new, upwards from the bottom of RAM_G uint32_t newAddress = RAM_G_BOTTOM + ICON_BYTE_COUNT * records.size(); records.push_back( { .name = name, .state = state, .address = newAddress, .buffer = nullptr, .bufferLength = 0, .bitmapState = BitmapState::Allocated } ); result = records.size(); } startRetrieval(); return result; } uint32_t IconManager::GetAddress(int8_t index) { std::lock_guard<std::mutex> lock(recordsMutex); if (index > 0 && index <= records.size()) { iconRecord& record = records[index - 1]; return record.address; } else return 0; } void IconManager::BurstIcon(int8_t index, int16_t x, int16_t y) { std::lock_guard<std::mutex> lock(recordsMutex); if (index > 0 && index <= records.size()) { iconRecord& record = records[index - 1]; /*Serial.print("Bursting icon "); Serial.print(index); Serial.print(" - address = "); Serial.print(record.address); Serial.print(" - at "); Serial.print(x); Serial.print(" ; "); Serial.print(y); Serial.println();*/ EVE_cmd_dl_burst(BITMAP_HANDLE(index)); EVE_cmd_dl_burst(BITMAP_LAYOUT(EVE_ARGB4, ICON_WIDTH * ICON_BYTES_PER_PIXEL, ICON_HEIGHT)); EVE_cmd_dl_burst(BITMAP_SOURCE(record.address)); EVE_cmd_dl_burst(BITMAP_SIZE(EVE_NEAREST, EVE_BORDER, EVE_BORDER, ICON_WIDTH, ICON_HEIGHT)); EVE_cmd_dl_burst(DL_COLOR_RGB | WHITE); EVE_cmd_dl_burst(COLOR_A(255)); EVE_cmd_dl_burst(DL_BEGIN | EVE_BITMAPS); EVE_cmd_dl_burst(VERTEX2F(x, y)); EVE_cmd_dl_burst(DL_END); EVE_cmd_dl_burst(BITMAP_HANDLE(0)); } } uint32_t IconManager::GetReloadIconAddress() const { return reloadIconAddress; } void IconManager::BurstReloadIcon(int16_t x, int16_t y) { EVE_cmd_dl_burst(BITMAP_HANDLE(15)); EVE_cmd_dl_burst(BITMAP_LAYOUT(reload_color_png_format, reload_color_png_width * reload_color_png_bytes_per_pixel, reload_color_png_height)); EVE_cmd_dl_burst(BITMAP_SOURCE(reloadIconAddress)); EVE_cmd_dl_burst(BITMAP_SIZE(EVE_NEAREST, EVE_BORDER, EVE_BORDER, reload_color_png_width, reload_color_png_height)); EVE_cmd_dl_burst(DL_COLOR_RGB | WHITE); EVE_cmd_dl_burst(COLOR_A(255)); EVE_cmd_dl_burst(DL_BEGIN | EVE_BITMAPS); EVE_cmd_dl_burst(VERTEX2F(x, y)); EVE_cmd_dl_burst(DL_END); EVE_cmd_dl_burst(BITMAP_HANDLE(0)); } }
38.361842
166
0.56877
obones
b0e84489f0c86ffe4e3db2718d2190e7ebb1f849
85
cpp
C++
node.cpp
Qt-Widgets/SPICE-circuit
f43bac80ef7322948eb89cdeb899751c25252d29
[ "MIT" ]
9
2020-05-04T13:21:39.000Z
2022-03-13T05:44:58.000Z
node.cpp
s94285/SPICE
f43bac80ef7322948eb89cdeb899751c25252d29
[ "MIT" ]
null
null
null
node.cpp
s94285/SPICE
f43bac80ef7322948eb89cdeb899751c25252d29
[ "MIT" ]
6
2019-09-28T06:02:04.000Z
2021-12-18T21:39:44.000Z
#include "node.h" Node::Node(QGraphicsItem *parent):QGraphicsItemGroup(parent) { }
12.142857
60
0.741176
Qt-Widgets
b0f3f757c800a88e77992bee09870e2a61d29e1a
919
cpp
C++
Engine/Core/Sources/Threading/Thread.cpp
kaluginadaria/YetAnotherProject
abedd20b484f868ded83e72261970703a27e024d
[ "MIT" ]
null
null
null
Engine/Core/Sources/Threading/Thread.cpp
kaluginadaria/YetAnotherProject
abedd20b484f868ded83e72261970703a27e024d
[ "MIT" ]
null
null
null
Engine/Core/Sources/Threading/Thread.cpp
kaluginadaria/YetAnotherProject
abedd20b484f868ded83e72261970703a27e024d
[ "MIT" ]
null
null
null
#include "Thread.hpp" #include <chrono> #include <iostream> #include "ThreadPool.hpp" const ThreadTask ThreadTask::NoTasksFound = ThreadTask(nullptr, ThreadTask::eNoTasksFound); const ThreadTask ThreadTask::ShouldDie = ThreadTask(nullptr, ThreadTask::eShouldDie ); const ThreadTask ThreadTask::NextLoop = ThreadTask(nullptr, ThreadTask::eNextLoop ); UNIQUE(Thread) Thread::Get() { return std::make_unique<Thread>(); } ThreadID Thread::GetThreadID() { return std::this_thread::get_id(); } void Thread::Run() { std::thread([&]() { using namespace std::chrono_literals; ThreadTask currentTask = ThreadTask::NextLoop; while ((currentTask = ThreadPool::GetRunTask(this, currentTask.task)) != ThreadTask::ShouldDie) { // try to take a new task if (currentTask.task == nullptr) { std::this_thread::sleep_for(5us); continue; } currentTask.task->Run(); } }).detach(); }
22.414634
97
0.70185
kaluginadaria
b0f4c4427b61d94ca4b0c9f66aedb58a2a93a545
4,264
cc
C++
code/render/frame/framepass.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/render/frame/framepass.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/render/frame/framepass.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
//------------------------------------------------------------------------------ // framepass.cc // (C) 2007 Radon Labs GmbH // (C) 2013-2016 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "frame/framepass.h" #include "coregraphics/renderdevice.h" namespace Frame { __ImplementClass(Frame::FramePass, 'FPSS', Frame::FramePassBase); using namespace CoreGraphics; //------------------------------------------------------------------------------ /** */ FramePass::FramePass() { // empty } //------------------------------------------------------------------------------ /** */ FramePass::~FramePass() { // empty } //------------------------------------------------------------------------------ /** */ void FramePass::Discard() { FramePassBase::Discard(); #if NEBULA3_ENABLE_PROFILING _discard_timer(debugTimer); #endif } //------------------------------------------------------------------------------ /** */ void FramePass::Render(IndexT frameIndex) { #if NEBULA3_ENABLE_PROFILING _start_timer(this->debugTimer); #endif n_assert(this->renderTarget.isvalid() || this->multipleRenderTarget.isvalid() || this->renderTargetCube.isvalid()); RenderDevice* renderDevice = RenderDevice::Instance(); if (this->renderTarget.isvalid()) { n_assert(!this->multipleRenderTarget.isvalid()); n_assert(!this->renderTargetCube.isvalid()); // update render targets this->renderTarget->SetClearFlags(this->clearFlags); this->renderTarget->SetClearDepth(this->clearDepth); this->renderTarget->SetClearStencil(this->clearStencil); this->renderTarget->SetClearColor(this->clearColor); } else if (this->renderTargetCube.isvalid()) { n_assert(!this->renderTarget.isvalid()); n_assert(!this->multipleRenderTarget.isvalid()); // update render targets this->renderTargetCube->SetClearFlags(this->clearFlags); this->renderTargetCube->SetClearDepth(this->clearDepth); this->renderTargetCube->SetClearStencil(this->clearStencil); this->renderTargetCube->SetClearColor(this->clearColor); } else if (this->multipleRenderTarget.isvalid()) { // ignore clear flags n_assert(!this->renderTarget.isvalid()); n_assert(!this->renderTargetCube.isvalid()); } // begin updating global shader state if (this->shader.isvalid()) this->shader->BeginUpdate(); // apply shader variables IndexT varIndex; for (varIndex = 0; varIndex < this->shaderVariables.Size(); varIndex++) { this->shaderVariables[varIndex]->Apply(); } // bind render target, either 2D, MRT, or Cube if (this->renderTarget.isvalid()) { n_assert(!this->multipleRenderTarget.isvalid()); n_assert(!this->renderTargetCube.isvalid()); renderDevice->BeginPass(this->renderTarget, this->shader); } else if (this->multipleRenderTarget.isvalid()) { n_assert(!this->renderTarget.isvalid()); n_assert(!this->renderTargetCube.isvalid()); renderDevice->BeginPass(this->multipleRenderTarget, this->shader); } else if (this->renderTargetCube.isvalid()) { n_assert(!this->renderTarget.isvalid()); n_assert(!this->multipleRenderTarget.isvalid()); renderDevice->BeginPass(this->renderTargetCube, this->shader); } else { n_error("FramePass::Render() : No render targets assigned!"); } if (this->shader.isvalid()) this->shader->EndUpdate(); // render batches... IndexT batchIndex; for (batchIndex = 0; batchIndex < this->batches.Size(); batchIndex++) { FRAME_LOG(" FramePass::Render() %s batch: %d", this->GetName().AsString().AsCharPtr(), batchIndex); this->batches[batchIndex]->Render(frameIndex); FRAME_LOG(" "); } renderDevice->EndPass(); #if NEBULA3_ENABLE_PROFILING _stop_timer(this->debugTimer); #endif } //------------------------------------------------------------------------------ /** */ #if NEBULA3_ENABLE_PROFILING void FramePass::SetFramePassDebugTimer(const Util::String& name) { this->debugTimer = Debug::DebugTimer::Create(); this->debugTimer->Setup(name, "Frame shaders"); } #endif } // namespace Frame
28.810811
119
0.593105
gscept
b0f60b2f479203abc4d193336bbf8798ec23bcb9
987
cpp
C++
opencv/resize/test.cpp
ericosur/ccbox
c230bd77533bf9a8af8f7183ea2cd2ae019716f7
[ "MIT" ]
null
null
null
opencv/resize/test.cpp
ericosur/ccbox
c230bd77533bf9a8af8f7183ea2cd2ae019716f7
[ "MIT" ]
10
2020-07-14T04:00:12.000Z
2020-07-14T05:30:48.000Z
opencv/resize/test.cpp
ericosur/ccbox
c230bd77533bf9a8af8f7183ea2cd2ae019716f7
[ "MIT" ]
null
null
null
#include "mytool/mytool.h" #include <iostream> #include <string> #include <opencv2/opencv.hpp> #include <nlohmann/json.hpp> #define SETTING_JSON "../setting.json" #define DEFAULT_TESTIMAGE "lena.png" #define REPEAT 200 void test() { using namespace std; using namespace cv; string test_image = mytool::get_string_from_jsonfile(SETTING_JSON, "test_image", DEFAULT_TESTIMAGE); if ( !mytool::is_file_exist(test_image) ) { cout << "test iamge not found: " << test_image << "\n"; return; } Mat src = imread(test_image); Mat dst, dst2, dst3; for (int i = REPEAT; i > 0; --i) { // specify fx and fy and let the function compute the destination image size. resize(src, dst, Size(), 0.01*i, 0.01*i); resize(src, dst2, Size(), 0.01*i, 0.01*i, INTER_AREA); resize(src, dst3, Size(), 0.01*i, 0.02*i, INTER_CUBIC); } // imshow("test", dst); // waitKey(0); // destroyAllWindows(); }
25.973684
104
0.616008
ericosur
b0fc14f5f8731d40220a3a0ae1b98fd5e95e000e
2,122
cc
C++
content/renderer/webcrypto_impl.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/webcrypto_impl.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/webcrypto_impl.cc
kurli/chromium-crosswalk
f4c5d15d49d02b74eb834325e4dff50b16b53243
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/webcrypto_impl.h" #include "base/memory/scoped_ptr.h" #include "third_party/WebKit/public/platform/WebArrayBuffer.h" #include "third_party/WebKit/public/platform/WebCryptoAlgorithm.h" #include "third_party/WebKit/public/platform/WebCryptoKey.h" namespace content { WebCryptoImpl::WebCryptoImpl() { Init(); } void WebCryptoImpl::digest( const WebKit::WebCryptoAlgorithm& algorithm, const unsigned char* data, unsigned data_size, WebKit::WebCryptoResult result) { WebKit::WebArrayBuffer buffer; if (!DigestInternal(algorithm, data, data_size, &buffer)) { result.completeWithError(); } else { result.completeWithBuffer(buffer); } } void WebCryptoImpl::importKey( WebKit::WebCryptoKeyFormat format, const unsigned char* key_data, unsigned key_data_size, const WebKit::WebCryptoAlgorithm& algorithm, bool extractable, WebKit::WebCryptoKeyUsageMask usage_mask, WebKit::WebCryptoResult result) { WebKit::WebCryptoKeyType type; scoped_ptr<WebKit::WebCryptoKeyHandle> handle; if (!ImportKeyInternal(format, key_data, key_data_size, algorithm, usage_mask, &handle, &type)) { result.completeWithError(); return; } WebKit::WebCryptoKey key( WebKit::WebCryptoKey::create( handle.release(), type, extractable, algorithm, usage_mask)); result.completeWithKey(key); } void WebCryptoImpl::sign( const WebKit::WebCryptoAlgorithm& algorithm, const WebKit::WebCryptoKey& key, const unsigned char* data, unsigned data_size, WebKit::WebCryptoResult result) { WebKit::WebArrayBuffer buffer; if (!SignInternal(algorithm, key, data, data_size, &buffer)) { result.completeWithError(); } else { result.completeWithBuffer(buffer); } } } // namespace content
28.293333
73
0.683318
kurli
b0fd829d724b15a07c5ecd6beb1d8c252f061e2c
1,396
hpp
C++
Engine/Math/Dice.hpp
achen889/Warlockery_Engine
160a14e85009057f4505ff5380a8c17258698f3e
[ "MIT" ]
null
null
null
Engine/Math/Dice.hpp
achen889/Warlockery_Engine
160a14e85009057f4505ff5380a8c17258698f3e
[ "MIT" ]
null
null
null
Engine/Math/Dice.hpp
achen889/Warlockery_Engine
160a14e85009057f4505ff5380a8c17258698f3e
[ "MIT" ]
null
null
null
//============================================================================================================== //Dice.hpp //by Albert Chen Sep-2-2015. //============================================================================================================== #pragma once #ifndef _included_Dice__ #define _included_Dice__ #include "IntVec3.hpp" #include "Engine/Core/Utilities.hpp" #include "MathUtils.hpp" //typedef IntVec3 Dice; //x for number of dice, y for size of dice (1-y), z for modifier //dice utility functions struct Dice { //vars IntVec3 diceDef; //operator overload Dice() { //do nothing } Dice(const std::string& diceString); const Dice& operator=(const std::string& diceStrToAssign); const int RollDice() const ; const std::string ToString() { return Stringf("%dd%d+%d", diceDef.x, diceDef.y, diceDef.z); } }; //=========================================================================================================== ///---------------------------------------------------------------------------------------------------------- ///globals int RollDice(const Dice& dice); int RollDice(const std::string& diceString); std::string DiceToString(const Dice& dice); Dice ParseStringToDice(const std::string& diceString); //=========================================================================================================== #endif
22.885246
112
0.424785
achen889
b0fe5b28fc38aa1790c14a9e84139604f3c35998
549
cpp
C++
podboat.cpp
adiel-mittmann/newsboat
8011952624387f0b2fcb18ba5d96382c257764c2
[ "MIT" ]
null
null
null
podboat.cpp
adiel-mittmann/newsboat
8011952624387f0b2fcb18ba5d96382c257764c2
[ "MIT" ]
null
null
null
podboat.cpp
adiel-mittmann/newsboat
8011952624387f0b2fcb18ba5d96382c257764c2
[ "MIT" ]
null
null
null
#include <iostream> #include <config.h> #include <pb_controller.h> #include <cstring> #include <pb_view.h> #include <errno.h> #include <utils.h> using namespace podboat; int main(int argc, char * argv[]) { utils::initialize_ssl_implementation(); if (!setlocale(LC_CTYPE,"") || !setlocale(LC_MESSAGES,"")) { std::cerr << "setlocale failed: " << strerror(errno) << std::endl; return 1; } bindtextdomain (PACKAGE, LOCALEDIR); textdomain (PACKAGE); pb_controller c; podboat::pb_view v(&c); c.set_view(&v); return c.run(argc, argv); }
19.607143
68
0.68306
adiel-mittmann
7c04605bb9c6d08c1c8c8e187b9100d340905be5
1,192
c++
C++
linker_script/strategies/default_e20_strategy.c++
sctincman/freedom-devicetree-tools
668d8795e474623863f65f890022d1d471a1c64b
[ "Apache-2.0", "MIT" ]
null
null
null
linker_script/strategies/default_e20_strategy.c++
sctincman/freedom-devicetree-tools
668d8795e474623863f65f890022d1d471a1c64b
[ "Apache-2.0", "MIT" ]
null
null
null
linker_script/strategies/default_e20_strategy.c++
sctincman/freedom-devicetree-tools
668d8795e474623863f65f890022d1d471a1c64b
[ "Apache-2.0", "MIT" ]
null
null
null
/* Copyright (c) 2019 SiFive Inc. */ /* SPDX-License-Identifier: Apache-2.0 */ #include "default_e20_strategy.h" #include <layouts/default_layout.h> #include <layouts/scratchpad_layout.h> #include <layouts/ramrodata_layout.h> bool DefaultE20Strategy::valid(const fdt &dtb, list<Memory> available_memories) { return has_testram(available_memories); } LinkerScript DefaultE20Strategy::create_layout(const fdt &dtb, list<Memory> available_memories, LinkStrategy link_strategy) { Memory rom_memory = find_testram(available_memories); rom_memory.name = "ram"; rom_memory.attributes = "wxa!ri"; /* Generate the layouts */ print_chosen_strategy("DefaultE20Strategy", link_strategy, rom_memory, rom_memory, rom_memory); switch (link_strategy) { default: case LINK_STRATEGY_DEFAULT: return DefaultLayout(dtb, rom_memory, rom_memory, rom_memory, rom_memory); break; case LINK_STRATEGY_SCRATCHPAD: return ScratchpadLayout(dtb, rom_memory, rom_memory, rom_memory, rom_memory); break; case LINK_STRATEGY_RAMRODATA: return RamrodataLayout(dtb, rom_memory, rom_memory, rom_memory, rom_memory); break; } }
29.073171
97
0.738255
sctincman
7c05632785ddee5669c5f9c890236c674cefce29
585
cpp
C++
cilantro/src/graphics/Framebuffer.cpp
dpilawa/cilantro
69daa2112e8e373783b4f1a27c62770e4540eb6f
[ "MIT" ]
null
null
null
cilantro/src/graphics/Framebuffer.cpp
dpilawa/cilantro
69daa2112e8e373783b4f1a27c62770e4540eb6f
[ "MIT" ]
null
null
null
cilantro/src/graphics/Framebuffer.cpp
dpilawa/cilantro
69daa2112e8e373783b4f1a27c62770e4540eb6f
[ "MIT" ]
null
null
null
#include "cilantroengine.h" #include "graphics/Framebuffer.h" Framebuffer::Framebuffer (unsigned int bufferWidth, unsigned int bufferHeight) { this->bufferWidth = bufferWidth; this->bufferHeight = bufferHeight; } Framebuffer::~Framebuffer () { } unsigned int Framebuffer::GetWidth () const { return bufferWidth; } unsigned int Framebuffer::GetHeight () const { return bufferHeight; } void Framebuffer::SetFramebufferResolution (unsigned int bufferWidth, unsigned int bufferHeight) { this->bufferWidth = bufferWidth; this->bufferHeight = bufferHeight; }
19.5
96
0.745299
dpilawa
7c0597aa563fb5f1065fc14f1813fe249d8a795c
433
cpp
C++
W08/in_lab/Account.cpp
ariaav/OOP244
bcfc52bfff86b68e4f464e85b8555eef541741a0
[ "MIT" ]
null
null
null
W08/in_lab/Account.cpp
ariaav/OOP244
bcfc52bfff86b68e4f464e85b8555eef541741a0
[ "MIT" ]
null
null
null
W08/in_lab/Account.cpp
ariaav/OOP244
bcfc52bfff86b68e4f464e85b8555eef541741a0
[ "MIT" ]
null
null
null
#include <iostream> #include "Account.h" namespace sict { Account::Account(double bal) { if (bal > 0) bala = bal; else bala = 0; } bool Account::credit(double add) { if (add > 0){ bala += add; return true; } else return false; } bool Account::debit(double sub) { if (sub > 0) { bala -= sub; return true; } else return false; } double Account::balance() const { return bala; } }
12.371429
35
0.577367
ariaav
7c0fe5fd6a310e5dd2f79b822fe425d9cce77f87
851
cpp
C++
amara/amara_tweenBase.cpp
BigBossErndog/Amara
e534001dee88b7d66f7384ed167257ffac58aac3
[ "MIT" ]
null
null
null
amara/amara_tweenBase.cpp
BigBossErndog/Amara
e534001dee88b7d66f7384ed167257ffac58aac3
[ "MIT" ]
null
null
null
amara/amara_tweenBase.cpp
BigBossErndog/Amara
e534001dee88b7d66f7384ed167257ffac58aac3
[ "MIT" ]
null
null
null
#ifndef AMARA_TWEENBASE #define AMARA_TWEENBASE #include "amara.h" namespace Amara { class Tweener; class Tween: public Amara::StateManager { public: Amara::GameProperties* properties = nullptr; bool finished = false; bool deleteOnFinish = true; double progress = 0; float time = 0; virtual void assign(Amara::Tweener* gTweener, Amara::GameProperties* gProperties) { properties = gProperties; } virtual void run() { progress += (time/properties->lps); if (progress >= 1) { finished = true; progress = 1; } } virtual void reset() { progress = 0; } }; } #endif
23.638889
95
0.480611
BigBossErndog
7c11f304a4c71c599e3aa18728323cf90f51aaa3
2,138
cc
C++
2021/5/main.cc
ey6es/aoc
c1e54534e5e6d4b52118ffd173834ab56a831102
[ "MIT" ]
null
null
null
2021/5/main.cc
ey6es/aoc
c1e54534e5e6d4b52118ffd173834ab56a831102
[ "MIT" ]
null
null
null
2021/5/main.cc
ey6es/aoc
c1e54534e5e6d4b52118ffd173834ab56a831102
[ "MIT" ]
null
null
null
#include <algorithm> #include <fstream> #include <iostream> #include <map> #include <string> #include <tuple> std::tuple<int, int> parse_coord (const std::string& str) { auto idx = str.find(','); return std::make_tuple( std::stoi(str.substr(0, idx)), std::stoi(str.substr(idx + 1))); } std::ostream& operator<< (std::ostream& out, const std::tuple<int, int>& tuple) { return out << std::get<0>(tuple) << " " << std::get<1>(tuple); } int main () { std::ifstream in("input.txt"); std::map<std::tuple<int, int>, int> points; while (in.good()) { std::string line; std::getline(in, line); if (!in.good()) break; auto start = parse_coord(line.substr(0, line.find(' '))); auto end = parse_coord(line.substr(line.rfind(' ') + 1)); auto sx = std::get<0>(start); auto sy = std::get<1>(start); auto ex = std::get<0>(end); auto ey = std::get<1>(end); if (sx == ex) { // vertical line auto x = sx; auto minmax_y = std::minmax(sy, ey); for (auto y = minmax_y.first; y <= minmax_y.second; y++) { points[std::make_tuple(x, y)]++; } } else if (sy == ey) { // horizontal auto y = sy; auto minmax_x = std::minmax(sx, ex); for (auto x = minmax_x.first; x <= minmax_x.second; x++) { points[std::make_tuple(x, y)]++; } } else { auto dx = ex - sx; auto dy = ey - sy; if (dx == dy) { if (dx > 0) { for (auto c = 0; c <= dx; c++) { points[std::make_tuple(sx + c, sy + c)]++; } } else { for (auto c = dx; c <= 0; c++) { points[std::make_tuple(sx + c, sy + c)]++; } } } else if (dx == -dy) { if (dx > 0) { for (auto c = 0; c <= dx; c++) { points[std::make_tuple(sx + c, sy - c)]++; } } else { for (auto c = dx; c <= 0; c++) { points[std::make_tuple(sx + c, sy - c)]++; } } } } } int count = 0; for (auto& pair : points) { if (pair.second >= 2) count++; } std::cout << count << std::endl; }
24.860465
81
0.481291
ey6es
7c1885c5d71e72c411d50181d4b84e586de72b3f
635
cpp
C++
0014.cpp
excript/curso_cpp
070d0bd1163c1252b7bf736fedb3370208c30811
[ "CC0-1.0" ]
1
2020-08-01T07:03:32.000Z
2020-08-01T07:03:32.000Z
0014.cpp
excript/curso_cpp
070d0bd1163c1252b7bf736fedb3370208c30811
[ "CC0-1.0" ]
1
2020-08-01T07:04:27.000Z
2020-08-01T07:04:27.000Z
0014.cpp
excript/curso_cpp
070d0bd1163c1252b7bf736fedb3370208c30811
[ "CC0-1.0" ]
null
null
null
#include <iostream> #include <stdlib.h> #include <iomanip> /*==================================== * eXcript.com * fb.com/eXcript * ====================================*/ using namespace std; int main() { //obj cin3 //obj cout cout << "Estudando a entrada e saida de dados." << endl; // cout << setw(10) << 1 << endl; // cout << setw(10) << 2 << endl; // cout << setw(10) << 3 << endl; // cout << setw(10) << 4 << endl; cout << setw(10) << 1456; cout << setw(10) << 25343543; cout << setw(10) << 3456546; cout << setw(10) << 44455; system("pause"); return 0; }
19.84375
60
0.445669
excript
7c1b5d88f091c7ddf7a60fc1969c757257d02a8d
907
hh
C++
src/agents/pacman/pathfinding_pacman_agent.hh
emanuelssj/PacmanRL
275715f7024e1ffab8a562c892a9852d4d7f16cb
[ "MIT" ]
3
2019-01-07T10:15:21.000Z
2019-03-25T15:36:39.000Z
src/agents/pacman/pathfinding_pacman_agent.hh
emanuelssj/Lunafreya-Pacman-Speedrun
275715f7024e1ffab8a562c892a9852d4d7f16cb
[ "MIT" ]
null
null
null
src/agents/pacman/pathfinding_pacman_agent.hh
emanuelssj/Lunafreya-Pacman-Speedrun
275715f7024e1ffab8a562c892a9852d4d7f16cb
[ "MIT" ]
1
2019-05-26T07:48:21.000Z
2019-05-26T07:48:21.000Z
#ifndef PATHFINDING_PACMAN_AGENT_HH #define PATHFINDING_PACMAN_AGENT_HH #include "../agent.hh" #include "../../state/direction.hh" #include "../../pathfinding/bfs.hh" #include "../../pathfinding/wsp.hh" #include <cmath> class Pathfinding_Pacman_Agent: public Agent { // In this case ghost_id can be ignored inline Direction take_action(const State& s, uint ghost_id) { if (s.distance_closest_harmful_ghost(s.pacman.pos) < 10) { return wsp(s.pacman.pos, [&s](const Position& pos) { return s.has_any_pill(pos); }, s, [&s](const Position& pos) { return 10*pow(2, 10 - min(10,s.distance_closest_harmful_ghost(pos))); } ).dir; } else return bfs(s.pacman.pos, [&s](const Position& pos) { return s.has_any_pill(pos); }, s).dir; } }; #endif
32.392857
122
0.582139
emanuelssj
7c21bfccc01efd7eb0c020508aee97d438dd283a
3,971
cpp
C++
cpr/unit_test_for_huffman/unit_test_for_bit_string.cpp
Mooophy/Compression
2d369956a83703f0283d36d438e76783e909957d
[ "MIT" ]
14
2015-03-04T23:12:03.000Z
2021-07-14T14:30:45.000Z
cpr/unit_test_for_huffman/unit_test_for_bit_string.cpp
Mooophy/Compression
2d369956a83703f0283d36d438e76783e909957d
[ "MIT" ]
7
2015-03-02T08:52:54.000Z
2015-03-09T08:32:09.000Z
cpr/unit_test_for_huffman/unit_test_for_bit_string.cpp
Mooophy/Compression
2d369956a83703f0283d36d438e76783e909957d
[ "MIT" ]
7
2015-03-04T23:13:14.000Z
2017-05-24T11:39:55.000Z
#include "stdafx.h" #include "CppUnitTest.h" #include "../huffman/bit_string.hpp" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace unit_test_for_huffman { TEST_CLASS(unit_test_for_bit_string) { public: TEST_METHOD(ctor) { cpr::huffman::BitString<char> bit_string; } TEST_METHOD(data) { cpr::huffman::BitString<char> bit_string; Assert::AreEqual(0u, bit_string.str().size()); } TEST_METHOD(bit_length) { cpr::huffman::BitString<char> bit_string; Assert::AreEqual(1u, bit_string.bit_length(0x00)); Assert::AreEqual(7u, bit_string.bit_length(0x7f)); Assert::AreEqual(8u, bit_string.bit_length(-0x01)); Assert::AreEqual(8u, bit_string.bit_length(-0x7f)); Assert::AreEqual(8u, bit_string.bit_length(-0x80)); Assert::AreNotEqual(8u, bit_string.bit_length((char)-0x81)); } TEST_METHOD(push_back_bits) { // case 1 cpr::huffman::BitString<char> bit_string; bit_string.push_back_bits(0); Assert::AreEqual((char)0, bit_string.str().front()); bit_string.push_back_bits((char)0xff); std::string expected(1, 0); expected += std::string(8, 1); Assert::AreEqual(expected, bit_string.str()); Assert::AreEqual(9u, bit_string.str().size()); //case 2 cpr::huffman::BitString<char> bs_for_testing_minus_number; bs_for_testing_minus_number.push_back_bits(char(-1)); Assert::AreEqual(8u, bs_for_testing_minus_number.str().size()); bs_for_testing_minus_number.push_back_bits(0); Assert::AreEqual(9u, bs_for_testing_minus_number.str().size()); //case 3 cpr::huffman::BitString<char> case3; case3.push_back_bits(0x07); std::string expected_for_case3(3, 1); Assert::AreEqual(expected_for_case3, case3.str()); } // protocol : // FrequencyTable|CompressedPart|Remainder|RemainderSize TEST_METHOD(compress_case1) { cpr::huffman::BitString<char> bit_string; bit_string.push_back_bits((char)0); std::string compressed = bit_string.compress('|'); //note the compressed part is empty Assert::AreEqual(4u, compressed.size()); std::string exprected{ '|', 0, '|', 1 }; Assert::AreEqual(exprected, compressed); } TEST_METHOD(compress_case2) { cpr::huffman::BitString<char> bit_string; bit_string.push_back_bits((char)0xff); std::string compressed = bit_string.compress('|'); Assert::AreEqual(5u, compressed.size()); std::string exprected{ (char)0xff, '|', 0, '|', 0 }; Assert::AreEqual(exprected, compressed); } TEST_METHOD(compress_case3) { cpr::huffman::BitString<char> bit_string; bit_string.push_back_bits((char)0X00); bit_string.push_back_bits((char)0Xff); std::string compressed = bit_string.compress('|'); Assert::AreEqual(5u, compressed.size()); std::string exprected{ (char)0x7f, '|', 1, '|', 1 }; Assert::AreEqual(exprected, compressed); } TEST_METHOD(compress_case4) { cpr::huffman::BitString<char> bit_string; bit_string.push_back_bits((char)0X00); bit_string.push_back_bits((char)0Xff); bit_string.push_back_bits((char)0Xff); std::string compressed = bit_string.compress('|'); Assert::AreEqual(6u, compressed.size()); std::string exprected{ (char)0x7f, (char)0xff, '|', 1, '|', 1 }; Assert::AreEqual(exprected, compressed); } }; }
33.940171
76
0.578444
Mooophy
7c283dc0e0c52f8c51f5f4a8f987d346aa6b947f
2,624
cpp
C++
Utilities/MarbleAction/MarbleAction.cpp
mym2o/HavokDemos
1235b96b93e256de50bc36c229439a334410fd77
[ "MIT" ]
1
2017-08-14T10:23:45.000Z
2017-08-14T10:23:45.000Z
Utilities/MarbleAction/MarbleAction.cpp
mym2o/HavokDemos
1235b96b93e256de50bc36c229439a334410fd77
[ "MIT" ]
null
null
null
Utilities/MarbleAction/MarbleAction.cpp
mym2o/HavokDemos
1235b96b93e256de50bc36c229439a334410fd77
[ "MIT" ]
2
2016-06-22T02:22:32.000Z
2019-11-21T19:49:41.000Z
#include "MarbleAction.h" MarbleAction::MarbleAction(hkpRigidBody* r, const hkVector4& forward, const hkVector4& resetPosition, hkReal impulseScale) : hkpUnaryAction(r), m_forward(forward), m_resetPosition(resetPosition), m_rotationIncrement(0.01f) { m_forwardPressed = false; m_backwardPressed = false; m_leftPressed = false; m_rightPressed = false; m_jumpPressed = false; m_brakePressed = false; m_lastJump = 0.f; m_impulseScale = impulseScale; m_lasttimeCalled = 0.f; m_currentAngle = 0.f; } void MarbleAction::applyAction(const hkStepInfo& stepInfo) { hkpRigidBody* rb = getRigidBody(); //we need the delta time to record how long it's been since we last jumped //(to avoid jumping while in the air!) hkReal dt = stepInfo.m_deltaTime; //get a "scale" to change the force of the impulse by, depending on both the mass of the body, //an arbitrary "gain", eg 0.1 hkReal scale = rb->getMass() * m_impulseScale; hkVector4 axis(0, 1, 0); hkQuaternion q(axis, m_currentAngle); hkVector4 f; f.setRotatedDir(q, m_forward); if (m_forwardPressed) { hkVector4 imp; imp.setMul4(scale, f); rb->applyLinearImpulse(imp); } if (m_backwardPressed) { hkVector4 imp; imp.setMul4(-scale, f); rb->applyLinearImpulse(imp); } if (m_rightPressed) { m_currentAngle += 3.141592653f * 2 * m_rotationIncrement; } if (m_leftPressed) { m_currentAngle -= 3.141592653f * 2 * m_rotationIncrement; } m_lasttimeCalled += dt; //Jump (only if haven't jumped for at least 1 second) if (m_jumpPressed && ((m_lasttimeCalled - m_lastJump) > 1.f)) { m_lastJump = m_lasttimeCalled; hkVector4 imp(0, rb->getMass() * 6, 0); rb->applyLinearImpulse(imp); setJumpPressed(false); } setJumpPressed(false); //if brake pressed, zero all velocities if (m_brakePressed) { hkVector4 zero; zero.setZero4(); rb->setLinearVelocity(zero); rb->setAngularVelocity(zero); setBrakePressed(false); } //draw current "facing" direction, usings "Debug" line. This gets pushed onto a global list, //and gets dealt with by (perhaps) a drawDebugPointsAndLines() method from the mainline start = rb->getPosition(); //end = start + 1.5 * "forward" end = start; f.mul4(1.5f); end.add4(f); //TODO: draw line from start to end } void MarbleAction::reset() { hkpRigidBody* rb = getRigidBody(); //put marble back to the reset position defined on construction, and zero velocities hkVector4 zero; zero.setZero4(); rb->setPosition(m_resetPosition); rb->setLinearVelocity(zero); rb->setAngularVelocity(zero); }
28.835165
225
0.699695
mym2o
7c28f9a0f641f5f618db137ee21ad79407c3aef8
13,626
cc
C++
src/ShaderCompiler/Private/GLSLangUtils.cc
PixPh/kaleido3d
8a8356586f33a1746ebbb0cfe46b7889d0ae94e9
[ "MIT" ]
38
2019-01-10T03:10:12.000Z
2021-01-27T03:14:47.000Z
src/ShaderCompiler/Private/GLSLangUtils.cc
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
null
null
null
src/ShaderCompiler/Private/GLSLangUtils.cc
fuqifacai/kaleido3d
ec77753b516949bed74e959738ef55a0bd670064
[ "MIT" ]
8
2019-04-16T07:56:27.000Z
2020-11-19T02:38:37.000Z
#include <Kaleido3D.h> #include "GLSLangUtils.h" #include <glslang/MachineIndependent/gl_types.h> using namespace ::glslang; using namespace ::k3d; void sInitializeGlSlang() { #if USE_GLSLANG static bool sGlSlangIntialized = false; if (!sGlSlangIntialized) { glslang::InitializeProcess(); sGlSlangIntialized = true; } #endif } void sFinializeGlSlang() { #if USE_GLSLANG static bool sGlSlangFinalized = false; if (!sGlSlangFinalized) { glslang::FinalizeProcess(); sGlSlangFinalized = true; } #endif } NGFXShaderDataType glTypeToRHIAttribType(int glType) { switch (glType) { case GL_FLOAT: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT; case GL_FLOAT_VEC2: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT2; case GL_FLOAT_VEC3: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT3; case GL_FLOAT_VEC4: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT4; case GL_INT: return NGFXShaderDataType::NGFX_SHADER_VAR_INT; case GL_INT_VEC2: return NGFXShaderDataType::NGFX_SHADER_VAR_INT2; case GL_INT_VEC3: return NGFXShaderDataType::NGFX_SHADER_VAR_INT3; case GL_INT_VEC4: return NGFXShaderDataType::NGFX_SHADER_VAR_INT4; case GL_UNSIGNED_INT: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT; case GL_UNSIGNED_INT_VEC2: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT2; case GL_UNSIGNED_INT_VEC3: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT3; case GL_UNSIGNED_INT_VEC4: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT4; } return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; } NGFXShaderDataType glTypeToRHIUniformType(int glType) { switch (glType) { case GL_FLOAT: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT; case GL_FLOAT_VEC2: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT2; case GL_FLOAT_VEC3: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT3; case GL_FLOAT_VEC4: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT4; case GL_INT: return NGFXShaderDataType::NGFX_SHADER_VAR_INT; case GL_INT_VEC2: return NGFXShaderDataType::NGFX_SHADER_VAR_INT2; case GL_INT_VEC3: return NGFXShaderDataType::NGFX_SHADER_VAR_INT3; case GL_INT_VEC4: return NGFXShaderDataType::NGFX_SHADER_VAR_INT4; case GL_UNSIGNED_INT: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT; case GL_UNSIGNED_INT_VEC2: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT2; case GL_UNSIGNED_INT_VEC3: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT3; case GL_UNSIGNED_INT_VEC4: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT4; } return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; } NGFXShaderDataType glslangDataTypeToRHIDataType(const TType& type) { switch (type.getBasicType()) { case EbtSampler: { switch (type.getQualifier().layoutFormat) { case ElfRgba32f: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT4; } } case EbtStruct: case EbtBlock: case EbtVoid: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; default: break; } if (type.isVector()) { int offset = type.getVectorSize() - 2; switch (type.getBasicType()) { case EbtFloat: return (NGFXShaderDataType)((int)NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT2 + offset); //case EbtDouble: return GL_DOUBLE_VEC2 + offset; #ifdef AMD_EXTENSIONS //case EbtFloat16: return GL_FLOAT16_VEC2_NV + offset; #endif case EbtInt: return (NGFXShaderDataType)((int)NGFXShaderDataType::NGFX_SHADER_VAR_INT2 + offset); case EbtUint: return (NGFXShaderDataType)((int)NGFXShaderDataType::NGFX_SHADER_VAR_UINT2 + offset); //case EbtInt64: return GL_INT64_ARB + offset; //case EbtUint64: return GL_UNSIGNED_INT64_ARB + offset; case EbtBool: return (NGFXShaderDataType)((int)NGFXShaderDataType::NGFX_SHADER_VAR_BOOL2 + offset); //case EbtAtomicUint: return GL_UNSIGNED_INT_ATOMIC_COUNTER + offset; default: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; } } if (type.isMatrix()) { switch (type.getBasicType()) { case EbtFloat: switch (type.getMatrixCols()) { case 2: switch (type.getMatrixRows()) { case 2: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT2; case 3: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT2X3; case 4: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT2X4; default: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; } case 3: switch (type.getMatrixRows()) { case 2: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT3X2; case 3: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT3; case 4: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT3X4; default: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; } case 4: switch (type.getMatrixRows()) { case 2: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT4X2; case 3: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT4X3; case 4: return NGFXShaderDataType::NGFX_SHADER_VAR_MAT4; default: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; } } } } if (type.getVectorSize() == 1) { switch (type.getBasicType()) { case EbtFloat: return NGFXShaderDataType::NGFX_SHADER_VAR_FLOAT; case EbtInt: return NGFXShaderDataType::NGFX_SHADER_VAR_INT; case EbtUint: return NGFXShaderDataType::NGFX_SHADER_VAR_UINT; case EbtBool: return NGFXShaderDataType::NGFX_SHADER_VAR_BOOL; default: return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; } } return NGFXShaderDataType::NGFX_SHADER_VAR_UNKNOWN; } NGFXShaderBindType glslangTypeToRHIType(const TBasicType& type) { switch (type) { case EbtSampler: return NGFXShaderBindType::NGFX_SHADER_BIND_SAMPLER; case EbtStruct: case EbtBlock: return NGFXShaderBindType::NGFX_SHADER_BIND_BLOCK; case EbtVoid: return NGFXShaderBindType::NGFX_SHADER_BIND_UNDEFINED; default: break; } return NGFXShaderBindType::NGFX_SHADER_BIND_BLOCK; } void initResources(TBuiltInResource &resources) { resources.maxLights = 32; resources.maxClipPlanes = 6; resources.maxTextureUnits = 32; resources.maxTextureCoords = 32; resources.maxVertexAttribs = 64; resources.maxVertexUniformComponents = 4096; resources.maxVaryingFloats = 64; resources.maxVertexTextureImageUnits = 32; resources.maxCombinedTextureImageUnits = 80; resources.maxTextureImageUnits = 32; resources.maxFragmentUniformComponents = 4096; resources.maxDrawBuffers = 32; resources.maxVertexUniformVectors = 128; resources.maxVaryingVectors = 8; resources.maxFragmentUniformVectors = 16; resources.maxVertexOutputVectors = 16; resources.maxFragmentInputVectors = 15; resources.minProgramTexelOffset = -8; resources.maxProgramTexelOffset = 7; resources.maxClipDistances = 8; resources.maxComputeWorkGroupCountX = 65535; resources.maxComputeWorkGroupCountY = 65535; resources.maxComputeWorkGroupCountZ = 65535; resources.maxComputeWorkGroupSizeX = 1024; resources.maxComputeWorkGroupSizeY = 1024; resources.maxComputeWorkGroupSizeZ = 64; resources.maxComputeUniformComponents = 1024; resources.maxComputeTextureImageUnits = 16; resources.maxComputeImageUniforms = 8; resources.maxComputeAtomicCounters = 8; resources.maxComputeAtomicCounterBuffers = 1; resources.maxVaryingComponents = 60; resources.maxVertexOutputComponents = 64; resources.maxGeometryInputComponents = 64; resources.maxGeometryOutputComponents = 128; resources.maxFragmentInputComponents = 128; resources.maxImageUnits = 8; resources.maxCombinedImageUnitsAndFragmentOutputs = 8; resources.maxCombinedShaderOutputResources = 8; resources.maxImageSamples = 0; resources.maxVertexImageUniforms = 0; resources.maxTessControlImageUniforms = 0; resources.maxTessEvaluationImageUniforms = 0; resources.maxGeometryImageUniforms = 0; resources.maxFragmentImageUniforms = 8; resources.maxCombinedImageUniforms = 8; resources.maxGeometryTextureImageUnits = 16; resources.maxGeometryOutputVertices = 256; resources.maxGeometryTotalOutputComponents = 1024; resources.maxGeometryUniformComponents = 1024; resources.maxGeometryVaryingComponents = 64; resources.maxTessControlInputComponents = 128; resources.maxTessControlOutputComponents = 128; resources.maxTessControlTextureImageUnits = 16; resources.maxTessControlUniformComponents = 1024; resources.maxTessControlTotalOutputComponents = 4096; resources.maxTessEvaluationInputComponents = 128; resources.maxTessEvaluationOutputComponents = 128; resources.maxTessEvaluationTextureImageUnits = 16; resources.maxTessEvaluationUniformComponents = 1024; resources.maxTessPatchComponents = 120; resources.maxPatchVertices = 32; resources.maxTessGenLevel = 64; resources.maxViewports = 16; resources.maxVertexAtomicCounters = 0; resources.maxTessControlAtomicCounters = 0; resources.maxTessEvaluationAtomicCounters = 0; resources.maxGeometryAtomicCounters = 0; resources.maxFragmentAtomicCounters = 8; resources.maxCombinedAtomicCounters = 8; resources.maxAtomicCounterBindings = 1; resources.maxVertexAtomicCounterBuffers = 0; resources.maxTessControlAtomicCounterBuffers = 0; resources.maxTessEvaluationAtomicCounterBuffers = 0; resources.maxGeometryAtomicCounterBuffers = 0; resources.maxFragmentAtomicCounterBuffers = 1; resources.maxCombinedAtomicCounterBuffers = 1; resources.maxAtomicCounterBufferSize = 16384; resources.maxTransformFeedbackBuffers = 4; resources.maxTransformFeedbackInterleavedComponents = 64; resources.maxCullDistances = 8; resources.maxCombinedClipAndCullDistances = 8; resources.maxSamples = 4; resources.limits.nonInductiveForLoops = 1; resources.limits.whileLoops = 1; resources.limits.doWhileLoops = 1; resources.limits.generalUniformIndexing = 1; resources.limits.generalAttributeMatrixVectorIndexing = 1; resources.limits.generalVaryingIndexing = 1; resources.limits.generalSamplerIndexing = 1; resources.limits.generalVariableIndexing = 1; resources.limits.generalConstantMatrixVectorIndexing = 1; } EShLanguage findLanguage(const NGFXShaderType shader_type) { switch (shader_type) { case NGFX_SHADER_TYPE_VERTEX: return EShLangVertex; case NGFX_SHADER_TYPE_HULL: return EShLangTessControl; case NGFX_SHADER_TYPE_DOMAIN: return EShLangTessEvaluation; case NGFX_SHADER_TYPE_GEOMETRY: return EShLangGeometry; case NGFX_SHADER_TYPE_FRAGMENT: return EShLangFragment; case NGFX_SHADER_TYPE_COMPUTE: return EShLangCompute; default: return EShLangVertex; } } void ExtractAttributeData(const TProgram& program, NGFXShaderAttributes& shAttributes) { auto numAttrs = program.getNumLiveAttributes(); if (numAttrs > 0) { for (uint32 i = 0; i < numAttrs; i++) { auto name = program.getAttributeName(i); auto type = program.getAttributeType(i); shAttributes.Append({name, NGFX_SEMANTIC_POSITION, glTypeToRHIAttribType(type), i, 0, 0}); } } } void ExtractUniformData(NGFXShaderType const& stype, const TProgram& program, NGFXShaderBindingTable& outUniformLayout) { auto numUniforms = program.getNumLiveUniformVariables(); for (int i = 0; i < numUniforms; i++) { auto name = program.getUniformName(i); auto index = program.getUniformIndex(name); auto type = program.getUniformTType(index); bool isImage = type->isImage(); auto baseType = type->getBasicType(); auto qualifier = type->getQualifier(); if (qualifier.hasBinding()) { NGFXShaderBindType bind = glslangTypeToRHIType(baseType); if (baseType == EbtSampler) { if (type->getSampler().isCombined()) { bind = NGFXShaderBindType::NGFX_SHADER_BIND_SAMPLER_IMAGE_COMBINE; } switch (type->getSampler().dim) { case Esd1D: case Esd2D: case Esd3D: case EsdCube: case EsdRect: bind = NGFXShaderBindType::NGFX_SHADER_BIND_SAMPLED_IMAGE; break; } if (type->isImage()) { switch (qualifier.storage) { case EvqUniform: bind = NGFXShaderBindType::NGFX_SHADER_BIND_RWTEXEL_BUFFER; break; case EvqBuffer: bind = NGFXShaderBindType::NGFX_SHADER_BIND_RWTEXEL_BUFFER; break; } } } outUniformLayout.AddBinding({bind, name, stype, qualifier.layoutBinding}); } if (qualifier.hasSet()) { outUniformLayout.AddSet(qualifier.layoutSet); } if (baseType == EbtSampler) { auto sampler = type->getSampler(); if (!sampler.combined) { outUniformLayout.AddUniform({glslangDataTypeToRHIDataType(*type), name, qualifier.hasOffset() ? (uint32)qualifier.layoutOffset : 0, /*type->getArraySizes()*/}); } } else { outUniformLayout.AddUniform({glslangDataTypeToRHIDataType(*type), name, qualifier.hasOffset() ? (uint32)qualifier.layoutOffset : 0, /*type->getArraySizes()*/}); } } auto numUniformBlocks = program.getNumLiveUniformBlocks(); for (int i = 0; i < numUniformBlocks; i++) { auto block = program.getUniformBlockTType(i); auto name = program.getUniformBlockName(i); auto bindNum = program.getUniformBlockIndex(i); auto bType = block->getBasicType(); auto qualifier = block->getQualifier(); if (qualifier.hasSet()) { outUniformLayout.AddSet(qualifier.layoutSet); } if (qualifier.hasBinding()) { outUniformLayout.AddBinding({glslangTypeToRHIType(bType), name, stype, (uint32)qualifier.layoutBinding}); } switch (bType) { case EbtString: break; } } }
32.754808
168
0.754954
PixPh
7c2b82eba95378926615f75703f463e29eb82ff6
3,288
cpp
C++
Project Mania/Source/Character/Chassis.cpp
larsolm/Archives
18968c18b80777e589bc8a704b4375be2fff8eea
[ "MIT" ]
null
null
null
Project Mania/Source/Character/Chassis.cpp
larsolm/Archives
18968c18b80777e589bc8a704b4375be2fff8eea
[ "MIT" ]
null
null
null
Project Mania/Source/Character/Chassis.cpp
larsolm/Archives
18968c18b80777e589bc8a704b4375be2fff8eea
[ "MIT" ]
null
null
null
#include "Pch.h" #include "Character/Character.h" #include "Character/Chassis.h" #include "Data/AugmentData.h" #include "Data/CharacterData.h" #include "Data/ComponentData.h" #include "Data/ChassisData.h" #include "Data/EquipmentData.h" #include "Data/UpgradeData.h" #include "Data/PartData.h" #include "Parts/Item.h" #include "Parts/Equipment.h" #include "Parts/Weapon.h" #include "Parts/Upgrade.h" void Chassis::Initialize() { Skeleton = Data->Skeleton->CreateSkeleton(); Skeleton->Data = Data->Skeleton; Skeleton->Character = Character; Skeleton->Initialize(); for (auto& attachment : Data->Attachments) { auto part = AttachPart(attachment.Bone, *attachment.Part); for (auto i = 0; i < attachment.Components.Count(); i++) attachment.Components.Item(i)->Apply(*part, i); for (auto augment : attachment.Augments) augment->Apply(*part); } Character->Health = GetMaxHealth(); Character->Shield = GetMaxShield(); } void Chassis::Update(float elapsed) { for (auto& equipment : Equipment) equipment->Update(elapsed, false, false, false); for (auto i = 0; i < Items.Count(); i++) { auto item = static_cast<Item*>(Items.Item(i).get()); auto active = Character->ActiveItemSlot == i; auto primary = active && Character->Controller->ItemPrimary; auto secondary = active && Character->Controller->ItemSecondary; item->Update(elapsed, active, primary, secondary); } for (auto i = 0; i < Weapons.Count(); i++) { auto weapon = static_cast<Weapon*>(Weapons.Item(i).get()); auto active = Character->ActiveWeaponSlot == i; auto primary = active && Character->Controller->WeaponPrimary; auto secondary = active && Character->Controller->WeaponSecondary; weapon->Update(elapsed, active, primary, secondary); } } auto Chassis::AttachPart(StringView name, PartData& data) -> Part* { auto& bone = Skeleton->GetBone(name); assert(bone.Data->AttachmentType == data.Bone.AttachmentType); auto part = data.CreatePart(); part->Data = &data; part->Character = Character; part->Bone = &bone; part->Initialize(); switch (data.Bone.AttachmentType) { case AttachmentType::Equipment: return Equipment.Add(std::move(part)).get(); case AttachmentType::Item: if (Items.IsEmpty()) Character->ActiveItemSlot = 0; return Items.Add(std::move(part)).get(); case AttachmentType::Weapon: if (Weapons.IsEmpty()) Character->ActiveWeaponSlot = 0; return Weapons.Add(std::move(part)).get(); } return nullptr; } auto Chassis::GetMaxHealth() const -> float { auto health = Character->Data->Health; for (auto& part : Equipment) { auto equipment = static_cast<class Equipment*>(part.get()); health += equipment->EquipmentData->Attributes.GetAttribute(equipment->Modifiers, EquipmentAttribute::Health); } return health; } auto Chassis::GetMaxShield() const -> float { auto shield = 0.0f; for (auto& part : Equipment) { for (auto& upgrade : part->Upgrades) shield += upgrade->Data->Attributes.GetAttribute(upgrade->Modifiers, UpgradeAttribute::Shield); } return shield; } auto Chassis::GetShieldRegen() const -> float { auto regen = 0.0f; for (auto& part : Equipment) { for (auto& upgrade : part->Upgrades) regen += upgrade->Data->Attributes.GetAttribute(upgrade->Modifiers, UpgradeAttribute::ShieldRegen); } return regen; }
27.630252
129
0.708942
larsolm
7c2e1ea6553fb140adf3f89f99d79cfaed04016d
1,699
cpp
C++
libvast/src/format/ostream_writer.cpp
ngrodzitski/vast
5d114f53d51db8558f673c7f873bd92ded630bf6
[ "BSD-3-Clause" ]
null
null
null
libvast/src/format/ostream_writer.cpp
ngrodzitski/vast
5d114f53d51db8558f673c7f873bd92ded630bf6
[ "BSD-3-Clause" ]
null
null
null
libvast/src/format/ostream_writer.cpp
ngrodzitski/vast
5d114f53d51db8558f673c7f873bd92ded630bf6
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/format/ostream_writer.hpp" #include "vast/error.hpp" namespace vast::format { ostream_writer::ostream_writer(ostream_ptr out) : out_(std::move(out)) { // nop } ostream_writer::~ostream_writer() { // nop } caf::expected<void> ostream_writer::flush() { if (out_ == nullptr) return caf::make_error(ec::format_error, "no output stream available"); out_->flush(); if (!*out_) return caf::make_error(ec::format_error, "failed to flush"); return caf::unit; } std::ostream& ostream_writer::out() { VAST_ASSERT(out_ != nullptr); return *out_; } void ostream_writer::write_buf() { VAST_ASSERT(out_ != nullptr); out_->write(buf_.data(), buf_.size()); buf_.clear(); } } // namespace vast::format
34.673469
80
0.479105
ngrodzitski
7c2e99d071f669e6bf42911f05fdfe7e036dfa42
12,307
cpp
C++
Sources/Rosetta/Battlegrounds/Models/Battle.cpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
62
2017-08-21T14:11:00.000Z
2018-04-23T16:09:02.000Z
Sources/Rosetta/Battlegrounds/Models/Battle.cpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
37
2017-08-21T11:13:07.000Z
2018-04-30T08:58:41.000Z
Sources/Rosetta/Battlegrounds/Models/Battle.cpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
10
2017-08-21T03:44:12.000Z
2018-01-10T22:29:10.000Z
// Copyright (c) 2017-2021 Chris Ohk // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <Rosetta/Battlegrounds/Models/Battle.hpp> #include <effolkronium/random.hpp> using Random = effolkronium::random_static; namespace RosettaStone::Battlegrounds { Battle::Battle(Player& player1, Player& player2) : m_player1(player1), m_player2(player2), m_p1Field(m_player1.battleField), m_p2Field(m_player2.battleField) { m_player1.battleField = m_player1.recruitField; m_player2.battleField = m_player2.recruitField; } void Battle::Initialize() { // Determine the player attacks first // NOTE: The player with the greater number of minions attacks first. // If the number of minions is equal for both players, one of the players // is randomly selected to attack first. const int p1NumMinions = m_p1Field.GetCount(); const int p2NumMinions = m_p2Field.GetCount(); if (p1NumMinions > p2NumMinions) { m_turn = Turn::PLAYER1; } else if (p1NumMinions < p2NumMinions) { m_turn = Turn::PLAYER2; } else { m_turn = static_cast<Turn>(Random::get<std::size_t>(0, 1)); } m_p1NextAttackerIdx = 0; m_p2NextAttackerIdx = 0; if (m_turn == Turn::PLAYER1) { m_p1Field.ForEach([&](MinionData& minion) { minion.value().ActivateTask(PowerType::START_OF_COMBAT, m_player1); }); m_p2Field.ForEach([&](MinionData& minion) { minion.value().ActivateTask(PowerType::START_OF_COMBAT, m_player2); }); } else { m_p2Field.ForEach([&](MinionData& minion) { minion.value().ActivateTask(PowerType::START_OF_COMBAT, m_player2); }); m_p1Field.ForEach([&](MinionData& minion) { minion.value().ActivateTask(PowerType::START_OF_COMBAT, m_player1); }); } ProcessDestroy(true); } void Battle::Run() { Initialize(); bool prevAttackSuccess = false; while (!IsDone()) { if (m_turn == Turn::PLAYER1) { m_p1Field.ForEachAlive([&](MinionData& owner) { m_p1Field.ForEachAlive([&](MinionData& minion) { { owner.value().ActivateTrigger(TriggerType::TURN_START, minion.value()); }; }); }); m_p2Field.ForEachAlive([&](MinionData& owner) { m_p2Field.ForEachAlive([&](MinionData& minion) { { owner.value().ActivateTrigger(TriggerType::TURN_START, minion.value()); }; }); }); } else { m_p2Field.ForEachAlive([&](MinionData& owner) { m_p2Field.ForEachAlive([&](MinionData& minion) { { owner.value().ActivateTrigger(TriggerType::TURN_START, minion.value()); }; }); }); m_p1Field.ForEachAlive([&](MinionData& owner) { m_p1Field.ForEachAlive([&](MinionData& minion) { { owner.value().ActivateTrigger(TriggerType::TURN_START, minion.value()); }; }); }); } const bool curAttackSuccess = Attack(); if (!prevAttackSuccess && !curAttackSuccess) { m_turn = Turn::DONE; break; } prevAttackSuccess = curAttackSuccess; } ProcessResult(); const int damage = CalculateDamage(); if (m_result == BattleResult::PLAYER1_WIN) { m_player2.hero.TakeDamage(m_player2, damage); } else if (m_result == BattleResult::PLAYER2_WIN) { m_player1.hero.TakeDamage(m_player1, damage); } } bool Battle::Attack() { const int attackerIdx = FindAttacker(); // No minions that can attack, switch players if (attackerIdx == -1) { m_turn = (m_turn == Turn::PLAYER1) ? Turn::PLAYER2 : Turn::PLAYER1; return false; } Minion& attacker = (m_turn == Turn::PLAYER1) ? m_p1Field[attackerIdx] : m_p2Field[attackerIdx]; Minion& target = GetProperTarget(attacker); target.TakeDamage(attacker); attacker.TakeDamage(target); ProcessDestroy(false); m_turn = (m_turn == Turn::PLAYER1) ? Turn::PLAYER2 : Turn::PLAYER1; return true; } int Battle::FindAttacker() { FieldZone& fieldZone = (m_turn == Turn::PLAYER1) ? m_p1Field : m_p2Field; int nextAttackerIdx = (m_turn == Turn::PLAYER1) ? m_p1NextAttackerIdx : m_p2NextAttackerIdx; for (int i = 0; i < fieldZone.GetCount(); ++i) { if (fieldZone[nextAttackerIdx].GetAttack() > 0) { return nextAttackerIdx; } ++nextAttackerIdx; if (nextAttackerIdx == fieldZone.GetCount()) { nextAttackerIdx = 0; } } return -1; } Minion& Battle::GetProperTarget([[maybe_unused]] Minion& attacker) { auto& minions = (m_turn == Turn::PLAYER1) ? m_p2Field : m_p1Field; std::vector<std::size_t> tauntMinions; tauntMinions.reserve(MAX_FIELD_SIZE); std::size_t minionIdx = 0; minions.ForEach([&](const MinionData& minion) { if (minion.value().HasTaunt()) { tauntMinions.emplace_back(minionIdx); } ++minionIdx; }); if (!tauntMinions.empty()) { const auto idx = Random::get<std::size_t>(0, tauntMinions.size() - 1); return minions[tauntMinions[idx]]; } const auto idx = Random::get<int>(0, minions.GetCount() - 1); return minions[idx]; } void Battle::ProcessDestroy(bool beforeAttack) { std::vector<std::tuple<int, Minion&>> deadMinions; if (m_turn == Turn::PLAYER1) { m_p2Field.ForEach([&](MinionData& minion) { if (minion.value().IsDestroyed()) { deadMinions.emplace_back( std::make_tuple(2, std::ref(minion.value()))); } }); m_p1Field.ForEach([&](MinionData& minion) { if (minion.value().IsDestroyed()) { deadMinions.emplace_back( std::make_tuple(1, std::ref(minion.value()))); } }); } else { m_p1Field.ForEach([&](MinionData& minion) { if (minion.value().IsDestroyed()) { deadMinions.emplace_back( std::make_tuple(1, std::ref(minion.value()))); } }); m_p2Field.ForEach([&](MinionData& minion) { if (minion.value().IsDestroyed()) { deadMinions.emplace_back( std::make_tuple(2, std::ref(minion.value()))); } }); } // A variable to check a minion at the index of next attacker is destroyed bool isAttackerDestroyed = false; for (auto& deadMinion : deadMinions) { Minion& minion = std::get<1>(deadMinion); Minion removedMinion; if (std::get<0>(deadMinion) == 1) { if (!beforeAttack) { // If the zone position of minion that is destroyed is lower // than nextAttackerIdx and greater than 0, decrease by 1 if (m_p1NextAttackerIdx < minion.GetZonePosition() && m_p1NextAttackerIdx > 0) { --m_p1NextAttackerIdx; } // If the turn is player 1 and the zone position of minion that // is destroyed equals nextAttackerIdx, keep the value of it else if (m_turn == Turn::PLAYER1 && m_p1NextAttackerIdx == minion.GetZonePosition()) { isAttackerDestroyed = true; } } m_p1Field.ForEachAlive([&](MinionData& aliveMinion) { aliveMinion.value().ActivateTrigger(TriggerType::DEATH, minion); }); m_p2Field.ForEachAlive([&](MinionData& aliveMinion) { aliveMinion.value().ActivateTrigger(TriggerType::DEATH, minion); }); minion.SetLastFieldPos(minion.GetZonePosition()); removedMinion = m_p1Field.Remove(minion); } else { if (!beforeAttack) { // If the zone position of minion that is destroyed is lower // than nextAttackerIdx and greater than 0, decrease by 1 if (m_p2NextAttackerIdx < minion.GetZonePosition() && m_p2NextAttackerIdx > 0) { --m_p2NextAttackerIdx; } // If the turn is player 2 and the zone position of minion that // is destroyed equals nextAttackerIdx, keep the value of it else if (m_turn == Turn::PLAYER2 && m_p2NextAttackerIdx == minion.GetZonePosition()) { isAttackerDestroyed = true; } } m_p1Field.ForEachAlive([&](MinionData& aliveMinion) { aliveMinion.value().ActivateTrigger(TriggerType::DEATH, minion); }); m_p2Field.ForEachAlive([&](MinionData& aliveMinion) { aliveMinion.value().ActivateTrigger(TriggerType::DEATH, minion); }); minion.SetLastFieldPos(minion.GetZonePosition()); removedMinion = m_p2Field.Remove(minion); } // Process deathrattle tasks if (removedMinion.HasDeathrattle()) { removedMinion.ActivateTask( PowerType::DEATHRATTLE, std::get<0>(deadMinion) == 1 ? m_player1 : m_player2); } } if (!beforeAttack) { // If the zone position of minion that is destroyed not equals // nextAttackerIdx, increase by 1 if (!isAttackerDestroyed) { if (m_turn == Turn::PLAYER1) { ++m_p1NextAttackerIdx; } else { ++m_p2NextAttackerIdx; } } // Check the boundaries of field zone if (m_p1NextAttackerIdx == m_p1Field.GetCount()) { m_p1NextAttackerIdx = 0; } if (m_p2NextAttackerIdx == m_p2Field.GetCount()) { m_p2NextAttackerIdx = 0; } } } bool Battle::IsDone() const { return m_p1Field.IsEmpty() || m_p2Field.IsEmpty() || m_turn == Turn::DONE; } void Battle::ProcessResult() { if (m_p1Field.IsEmpty() && !m_p2Field.IsEmpty()) { m_result = BattleResult::PLAYER2_WIN; } else if (!m_p1Field.IsEmpty() && m_p2Field.IsEmpty()) { m_result = BattleResult::PLAYER1_WIN; } else { m_result = BattleResult::DRAW; } } int Battle::CalculateDamage() { int totalDamage = 0; if (m_result == BattleResult::PLAYER1_WIN) { m_p1Field.ForEach([&](const MinionData& minion) { totalDamage += minion.value().GetTier(); }); totalDamage += m_player1.currentTier; } else { m_p2Field.ForEach([&](const MinionData& minion) { totalDamage += minion.value().GetTier(); }); totalDamage += m_player2.currentTier; } return totalDamage; } const FieldZone& Battle::GetPlayer1Field() const { return m_p1Field; } const FieldZone& Battle::GetPlayer2Field() const { return m_p2Field; } int Battle::GetPlayer1NextAttacker() const { return m_p1NextAttackerIdx; } int Battle::GetPlayer2NextAttacker() const { return m_p2NextAttackerIdx; } BattleResult Battle::GetResult() const { return m_result; } } // namespace RosettaStone::Battlegrounds
28.291954
80
0.542781
Hearthstonepp
7c320e8880a227a1bb2501c2bd6e7bd6ba233ea0
1,447
hpp
C++
include/clotho/fitness/linear_fitness_metric.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
3
2015-06-16T21:27:57.000Z
2022-01-25T23:26:54.000Z
include/clotho/fitness/linear_fitness_metric.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
3
2015-06-16T21:12:42.000Z
2015-06-23T12:41:00.000Z
include/clotho/fitness/linear_fitness_metric.hpp
putnampp/clotho
6dbfd82ef37b4265381cd78888cd6da8c61c68c2
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// Copyright 2015 Patrick Putnam // // 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 LINEAR_FITNESS_METRIC_HPP_ #define LINEAR_FITNESS_METRIC_HPP_ #include <vector> #include "clotho/genetics/ifitness.hpp" extern const std::string LINEAR_FIT_NAME; class linear_fitness_metric : public ifitness { public: typedef double real_type; typedef real_type result_type; linear_fitness_metric( real_type a = 1., real_type b = 0. ) : m_val( c ) { } result_type operator()() { return m_B; } result_type operator()( real_type x ) { return m_A * x + m_B; } result_type operator()( const std::vector< real_type > & multi_variate ) { return m_B; } const std::string name() const; void log( std::ostream & out ) const; virtual ~linear_fitness_metric(); protected: real_type m_A, m_B; }; #endif // LINEAR_FITNESS_METRIC_HPP_
27.301887
78
0.68763
putnampp
7c33935241f7c129d9af1d1003bd3b8c73346e36
21,839
cpp
C++
addons/ofxGuido/lib/guidolib-code/linux/src/GDeviceGtk.cpp
k4rm/AscoGraph
9038ae785b6f4f144a3ab5c4c5520761c0cd08f2
[ "MIT" ]
18
2015-01-18T22:34:22.000Z
2020-09-06T20:30:30.000Z
addons/ofxGuido/lib/guidolib-code/linux/src/GDeviceGtk.cpp
k4rm/AscoGraph
9038ae785b6f4f144a3ab5c4c5520761c0cd08f2
[ "MIT" ]
2
2015-08-04T00:07:46.000Z
2017-05-10T15:53:51.000Z
addons/ofxGuido/lib/guidolib-code/linux/src/GDeviceGtk.cpp
k4rm/AscoGraph
9038ae785b6f4f144a3ab5c4c5520761c0cd08f2
[ "MIT" ]
10
2015-01-18T23:46:10.000Z
2019-08-25T12:10:04.000Z
/* GUIDO Library Copyright (C) 2004 Torben Hohn This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ ///////////////////////////////////////////////////////////////// /// /// GTK implementation of VGDevice. /// ///////////////////////////////////////////////////////////////// #include "GDeviceGtk.h" #include "GFontGtk.h" #include "GSystemGtk.h" // GUIDO HACK - REMOVE ASAP // -------------------------------------------------------------- GDeviceGtk::GDeviceGtk( GdkDrawable * inDrawable, int inWidth, int inHeight ) : mCurrTextFont(NULL), mCurrMusicFont(NULL), mRasterMode(kOpCopy), mDPITag(72.0f), mBeginDrawCount(0), mDrawable( inDrawable ) { // Default device init --------------------------- // Default pen and brush colors must be pure black. mPhysicalWidth = inWidth; mPhysicalHeight = inHeight; mPenStack.reserve( 16 ); mBrushStack.reserve( 16 ); SetFontAlign( kAlignLeft | kAlignBase ); // GTK ------------------------------------------- Init(); mPangoContext = gdk_pango_context_get(); gdk_pango_context_set_colormap( mPangoContext, gdk_rgb_get_colormap() ); if( mDrawable ) { printf( "dc is OK\n" ); mGC = gdk_gc_new( mDrawable ); // TODO: get GdkGC... // - Initial state of GDevice SelectPen( VGColor( 0, 0, 0), 1 ); SelectFillColor( VGColor( 0, 0, 0) ); SetFontColor( VGColor(0,0,0) ); SetFontBackgroundColor( VGColor(255,255,255,ALPHA_TRANSPARENT) ); SetScale( 1, 1 ); SetOrigin( 0, 0 ); } else printf( "dc is NULL\n" ); // guigo hack - remove asap mSys = new GSystemGtk(inDrawable, NULL); } // -------------------------------------------------------------- GDeviceGtk::~GDeviceGtk() { delete [] mPtArray; } // -------------------------------------------------------------- bool GDeviceGtk::IsValid() const { if( mDrawable == NULL ) return false; return true; } ///////////////////////////////////////////////////////////////// // - Drawing services ------------------------------------------- ///////////////////////////////////////////////////////////////// // -------------------------------------------------------------- bool GDeviceGtk::BeginDraw() { // general device's state save - was VGDevice::SaveDC() GState s; s.pen = mPen; s.fillColor = mFillColor; s.textColor = mTextColor; s.textBackColor = mTextBackColor; s.scaleX = mScaleX; s.scaleY = mScaleY; s.originX = mOriginX; s.originY = mOriginY; s.textAlign = mTextAlign; s.currTextFont = mCurrTextFont; s.currMusicFont = mCurrMusicFont; s.rasterMode = mRasterMode; s.gtkUserScaleX = mGtkScaleX; s.gtkUserScaleY = mGtkScaleY; s.gtkOriginX = mGtkOriginX; s.gtkOriginY = mGtkOriginY; s.penPos = mCurrPenPos; mStateStack.push_back( s ); // TODO : complete this code with correct // platform-dependant implementation return true; } // -------------------------------------------------------------- void GDeviceGtk::EndDraw() { // Default device code --------------------------- if( -- mBeginDrawCount == 0 ) {} // general device's state restore - was RestoreDC() GState & s = mStateStack.back(); mPen = s.pen; mFillColor = s.fillColor; mTextColor = s.textColor; mTextBackColor = s.textBackColor; mScaleX = s.scaleX; mScaleY = s.scaleY; mOriginX = s.originX; mOriginY = s.originY; mTextAlign = s.textAlign; mCurrTextFont = s.currTextFont; mCurrMusicFont = s.currMusicFont; mRasterMode = s.rasterMode; mGtkOriginX = s.gtkOriginX; mGtkOriginY = s.gtkOriginY; mGtkScaleX = s.gtkUserScaleX; mGtkScaleY = s.gtkUserScaleY; mCurrPenPos = s.penPos; mStateStack.pop_back(); SetTextFont( s.currTextFont ); SetMusicFont( s.currMusicFont ); } // -------------------------------------------------------------- void GDeviceGtk::MoveTo( float x, float y ) { printf( "moveto: %f, %f\n", x, y ); mCurrPenPos.x = lrintf (x * mGtkScaleX + mGtkOriginX); mCurrPenPos.y = lrintf (y * mGtkScaleY + mGtkOriginY); } // -------------------------------------------------------------- void GDeviceGtk::LineTo( float x, float y ) { int gx = lrintf (x * mGtkScaleX + mGtkOriginX); int gy = lrintf (y * mGtkScaleY + mGtkOriginY); printf( "lineto: %f, %f -> (%d, %d)\n", x, y, gx, gy ); gdk_draw_line( mDrawable, mGC, mCurrPenPos.x, mCurrPenPos.y, gx, gy ); mCurrPenPos.x = gx; mCurrPenPos.y = gy; } // -------------------------------------------------------------- void GDeviceGtk::Line( float x1, float y1, float x2, float y2 ) { MoveTo( x1, y1 ); LineTo( x2, y2 ); } // -------------------------------------------------------------- void GDeviceGtk::Frame( float left, float top, float right, float bottom ) { MoveTo (left, top); LineTo (right, top); LineTo (right, bottom); LineTo (left, bottom); LineTo (left, top); } // -------------------------------------------------------------- void GDeviceGtk::Arc( float left, float top, float right, float bottom, float startX, float startY, float endX, float endY ) { int x = (int) (left); int y = (int) (top); int width = (int) (right - left); int height = (int) (bottom - top); float midX = (left + right) * 0.5f; float midY = (top + bottom) * 0.5f; int angle1 = (int) (atan( (startX - midX)/(startY - midY) ) * 360 * 64 * 2 * M_PI); int angle2 = (int) (atan( (endX - midX) /(endY - midY) ) * 360 * 64 * 2 * M_PI - angle1); gdk_draw_arc( mDrawable, mGC, 0, x, y, width, height, angle1, angle2 ); } // -------------------------------------------------------------- void GDeviceGtk::Triangle( float x1, float y1, float x2, float y2, float x3, float y3 ) { const float xCoords [] = { x1, x2, x3 }; const float yCoords [] = { y1, y2, y3 }; Polygon( xCoords, yCoords, 3 ); } // -------------------------------------------------------------- void GDeviceGtk::Polygon( const float * xCoords, const float * yCoords, int count ) { if( count > mPtCount ) { if( mPtArray ) delete [] mPtArray; mPtArray = new GdkPoint [ count ]; if( mPtArray ) mPtCount = count; } for( int index = 0; index < count; index ++ ) { mPtArray[ index ].x = (int) (xCoords[ index ] * mGtkScaleX + mGtkOriginX); mPtArray[ index ].y = (int) (yCoords[ index ] * mGtkScaleY + mGtkOriginY); } gdk_draw_polygon( mDrawable, mGC, 0, mPtArray, count ); } // -------------------------------------------------------------- void GDeviceGtk::Rectangle( float left, float top, float right, float bottom ) { int x = (int) (left * mGtkScaleX + mGtkOriginX); int y = (int) (top * mGtkScaleY + mGtkOriginY); int w = (int) ((left - right) * mGtkScaleX); int h = (int) ((top - bottom ) * mGtkScaleY); gdk_draw_rectangle( mDrawable, mGC, 0, x, y, w, h ); } ///////////////////////////////////////////////////////////////// // - Font services ---------------------------------------------- ///////////////////////////////////////////////////////////////// // -------------------------------------------------------------- void GDeviceGtk::SetMusicFont( const VGFont * font ) { mCurrMusicFont = font; GFontGtk* gtkFont = (GFontGtk*)mCurrMusicFont; // printf( "select music font = %d\n", (PangoFontDescription *)font->GetNativeFont() ); pango_context_set_font_description( mPangoContext, (PangoFontDescription*) gtkFont->GetNativeFont() ); } // -------------------------------------------------------------- const VGFont * GDeviceGtk::GetMusicFont() const { return mCurrMusicFont; } // -------------------------------------------------------------- void GDeviceGtk::SetTextFont( const VGFont * font ) { mCurrTextFont = font; GFontGtk* gtkFont = (GFontGtk*)mCurrTextFont; // printf( "select text font = %d\n", font->GetNativeFont() ); pango_context_set_font_description( mPangoContext, (PangoFontDescription*) gtkFont->GetNativeFont() ); } // -------------------------------------------------------------- const VGFont * GDeviceGtk::GetTextFont() const { return mCurrTextFont; } ///////////////////////////////////////////////////////////////// // - Pen & brush services --------------------------------------- ///////////////////////////////////////////////////////////////// // -------------------------------------------------------------- void GDeviceGtk::SelectPen( const VGColor & inColor, float width ) { mPen.Set( inColor, width ); GdkColor color = { 0, inColor.mRed, inColor.mGreen, inColor.mBlue }; GdkLineStyle style = (inColor.mAlpha >= ALPHA_TRANSPARENT) ? GDK_LINE_ON_OFF_DASH : GDK_LINE_SOLID ; gdk_gc_set_rgb_fg_color( mGC, &color ); gdk_gc_set_line_attributes( mGC, lrintf(width * mGtkScaleX), style, GDK_CAP_ROUND, GDK_JOIN_MITER ); } // -------------------------------------------------------------- void GDeviceGtk::SelectFillColor( const VGColor & c ) { mFillColor.Set( c ); GdkColor color = { 0, c.mRed, c.mGreen, c.mBlue }; gdk_gc_set_rgb_fg_color( mGC, &color ); } // -------------------------------------------------------------- // Save the current pen, select the new one void GDeviceGtk::PushPen( const VGColor & inColor, float inWidth ) { mPenStack.push_back( mPen ); SelectPen( inColor, inWidth ); // TODO : complete this code with correct // platform-dependant implementation } // -------------------------------------------------------------- // Restore the previous pen from the stack void GDeviceGtk::PopPen() { VGPen & pen = mPenStack.back(); SelectPen( pen.mColor, pen.mWidth ); mPenStack.pop_back(); // TODO : complete this code with correct // platform-dependant implementation } // -------------------------------------------------------------- // Save the current brush, select the new one void GDeviceGtk::PushFillColor( const VGColor & inColor ) { mBrushStack.push_back( mFillColor ); if( inColor != mFillColor ) SelectFillColor( inColor ); // TODO : complete this code with correct // platform-dependant implementation } // -------------------------------------------------------------- // Restore the previous brush from the stack void GDeviceGtk::PopFillColor() { VGColor & brush = mBrushStack.back(); SelectFillColor( brush ); mBrushStack.pop_back(); // TODO : complete this code with correct // platform-dependant implementation } // -------------------------------------------------------------- void GDeviceGtk::SetRasterOpMode( VRasterOpMode ROpMode ) { mRasterMode = ROpMode; } ///////////////////////////////////////////////////////////////// // - Bitmap services (bit-block copy methods) ------------------- ///////////////////////////////////////////////////////////////// // -------------------------------------------------------------- bool GDeviceGtk::CopyPixels( VGDevice* pSrcDC, float alpha ) { return false; // TODO : replace this code by correct // platform-dependant implementation } // -------------------------------------------------------------- bool GDeviceGtk::CopyPixels( int xDest, int yDest, VGDevice* pSrcDC, int xSrc, int ySrc, int nSrcWidth, int nSrcHeight, float alpha ) { return false; // TODO : replace this code by correct // platform-dependant implementation } // -------------------------------------------------------------- bool GDeviceGtk::CopyPixels( int xDest, int yDest, int dstWidth, int dstHeight, VGDevice* pSrcDC, float alphas ) { return false; // TODO : replace this code by correct // platform-dependant implementation } ///////////////////////////////////////////////////////////////// // - Coordinate services ---------------------------------------- ///////////////////////////////////////////////////////////////// // -------------------------------------------------------------- void GDeviceGtk::SetScale( float x, float y ) { const float prevX = mScaleX; const float prevY = mScaleY; mScaleX = mGtkScaleX = x; mScaleY = mGtkScaleY = y; // TODO : complete this code with correct // platform-dependant implementation // was DoSetScale( prevX, prevY, x, y ); printf( "set Scale %f, %f\n", x, y ); // mGtkScaleX = x; // mGtkScaleY = y; } // -------------------------------------------------------------- // Called only by GRPage void GDeviceGtk::SetOrigin( float x, float y ) { const float prevX = mOriginX; const float prevY = mOriginY; mOriginX = x; mOriginY = y; // TODO : complete this code with correct // platform-dependant implementation // was DoSetOrigin( prevX, prevY, x, y ); printf( "set Origin %f, %f\n", x, y ); mGtkOriginX += (int) ((x - prevX) * GetXScale()); mGtkOriginY += (int) ((y - prevY) * GetYScale()); } // -------------------------------------------------------------- // Called by: GRPage, GRStaff, GRSystem void GDeviceGtk::OffsetOrigin( float x, float y ) { const float prevX = mOriginX; const float prevY = mOriginY; mOriginX += x; mOriginY += y; // TODO : complete this code with correct // platform-dependant implementation // was DoSetOrigin( prevX, prevY, x, y ); printf( "set Origin %f, %f\n", x, y ); mGtkOriginX += (int) ((x - prevX) * GetXScale()); mGtkOriginY += (int) ((y - prevY) * GetYScale()); } // -------------------------------------------------------------- // Called by: // GRMusic::OnDraw // GRPage::getPixelSize void GDeviceGtk::LogicalToDevice( float * x, float * y ) const { *x = (*x * mScaleX - mOriginX); *y = (*y * mScaleY - mOriginY); // TODO : complete this code with correct // platform-dependant implementation } // -------------------------------------------------------------- // Called by: // GRPage::DPtoLPRect // GRPage::getVirtualSize void GDeviceGtk::DeviceToLogical( float * x, float * y ) const { *x = ( *x + mOriginX ) / mScaleX; *y = ( *y + mOriginY ) / mScaleY; // TODO : complete this code with correct // platform-dependant implementation } // -------------------------------------------------------------- float GDeviceGtk::GetXScale() const { return mScaleX; } // -------------------------------------------------------------- float GDeviceGtk::GetYScale() const { return mScaleY; } // -------------------------------------------------------------- float GDeviceGtk::GetXOrigin() const { return mOriginX; } // -------------------------------------------------------------- float GDeviceGtk::GetYOrigin() const { return mOriginY; } // -------------------------------------------------------------- void GDeviceGtk::NotifySize( int inWidth, int inHeight ) { mPhysicalWidth = inWidth; mPhysicalHeight = inHeight; } // -------------------------------------------------------------- int GDeviceGtk::GetWidth() const { return mPhysicalWidth; } // -------------------------------------------------------------- int GDeviceGtk::GetHeight() const { return mPhysicalHeight; } ///////////////////////////////////////////////////////////////// // - Text and music symbols services ---------------------------- ///////////////////////////////////////////////////////////////// // -------------------------------------------------------------- void GDeviceGtk::DrawMusicSymbol(float x, float y, unsigned int inSymbolID ) { int gx = (int) (x * mGtkScaleX + mGtkOriginX); int gy = (int) (y * mGtkScaleY + mGtkOriginY); GFontGtk* gtkFont = (GFontGtk*)mCurrMusicFont; // PangoFontDescription *mydescr = pango_font_description_copy( (PangoFontDescription *) mCurrFont->mNativeFont ); // pango_font_description_set_size( mydescr, mCurrFont->mHeight * PANGO_SCALE * mGtkScaleY ); PangoFontDescription *mydescr = pango_font_description_copy( (PangoFontDescription *) gtkFont->GetNativeFont() ); pango_font_description_set_size( mydescr, gtkFont->GetSize() * PANGO_SCALE * mGtkScaleY ); printf( "Draw Symbol %f, %f -> (%d,%d) size = %d \n", x,y, gx,gy, (int) (gtkFont->GetSize() * PANGO_SCALE * mGtkScaleY) ); // char theChar = mSymbolToChar[ inSymbolID ]; char theChar = gtkFont->Symbol( inSymbolID ); printf( "char = %c, %d\n", theChar, (int) theChar ); gsize newstringlen; char *utf8string = g_convert( &theChar, 1, "LATIN1", "UTF8", NULL, &newstringlen, NULL ); PangoLayout *layout = pango_layout_new( mPangoContext ); PangoLanguage* pangoLanguage = pango_language_from_string( "en-us" ); PangoFontMetrics *metrics = pango_context_get_metrics( mPangoContext, mydescr, pangoLanguage ); pango_layout_set_font_description( layout, mydescr ); pango_layout_set_text( layout, utf8string, newstringlen ); const unsigned int textAlign = GetFontAlign(); if( textAlign != ( kAlignLeft | kAlignTop )) { int w = 0; int h = 0; int descent = (pango_font_metrics_get_descent( metrics ) / PANGO_SCALE) + 1; //int descent = 0; pango_layout_get_pixel_size( layout, &w, &h ); h--; if( textAlign & kAlignBase ) gy -= ( h - descent ); else if( textAlign & kAlignBottom ) gy -= h; // depends on axis orientation ? // - Perform horizontal text alignement if( textAlign & kAlignRight ) gx -= w; else if( textAlign & kAlignCenter ) gx -= (w * 0.5); } gdk_draw_layout( mDrawable, mGC, gx, gy, layout ); pango_font_description_free( mydescr ); g_free( utf8string ); g_object_unref( G_OBJECT( layout ) ); } // -------------------------------------------------------------- void GDeviceGtk::DrawString( float x, float y, const char * s, int inCharCount ) { printf( "printAt( %f, %f ) scale = %f, origin = %d \n", x, y, mGtkScaleX, mGtkOriginX ); int gx = (int)( x * mGtkScaleX + mGtkOriginX ); int gy = (int)( y * mGtkScaleY + mGtkOriginY ); PangoLayout *layout = pango_layout_new( mPangoContext ); pango_layout_set_text( layout, s, inCharCount ); gdk_draw_layout( mDrawable, mGC, gx, gy, layout ); g_object_unref( G_OBJECT( layout ) ); } // -------------------------------------------------------------- void GDeviceGtk::SetFontColor( const VGColor & inColor ) { mTextColor = inColor; GdkColor color = { 0, inColor.mRed, inColor.mGreen, inColor.mBlue }; gdk_gc_set_rgb_bg_color( mGC, &color ); } // -------------------------------------------------------------- VGColor GDeviceGtk::GetFontColor() const { return mTextColor; } // -------------------------------------------------------------- void GDeviceGtk::SetFontBackgroundColor( const VGColor & inColor ) { mTextBackColor = inColor; GdkColor color = { 0, inColor.mRed, inColor.mGreen, inColor.mBlue }; gdk_gc_set_rgb_bg_color( mGC, &color ); } // -------------------------------------------------------------- VGColor GDeviceGtk::GetFontBackgroundColor() const { return mTextBackColor; } // -------------------------------------------------------------- void GDeviceGtk::SetFontAlign( unsigned int inAlign ) { mTextAlign = inAlign; } // -------------------------------------------------------------- unsigned int GDeviceGtk::GetFontAlign() const { return mTextAlign; } ///////////////////////////////////////////////////////////////// // - Printer informations services ------------------------------ ///////////////////////////////////////////////////////////////// // -------------------------------------------------------------- void GDeviceGtk::SetDPITag( float inDPI ) { mDPITag = inDPI; } // -------------------------------------------------------------- float GDeviceGtk::GetDPITag() const { return mDPITag; } // -------------------------------------------------------------- VGSystem * GDeviceGtk::getVGSystem() const { return mSys; // TODO : replace this code by correct // platform-dependant implementation } // -------------------------------------------------------------- void * GDeviceGtk::GetNativeContext() const { return mGC; } // -------------------------------------------------------------- void GDeviceGtk::Init() { mStateStack.reserve( 16 ); mGtkOriginX = 0; mGtkOriginY = 0; mCurrPenPos.x = 0; mCurrPenPos.y = 0; mPtArray = 0; // For polygon mPtCount = 0; // For polygon } // -------------------------------------------------------------- #if 0 void GDeviceGtk::AddWxAlignOffset( const wxString & inString, wxCoord * ioX, wxCoord * ioY ) const { const unsigned int textAlign = GetTextAlign(); if( textAlign != ( kAlignLeft | kAlignTop )) { wxCoord w = 0; wxCoord h = 0; wxCoord descent = 0; mDC->GetTextExtent( inString, &w, &h, &descent );// <- crashes wxWindows if font is wrong. if( textAlign & kAlignBase ) *ioY -= ( h - descent ); else if( textAlign & kAlignBottom ) *ioY -= h; // depends on axis orientation ? // - Perform horizontal text alignement if( textAlign & kAlignRight ) *ioX -= w; else if( textAlign & kAlignCenter ) *ioX -= (w * 0.5); } } #endif // -------------------------------------------------------------- int GDeviceGtk::MaxWidth() const { int width; int height; gdk_drawable_get_size( mDrawable, &width, &height ); return width; } // -------------------------------------------------------------- int GDeviceGtk::MaxHeight() const { int width; int height; gdk_drawable_get_size( mDrawable, &width, &height ); return height; }
27.367168
126
0.521223
k4rm
7c36b071ee0da1c00b054d908090ba037591858e
2,372
cc
C++
src/swganh/social/social_service.cc
JohnShandy/swganh
d20d22a8dca2e9220a35af0f45f7935ca2eda531
[ "MIT" ]
1
2015-03-25T16:02:17.000Z
2015-03-25T16:02:17.000Z
src/swganh/social/social_service.cc
JohnShandy/swganh
d20d22a8dca2e9220a35af0f45f7935ca2eda531
[ "MIT" ]
null
null
null
src/swganh/social/social_service.cc
JohnShandy/swganh
d20d22a8dca2e9220a35af0f45f7935ca2eda531
[ "MIT" ]
null
null
null
// This file is part of SWGANH which is released under the MIT license. // See file LICENSE or go to http://swganh.com/LICENSE #include "swganh/social/social_service.h" #include "anh/logger.h" #include "anh/plugin/plugin_manager.h" #include "anh/service/service_manager.h" #include "anh/database/database_manager.h" #include "swganh/app/swganh_kernel.h" #include "swganh/connection/connection_service.h" #include "swganh/character/character_provider_interface.h" #include "swganh/object/player/player.h" #include "swganh/object/object.h" #include "swganh/object/object_controller.h" #include "swganh/object/object_manager.h" #include "swganh/messages/out_of_band.h" using namespace anh::database; using namespace anh::plugin; using namespace std; using namespace swganh::connection; using namespace swganh::object; using namespace swganh::object::player; using namespace swganh::social; using anh::app::KernelInterface; using anh::service::ServiceDescription; using swganh::app::SwganhKernel; using swganh::character::CharacterProviderInterface; SocialService::SocialService(SwganhKernel* kernel) : kernel_(kernel) { character_provider_ = kernel->GetPluginManager()->CreateObject<CharacterProviderInterface>("Character::CharacterProvider"); } SocialService::~SocialService() {} ServiceDescription SocialService::GetServiceDescription() { ServiceDescription service_description( "SocialService", "social", "0.1", "127.0.0.1", 0, 0, 0); return service_description; } bool SocialService::AddFriend(const shared_ptr<Player>& player, const string& friend_name) { uint64_t friend_id = character_provider_->GetCharacterIdByName(friend_name); /// If we found our friend, lets add them to our friends list (which will get updated by the player) if (friend_id > 0) { player->AddFriend(friend_name, friend_id); return true; } return false; } bool SocialService::AddIgnore(const shared_ptr<Player>& player, const string& player_name) { uint64_t player_id = character_provider_->GetCharacterIdByName(player_name); /// If we found the player name, lets add them to our ignore list (which will get updated by the player) if (player_id > 0) { player->IgnorePlayer(player_name, player_id); return true; } return false; }
28.238095
127
0.736931
JohnShandy
7c3d1b998ba7e55703307ac573b0d4775b3151b5
388
hpp
C++
sdl2-sonic-drivers/src/utils/constants.hpp
Raffaello/sdl2-sonic-drivers
20584f100ddd7c61f584deaee0b46c5228d8509d
[ "Apache-2.0" ]
3
2021-10-31T14:24:00.000Z
2022-03-16T08:15:31.000Z
sdl2-sonic-drivers/src/utils/constants.hpp
Raffaello/sdl2-sonic-drivers
20584f100ddd7c61f584deaee0b46c5228d8509d
[ "Apache-2.0" ]
48
2020-06-05T11:11:29.000Z
2022-02-27T23:58:44.000Z
sdl2-sonic-drivers/src/utils/constants.hpp
Raffaello/sdl2-sonic-drivers
20584f100ddd7c61f584deaee0b46c5228d8509d
[ "Apache-2.0" ]
null
null
null
#pragma once #include <cmath> namespace utils { // TODO remove M_PI and M_2PI replace them with PI and PI2 #ifdef M_PI #undef M_PI #endif // M_PI constexpr double M_PI = 3.14159265358979323846; #ifdef M_2PI #undef M_2PI #endif // M_2PI constexpr double M_2PI = 2.0 * M_PI; constexpr double PI = 3.141592653589793238462643; constexpr double PI2 = PI * 2; }
18.47619
62
0.688144
Raffaello
7c423f5a6c83d0ccfe3ff3d33914a241403fcc8e
12,071
cpp
C++
Sourcecode/mxtest/core/PropertiesTest.cpp
diskzero/MusicXML-Class-Library
bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db
[ "MIT" ]
null
null
null
Sourcecode/mxtest/core/PropertiesTest.cpp
diskzero/MusicXML-Class-Library
bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db
[ "MIT" ]
null
null
null
Sourcecode/mxtest/core/PropertiesTest.cpp
diskzero/MusicXML-Class-Library
bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db
[ "MIT" ]
null
null
null
// MusicXML Class Library // Copyright (c) by Matthew James Briggs // Distributed under the MIT License #include "mxtest/control/CompileControl.h" #ifdef MX_COMPILE_CORE_TESTS #include "cpul/cpulTestHarness.h" #include "mxtest/core/HelperFunctions.h" #include "mxtest/core/PropertiesTest.h" #include "mxtest/core/EditorialGroupTest.h" using namespace mx::core; using namespace std; using namespace mxtest; TEST( Test01, Properties ) { variant v = variant::one; PropertiesPtr object = tgenProperties( v ); stringstream expected; tgenPropertiesExpected( expected, 1, v ); stringstream actual; // object->toStream( std::cout, 1 ); object->toStream( actual, 1 ); CHECK_EQUAL( expected.str(), actual.str() ) CHECK( ! object->hasAttributes() ) CHECK( ! object->hasContents() ) } TEST( Test02, Properties ) { variant v = variant::two; PropertiesPtr object = tgenProperties( v ); stringstream expected; tgenPropertiesExpected( expected, 1, v ); stringstream actual; // object->toStream( std::cout, 1 ); object->toStream( actual, 1 ); CHECK_EQUAL( expected.str(), actual.str() ) CHECK( ! object->hasAttributes() ) CHECK( object->hasContents() ) } TEST( Test03, Properties ) { variant v = variant::three; PropertiesPtr object = tgenProperties( v ); stringstream expected; tgenPropertiesExpected( expected, 1, v ); stringstream actual; // object->toStream( std::cout, 1 ); object->toStream( actual, 1 ); CHECK_EQUAL( expected.str(), actual.str() ) CHECK( ! object->hasAttributes() ) CHECK( object->hasContents() ) } namespace mxtest { PropertiesPtr tgenProperties( variant v ) { PropertiesPtr o = makeProperties(); switch ( v ) { case variant::one: { } break; case variant::two: { o->setEditorialGroup( tgenEditorialGroup( v ) ); auto d = makeDivisions(); d->setValue( PositiveDivisionsValue( 120 ) ); o->setDivisions( d ); o->setHasDivisions( true ); auto k = makeKey(); k->getKeyChoice()->setChoice( KeyChoice::Choice::traditionalKey ); k->getKeyChoice()->getTraditionalKey()->getFifths()->setValue( FifthsValue( -2 ) ); k->getKeyChoice()->getTraditionalKey()->setHasCancel( true ); k->getKeyChoice()->getTraditionalKey()->getCancel()->setValue( FifthsValue ( 1 ) ); o->addKey( k ); auto t = makeTime(); t->getTimeChoice()->setChoice( TimeChoice::Choice::timeSignature ); auto timeSignature = makeTimeSignatureGroup(); timeSignature->getBeats()->setValue( XsString( "3" ) ); timeSignature->getBeatType()->setValue( XsString( "4" ) ); t->getTimeChoice()->addTimeSignatureGroup( timeSignature ); t->getTimeChoice()->removeTimeSignatureGroup( t->getTimeChoice()->getTimeSignatureGroupSet().cbegin() ); o->addTime( t ); o->setHasStaves( true ); o->getStaves()->setValue( NonNegativeInteger( 4 ) ); o->setHasPartSymbol( true ); o->getPartSymbol()->setValue( GroupSymbolValue::none ); o->setHasInstruments( true ); o->getInstruments()->setValue( NonNegativeInteger( 3 ) ); auto c = makeClef(); c->getSign()->setValue( ClefSign::g ); c->getLine()->setValue( StaffLine( 2 ) ); c->setHasLine( true ); o->addClef( c ); auto sd = makeStaffDetails(); sd->setHasStaffLines( true ); sd->getStaffLines()->setValue( NonNegativeInteger( 5 ) ); sd->setHasStaffType( true ); sd->getStaffType()->setValue( StaffTypeEnum::regular ); o->addStaffDetails( sd ); auto dir = makeDirective(); dir->setValue( XsString( "allegro" ) ); dir->getAttributes()->hasLang = true; o->addDirective( dir ); auto ms = makeMeasureStyle(); ms->getMeasureStyleChoice()->setChoice( MeasureStyleChoice::Choice::slash ); ms->getMeasureStyleChoice()->getSlash()->getSlashType()->setValue( NoteTypeValue::eighth ); o->addMeasureStyle( ms ); } break; case variant::three: { o->setEditorialGroup( tgenEditorialGroup( v ) ); auto d = makeDivisions(); d->setValue( PositiveDivisionsValue( 99 ) ); o->setDivisions( d ); o->setHasDivisions( true ); auto k = makeKey(); k->getKeyChoice()->setChoice( KeyChoice::Choice::traditionalKey ); k->getKeyChoice()->getTraditionalKey()->getFifths()->setValue( FifthsValue( -2 ) ); k->getKeyChoice()->getTraditionalKey()->setHasCancel( true ); k->getKeyChoice()->getTraditionalKey()->getCancel()->setValue( FifthsValue ( 1 ) ); o->addKey( k ); auto t = makeTime(); t->getTimeChoice()->setChoice( TimeChoice::Choice::timeSignature ); auto timeSignature = makeTimeSignatureGroup(); timeSignature->getBeats()->setValue( XsString( "5" ) ); timeSignature->getBeatType()->setValue( XsString( "4" ) ); t->getTimeChoice()->addTimeSignatureGroup( timeSignature ); t->getTimeChoice()->removeTimeSignatureGroup( t->getTimeChoice()->getTimeSignatureGroupSet().cbegin() ); o->addTime( t ); o->setHasStaves( true ); o->getStaves()->setValue( NonNegativeInteger( 4 ) ); o->setHasPartSymbol( true ); o->getPartSymbol()->setValue( GroupSymbolValue::none ); o->setHasInstruments( true ); o->getInstruments()->setValue( NonNegativeInteger( 3 ) ); auto c = makeClef(); c->getSign()->setValue( ClefSign::g ); c->getLine()->setValue( StaffLine( 2 ) ); c->setHasLine( true ); o->addClef( c ); c = makeClef(); c->getSign()->setValue( ClefSign::c ); c->getLine()->setValue( StaffLine( 3 ) ); c->setHasLine( true ); o->addClef( c ); // auto sd = makeStaffDetails(); // sd->setHasStaffLines( true ); // sd->getStaffLines()->setValue( NonNegativeInteger( 5 ) ); // sd->setHasStaffType( true ); // sd->getStaffType()->setValue( StaffTypeEnum::regular ); // o->addStaffDetails( sd ); auto dir = makeDirective(); dir->setValue( XsString( "allegro" ) ); dir->getAttributes()->hasLang = true; o->addDirective( dir ); auto ms = makeMeasureStyle(); ms->getMeasureStyleChoice()->setChoice( MeasureStyleChoice::Choice::slash ); ms->getMeasureStyleChoice()->getSlash()->getSlashType()->setValue( NoteTypeValue::eighth ); o->addMeasureStyle( ms ); } break; default: break; } return o; } void tgenPropertiesExpected( std::ostream& os, int i, variant v ) { switch ( v ) { case variant::one: { streamLine( os, i, R"(<attributes/>)", false ); } break; case variant::two: { streamLine( os, i, R"(<attributes>)" ); tgenEditorialGroupExpected( os, i+1, v ); os << std::endl; streamLine( os, i+1, R"(<divisions>120</divisions>)" ); streamLine( os, i+1, R"(<key>)" ); streamLine( os, i+2, R"(<cancel>1</cancel>)" ); streamLine( os, i+2, R"(<fifths>-2</fifths>)" ); streamLine( os, i+1, R"(</key>)" ); streamLine( os, i+1, R"(<time>)" ); streamLine( os, i+2, R"(<beats>3</beats>)" ); streamLine( os, i+2, R"(<beat-type>4</beat-type>)" ); streamLine( os, i+1, R"(</time>)" ); streamLine( os, i+1, R"(<staves>4</staves>)" ); streamLine( os, i+1, R"(<part-symbol>none</part-symbol>)" ); streamLine( os, i+1, R"(<instruments>3</instruments>)" ); streamLine( os, i+1, R"(<clef>)" ); streamLine( os, i+2, R"(<sign>G</sign>)" ); streamLine( os, i+2, R"(<line>2</line>)" ); streamLine( os, i+1, R"(</clef>)" ); streamLine( os, i+1, R"(<staff-details>)" ); streamLine( os, i+2, R"(<staff-type>regular</staff-type>)" ); streamLine( os, i+2, R"(<staff-lines>5</staff-lines>)" ); streamLine( os, i+1, R"(</staff-details>)" ); streamLine( os, i+1, R"(<directive xml:lang="it">allegro</directive>)" ); streamLine( os, i+1, R"(<measure-style>)" ); streamLine( os, i+2, R"(<slash type="start">)" ); streamLine( os, i+3, R"(<slash-type>eighth</slash-type>)" ); streamLine( os, i+2, R"(</slash>)" ); streamLine( os, i+1, R"(</measure-style>)" ); streamLine( os, i, R"(</attributes>)", false ); } break; case variant::three: { streamLine( os, i, R"(<attributes>)" ); tgenEditorialGroupExpected( os, i+1, v ); os << std::endl; streamLine( os, i+1, R"(<divisions>99</divisions>)" ); streamLine( os, i+1, R"(<key>)" ); streamLine( os, i+2, R"(<cancel>1</cancel>)" ); streamLine( os, i+2, R"(<fifths>-2</fifths>)" ); streamLine( os, i+1, R"(</key>)" ); streamLine( os, i+1, R"(<time>)" ); streamLine( os, i+2, R"(<beats>5</beats>)" ); streamLine( os, i+2, R"(<beat-type>4</beat-type>)" ); streamLine( os, i+1, R"(</time>)" ); streamLine( os, i+1, R"(<staves>4</staves>)" ); streamLine( os, i+1, R"(<part-symbol>none</part-symbol>)" ); streamLine( os, i+1, R"(<instruments>3</instruments>)" ); streamLine( os, i+1, R"(<clef>)" ); streamLine( os, i+2, R"(<sign>G</sign>)" ); streamLine( os, i+2, R"(<line>2</line>)" ); streamLine( os, i+1, R"(</clef>)" ); streamLine( os, i+1, R"(<clef>)" ); streamLine( os, i+2, R"(<sign>C</sign>)" ); streamLine( os, i+2, R"(<line>3</line>)" ); streamLine( os, i+1, R"(</clef>)" ); // streamLine( os, i+1, R"(<staff-details>)" ); // streamLine( os, i+2, R"(<staff-type>regular</staff-type>)" ); // streamLine( os, i+2, R"(<staff-lines>5</staff-lines>)" ); // streamLine( os, i+1, R"(</staff-details>)" ); streamLine( os, i+1, R"(<directive xml:lang="it">allegro</directive>)" ); streamLine( os, i+1, R"(<measure-style>)" ); streamLine( os, i+2, R"(<slash type="start">)" ); streamLine( os, i+3, R"(<slash-type>eighth</slash-type>)" ); streamLine( os, i+2, R"(</slash>)" ); streamLine( os, i+1, R"(</measure-style>)" ); streamLine( os, i, R"(</attributes>)", false ); } break; default: break; } } } #endif
44.873606
120
0.498385
diskzero
7c45da4372eb53b9bbb2f92658006d7acf60e1c0
1,363
cpp
C++
Strings Problem/Valid Ip Addresses.cpp
theslytherin/Interview_Bit
da9973de33be2f12d6e051bea1e918004216b6ed
[ "MIT" ]
null
null
null
Strings Problem/Valid Ip Addresses.cpp
theslytherin/Interview_Bit
da9973de33be2f12d6e051bea1e918004216b6ed
[ "MIT" ]
null
null
null
Strings Problem/Valid Ip Addresses.cpp
theslytherin/Interview_Bit
da9973de33be2f12d6e051bea1e918004216b6ed
[ "MIT" ]
null
null
null
int stringnumber(string s){ int i=0; int n=s.length(); int face=1; int answer=0; for(i=n-1;i>=0;i--){ answer+=(s[i]-'0')*face; face*=10; } return answer; } bool isValid(string s){ int i,j; int n=s.length(); int number; int start=0; string temp=""; while(start < n){ i=start; temp=""; while(i<n && s[i]!='.')i++; if(i-start >3 ||i-start==0) return false; for(j=start;j<i;j++) temp+=s[j]; number=stringnumber(temp); if(number > 255) return false; if(number == 0 && i-start >1) return false; if(i-start > 1 && s[start]=='0') return false; start=i+1; } return true; } string copyString(string s,int i,int j,int k){ string x; for(int l=0;l<s.length();l++){ if(l==i) x+='.'; if(l==j) x+='.'; if(l==k) x+='.'; x+=s[l]; } return x; } vector<string> Solution::restoreIpAddresses(string A) { vector <string> B; int i,j,k; string s; int l=A.length(); for(i=0;i<l-1;i++) for(j=i+1;j<l-1;j++) for(k=j+1;k<l-1;k++){ s=copyString(A,i+1,j+1,k+1); if(isValid(s)) B.push_back(s); } return B; }
21.296875
55
0.432869
theslytherin
7c48357bb84762320f6d3c9346f67acfbca91d1c
5,398
cpp
C++
src/publish_trajectory/publish_trajectory_to_quadrotor_tmp.cpp
test-bai-cpu/hdi_plan
89684bb73832d7e40f3c669f284ffddb56a1e299
[ "MIT" ]
1
2021-07-31T12:34:11.000Z
2021-07-31T12:34:11.000Z
src/publish_trajectory/publish_trajectory_to_quadrotor_tmp.cpp
test-bai-cpu/hdi_plan
89684bb73832d7e40f3c669f284ffddb56a1e299
[ "MIT" ]
null
null
null
src/publish_trajectory/publish_trajectory_to_quadrotor_tmp.cpp
test-bai-cpu/hdi_plan
89684bb73832d7e40f3c669f284ffddb56a1e299
[ "MIT" ]
2
2021-05-08T13:27:31.000Z
2021-09-24T07:59:04.000Z
#include "publish_trajectory/publish_trajectory_to_quadrotor.hpp" namespace hdi_plan { PublishTrajectory::PublishTrajectory(const ros::NodeHandle &nh, const ros::NodeHandle &pnh) :nh_(nh), pnh_(pnh){ arm_bridge_pub_ = nh_.advertise<std_msgs::Bool>("bridge/arm", 1); start_pub_ = nh_.advertise<std_msgs::Empty>("autopilot/start", 1); //go_to_pose_pub_ = nh_.advertise<geometry_msgs::PoseStamped>("autopilot/pose_command", 100); trajectory_pub_ = nh_.advertise<quadrotor_msgs::Trajectory>("autopilot/trajectory", 1); //max_velocity_pub_ = nh_.advertise<std_msgs::Float64>("autopilot/max_velocity", 1); //trajectory_sub_ = nh_.subscribe("hdi_plan/full_trajectory", 1, &PublishTrajectory::trajectory_callback, this); pub_solution_path_ = nh_.advertise<geometry_msgs::PoseStamped>("autopilot/pose_command", 1); //get_new_path_sub_ = nh_.subscribe("hdi_plan/get_new_path", 1, &PublishTrajectory::get_new_path_callback, this); //quadrotor_state_sub_ = nh_.subscribe("hdi_plan/quadrotor_state", 1, &PublishTrajectory::quadrotor_state_callback, this); ros::Duration(9.0).sleep(); start_quadrotor_bridge(); ros::Duration(9.0).sleep(); ROS_INFO("Start to publish the trajectory!!!"); publish_trajectory(); } PublishTrajectory::~PublishTrajectory() {} void PublishTrajectory::quadrotor_state_callback(const nav_msgs::Odometry::ConstPtr &msg) { quadrotor_state_(0) = msg->pose.pose.position.x; quadrotor_state_(1) = msg->pose.pose.position.y; quadrotor_state_(2) = msg->pose.pose.position.z; } void PublishTrajectory::start_quadrotor_bridge() { ROS_INFO("###### Start the quadrotor bridge"); std_msgs::Bool arm_message; arm_message.data = true; this->arm_bridge_pub_.publish(arm_message); std_msgs::Empty empty_message; this->start_pub_.publish(empty_message); ros::Duration(7.0).sleep(); ROS_INFO("Go to pose msg"); geometry_msgs::PoseStamped go_to_pose_msg; go_to_pose_msg.pose.position.x = 0.0; go_to_pose_msg.pose.position.y = 2.0; go_to_pose_msg.pose.position.z = 2.0; this->pub_solution_path_.publish(go_to_pose_msg); } void PublishTrajectory::get_new_path_callback(const std_msgs::Bool::ConstPtr &msg) { this->if_get_new_path_ = msg->data; } /* void PublishTrajectory::trajectory_callback(const hdi_plan::point_array::ConstPtr &msg) { ROS_INFO("In the trajectory callback"); int trajectory_size = msg->points.size(); this->if_get_new_path_ = false; quadrotor_msgs::Trajectory trajectory_msg; trajectory_msg.header.stamp = ros::Time::now(); trajectory_msg.type = trajectory_msg.GENERAL; for (int i = 0; i < trajectory_size; i++) { quadrotor_msgs::TrajectoryPoint point; geometry_msgs::Point point_msg; point_msg.x = msg->points[i].x; point_msg.y = msg->points[i].y; point_msg.z = msg->points[i].z; point.pose.position = point_msg; trajectory_msg.points.push_back(point); } this->trajectory_pub_.publish(trajectory_msg); }*/ void PublishTrajectory::publish_trajectory() { ROS_INFO("check into publish trajectory"); std::vector<Eigen::Vector3d> optimized_trajectory; for (int i = 1; i < 11; i++) { Eigen::Vector3d point1(i, 2, 2); optimized_trajectory.push_back(point1); } int trajectory_size = optimized_trajectory.size(); geometry_msgs::PoseStamped go_to_pose_msg; for (int i = 0; i < trajectory_size; i++) { Eigen::Vector3d point = optimized_trajectory.at(i); go_to_pose_msg.pose.position.x = point(0); go_to_pose_msg.pose.position.y = point(1); go_to_pose_msg.pose.position.z = point(2); this->pub_solution_path_.publish(go_to_pose_msg); ros::Duration(0.7).sleep(); } /* std_msgs::Bool get_new_path_msg; get_new_path_msg.data = true; this->pub_get_new_path_.publish(get_new_path_msg);*/ } } /* trajectory_pub_ = nh_.advertise<hdi_plan::point_array>("hdi_plan/full_trajectory", 1); trigger_sub_ = nh_.subscribe("hdi_plan/trigger", 1, &PublishTrajectory::trigger_callback, this); pub_get_new_path_ = nh_.advertise<std_msgs::Bool>("hdi_plan/get_new_path", 1); void PublishTrajectory::trigger_callback(const std_msgs::Empty::ConstPtr &msg) { this->publish_trajectory(); } void PublishTrajectory::publish_another_trajectory() { ROS_INFO("check into another publish trajectory"); quadrotor_common::Trajectory trajectory; for (int i=0; i<10; i++) { quadrotor_common::TrajectoryPoint point = quadrotor_common::TrajectoryPoint(); Eigen::Vector3d position(1,i+1,10); point.position = position; trajectory.points.push_back(point); } quadrotor_msgs::Trajectory msg = trajectory.toRosMessage(); this->trajectory_pub_.publish(msg); } void PublishTrajectory::publish_trajectory() { ROS_INFO("check into publish trajectory"); std::vector<Eigen::Vector3d> optimized_trajectory; for (int i = 0; i < 10; i++) { Eigen::Vector3d point1(i, i+1, i+2); optimized_trajectory.push_back(point1); } hdi_plan::point_array trajectory_msg; int trajectory_size = optimized_trajectory.size(); geometry_msgs::Point trajectory_point; for (int i = 0; i < trajectory_size; i++) { Eigen::Vector3d point = optimized_trajectory.at(i); trajectory_point.x = point(0); trajectory_point.y = point(1); trajectory_point.z = point(2); trajectory_msg.points.push_back(trajectory_point); } std_msgs::Bool get_new_path_msg; get_new_path_msg.data = true; this->pub_get_new_path_.publish(get_new_path_msg); this->trajectory_pub_.publish(trajectory_msg); ROS_INFO("Finish publish trajectory"); } */
34.825806
123
0.757318
test-bai-cpu
7c49087a00e33b089fb2609357398b4506781137
14,722
cpp
C++
src/moment_quantization.cpp
TobiasRp/mray
d59bb110c97c7f0a7263981ca0050132220f2688
[ "MIT" ]
null
null
null
src/moment_quantization.cpp
TobiasRp/mray
d59bb110c97c7f0a7263981ca0050132220f2688
[ "MIT" ]
1
2021-11-29T14:03:20.000Z
2021-11-29T14:03:20.000Z
src/moment_quantization.cpp
TobiasRp/mray
d59bb110c97c7f0a7263981ca0050132220f2688
[ "MIT" ]
null
null
null
// Copyright (c) 2020, Tobias Rapp // 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 Karlsruhe Institute of Technology nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "moment_quantization.h" #include "moment_prediction_coding.h" #include <fstream> namespace moment_quantization { static bool s_UseQuantizationTable = false; static array<Byte, 255> s_QuantizationTable; uint32_t quantize(float value, int numBits, float min, float max) { if (numBits == 32) { value = cut::clamp(value, min, max); uint32_t uvalue; std::memcpy(&uvalue, &value, sizeof(float)); return uvalue; } value = cut::clamp(value, min, max); float norm = (value - min) / (max - min); uint32_t bits = norm * ((1 << numBits) - 1); uint32_t mask = 0xFFFFFFFF & ((1 << numBits) - 1); return bits & mask; } float dequantize(uint32_t q, int numBits, float min, float max) { if (numBits == 32) { float fvalue; std::memcpy(&fvalue, &q, sizeof(float)); return cut::clamp(fvalue, min, max); } float norm = q / static_cast<float>((1 << numBits) - 1); return norm * (max - min) + min; } inline void pack_bits(vector<Byte> &out, const vector<uint32_t> &sparse_bits, int num_bits) { Byte buffer = 0; int current_bit = 0; for (size_t i = 0; i < sparse_bits.size(); ++i) { for (int b = 0; b < num_bits; ++b) { int bit = sparse_bits[i] & (1 << b); if (bit) buffer |= (1 << current_bit); ++current_bit; if (current_bit == 8) { out.push_back(buffer); buffer = 0; current_bit = 0; } } } } inline void pack_bits(vector<Byte> &out, const vector<uint32_t> &sparse_bits, const vector<Byte> &num_bits) { Byte buffer = 0; int current_bit = 0; for (size_t i = 0; i < sparse_bits.size(); ++i) { for (int b = 0; b < num_bits[i]; ++b) { int bit = sparse_bits[i] & (1 << b); if (bit) buffer |= (1 << current_bit); ++current_bit; if (current_bit == 8) { out.push_back(buffer); buffer = 0; current_bit = 0; } } } } inline void unpack_bits(vector<uint32_t> &sparse_bits, const vector<Byte> &in, int num_bits) { uint32_t buffer = 0; int current_bit = 0; for (size_t i = 0; i < in.size(); ++i) { for (int b = 0; b < 8; ++b) { int bit = in[i] & (1 << b); if (bit) buffer |= (1 << current_bit); ++current_bit; if (current_bit == num_bits) { sparse_bits.push_back(buffer); buffer = 0; current_bit = 0; } } } } inline void unpack_bits(vector<uint32_t> &sparse_bits, const vector<Byte> &in, const vector<Byte> &num_bits) { uint32_t buffer = 0; int current_bit = 0; int num_idx = 0; for (size_t i = 0; i < in.size(); ++i) { for (int b = 0; b < 8; ++b) { int bit = in[i] & (1 << b); if (bit) buffer |= (1 << current_bit); ++current_bit; if (current_bit == num_bits[num_idx]) { sparse_bits.push_back(buffer); buffer = 0; current_bit = 0; ++num_idx; } } } } bool uses_prediction_coding_quantization_table() { return s_UseQuantizationTable; } void load_prediction_coding_quantization_table(const string &file) { s_UseQuantizationTable = true; std::ifstream in(file, std::ifstream::in); string line; int i = 0; while (std::getline(in, line, ',') && i < 255) { s_QuantizationTable[i] = std::stoi(line); ++i; } } vector<Byte> get_prediction_coding_quantization_table(int max_moments, int numBits) { vector<Byte> table(max_moments); for (int m = 0; m < max_moments; ++m) { if (s_UseQuantizationTable) table[m] = s_QuantizationTable[m]; else { if (m == 0) table[m] = 16; else table[m] = numBits; } } return table; } void set_prediction_coding_quantization_table(const vector<Byte> &table) { s_UseQuantizationTable = true; for (size_t i = 0; i < table.size(); ++i) s_QuantizationTable[i] = table[i]; } vector<Byte> get_prediction_coding_quantization_table() { vector<Byte> table(255, 32); if (s_UseQuantizationTable) { for (int i = 0; i < 255; ++i) table[i] = s_QuantizationTable[i]; } else assert(false); return table; } void write_prediction_coding_quantization_table_to_file(const string &filename) { std::fstream out(filename, std::fstream::out); for (size_t i = 0; i < s_QuantizationTable.size(); ++i) { if (i != s_QuantizationTable.size() -1) out << int(s_QuantizationTable[i]) << ", "; else out << int(s_QuantizationTable[i]); } out << "\n"; } vector<Byte> quantize_prediction_coding(const MomentImageHost &mi, const vector<Byte> &quant_table) { assert(mi.prediction_code); vector<uint32_t> words; vector<Byte> num_bits; for (int y = 0; y < mi.height; ++y) { for (int x = 0; x < mi.width; ++x) { auto num_moments = mi.get_num_moments(x, y); auto idx = mi.get_idx(x, y); if (num_moments == 0) continue; auto num_bits_0 = quant_table[0]; auto ql = quantize(mi.data[idx], num_bits_0, 0.0f, 1.0f); words.push_back(ql); num_bits.push_back(num_bits_0); for (int l = 1; l < num_moments; ++l) { auto num_bits_l = quant_table[l]; auto u_l = mi.data[idx + l]; auto ql = quantize(u_l, num_bits_l, PREDICTION_CODING_QUANTIZATION_MIN, PREDICTION_CODING_QUANTIZATION_MAX); words.push_back(ql); num_bits.push_back(num_bits_l); } } } vector<Byte> packed_bits; pack_bits(packed_bits, words, num_bits); return packed_bits; } vector<Byte> quantize_prediction_coding(const MomentImageHost &mi, int numBits) { auto table = get_prediction_coding_quantization_table(mi.num_moments, numBits); return quantize_prediction_coding(mi, table); } void dequantize_prediction_coding(MomentImageHost &mi, const vector<Byte> &quant_table, const vector<Byte> &qs) { assert(mi.prediction_code); vector<Byte> num_bits; for (int y = 0; y < mi.height; ++y) { for (int x = 0; x < mi.width; ++x) { auto num_moments = mi.get_num_moments(x, y); if (num_moments == 0) continue; for (int l = 0; l < num_moments; ++l) num_bits.push_back(quant_table[l]); } } vector<uint32_t> words; unpack_bits(words, qs, num_bits); size_t offset = 0; for (int y = 0; y < mi.height; ++y) { for (int x = 0; x < mi.width; ++x) { auto num_moments = mi.get_num_moments(x, y); auto idx = mi.get_idx(x, y); if (num_moments == 0) continue; uint32_t qj = words[offset]; mi.data[idx] = dequantize(qj, num_bits[offset], 0.0, 1.0); assert(!std::isnan(mi.data[idx]) && !std::isinf(mi.data[idx])); ++offset; for (int l = 1; l < num_moments; ++l) { uint32_t qj = words[offset]; mi.data[idx + l] = dequantize(qj, num_bits[offset], PREDICTION_CODING_QUANTIZATION_MIN, PREDICTION_CODING_QUANTIZATION_MAX); assert(!std::isnan(mi.data[idx + l]) && !std::isinf(mi.data[idx + l])); assert(mi.data[idx + l] >= -1.0f && mi.data[idx + l] <= 1.0f); ++offset; } } } } void dequantize_prediction_coding(MomentImageHost &mi, int numBits, const vector<Byte> &qs) { auto table = get_prediction_coding_quantization_table(mi.num_moments, numBits); return dequantize_prediction_coding(mi, table, qs); } vector<Byte> quantize(const MomentImageHost &mi, int numBits) { assert(!mi.prediction_code); vector<uint32_t> qs; for (int y = 0; y < mi.height; ++y) { for (int x = 0; x < mi.width; ++x) { auto num_moments = mi.get_num_moments(x, y); auto idx = mi.get_idx(x, y); if (num_moments == 0) continue; uint32_t q0 = quantize(mi.data[idx], numBits, 0.0f, 1.0f); qs.push_back(q0); for (int j = 1; j < num_moments; ++j) { float mj = mi.data[idx + j]; auto qm = quantize(mj, numBits, -1.0 / M_PI, 1.0 / M_PI); qs.push_back(qm); } } } vector<Byte> packed_bits; pack_bits(packed_bits, qs, numBits); return packed_bits; } void dequantize(MomentImageHost &mi, int numBits, const vector<Byte> &qs) { assert(!mi.prediction_code); vector<uint32_t> words; unpack_bits(words, qs, numBits); size_t offset = 0; for (int y = 0; y < mi.height; ++y) { for (int x = 0; x < mi.width; ++x) { auto num_moments = mi.get_num_moments(x, y); auto idx = mi.get_idx(x, y); if (num_moments == 0) continue; auto m0 = words[offset]; // read_bytes(qs, b_offset, num_bytes); ++offset; // b_offset += num_bytes; mi.data[idx] = dequantize(m0, numBits, 0.0f, 1.0f); assert(mi.data[idx] >= 0.0f / M_PI && mi.data[idx] <= 1.0f); for (int l = 1; l < num_moments; ++l) { uint32_t qj = words[offset]; // read_bytes(qs, b_offset, num_bytes); // b_offset += num_bytes; ++offset; mi.data[idx + l] = dequantize(qj, numBits, -1.0 / M_PI, 1.0 / M_PI); assert(mi.data[idx + l] >= -1.0f / M_PI && mi.data[idx + l] <= 1.0f / M_PI); } } } } void append(vector<Byte> &qs, uint32_t q, int numBits) { int numBytes = (numBits + 7) / 8; if (numBytes == 1) qs.push_back(static_cast<Byte>(q)); else if (numBytes == 2) { qs.push_back(static_cast<Byte>(q & 0xFF)); qs.push_back(static_cast<Byte>((q >> 8) & 0xFF)); } else if (numBytes == 3) { qs.push_back(static_cast<Byte>(q & 0xFF)); qs.push_back(static_cast<Byte>((q >> 8) & 0xFF)); qs.push_back(static_cast<Byte>((q >> 16) & 0xFF)); } else { qs.push_back(static_cast<Byte>(q & 0xFF)); qs.push_back(static_cast<Byte>((q >> 8) & 0xFF)); qs.push_back(static_cast<Byte>((q >> 16) & 0xFF)); qs.push_back(static_cast<Byte>((q >> 24) & 0xFF)); } } uint32_t read_bits_at_idx(const vector<Byte> &qs, int idx, int numBits) { int numBytes = (numBits + 7) / 8; if (numBytes == 1) return qs[idx]; else if (numBytes == 2) { uint32_t res = qs[idx * numBytes]; res |= qs[idx * numBytes + 1] << 8; return res; } else if (numBytes == 3) { uint32_t res = qs[idx * numBytes]; res |= qs[idx * numBytes + 1] << 8; res |= qs[idx * numBytes + 2] << 16; return res; } else { uint32_t res = qs[idx * numBytes]; res |= qs[idx * numBytes + 1] << 8; res |= qs[idx * numBytes + 2] << 16; res |= qs[idx * numBytes + 3] << 24; return res; } } vector<Byte> quantize(const vector<float> &moments, int numMoments, int numBits) { int numRays = moments.size() / numMoments; vector<Byte> qs; qs.reserve(numRays * numMoments * static_cast<int>((numBits + 7) / 8)); for (int i = 0; i < numRays; ++i) { float m0 = moments[i * numMoments]; uint32_t q0 = quantize(m0, numBits, 0.0f, 1.0f); append(qs, q0, numBits); for (int j = 1; j < numMoments; ++j) { float mj = moments[i * numMoments + j]; append(qs, quantize(mj, numBits, -1.0 / M_PI, 1.0 / M_PI), numBits); } } return qs; } vector<float> dequantize(const vector<Byte> &qs, int numMoments, int numBits) { int numBytes = (numBits + 7) / 8; int numRays = qs.size() / numMoments / numBytes; vector<float> values; values.reserve(numRays * numMoments); for (int i = 0; i < numRays; ++i) { uint32_t q0 = read_bits_at_idx(qs, i * numMoments, numBits); values.push_back(dequantize(q0, numBits, 0.0f, 1.0f)); for (int j = 1; j < numMoments; ++j) { uint32_t qj = read_bits_at_idx(qs, numMoments * i + j, numBits); values.push_back(dequantize(qj, numBits, -1.0 / M_PI, 1.0 / M_PI)); } } return values; } } // namespace moment_quantization
28.866667
118
0.553118
TobiasRp
7c49113f755566789ee39bf2b097dddcaf588764
774
hpp
C++
03_Simple_2D_game/Asteroid/include/SFML-Book/Player.hpp
Krozark/SFML-book
397dd3dc0c73b694d4b5c117e974c7ebdb885572
[ "BSD-2-Clause" ]
75
2015-01-18T21:29:03.000Z
2022-02-09T14:11:05.000Z
03_Simple_2D_game/Asteroid/include/SFML-Book/Player.hpp
Krozark/SFML-book
397dd3dc0c73b694d4b5c117e974c7ebdb885572
[ "BSD-2-Clause" ]
7
2015-03-12T10:41:55.000Z
2020-11-23T11:15:58.000Z
03_Simple_2D_game/Asteroid/include/SFML-Book/Player.hpp
Krozark/SFML-book
397dd3dc0c73b694d4b5c117e974c7ebdb885572
[ "BSD-2-Clause" ]
33
2015-12-01T07:34:46.000Z
2022-03-23T03:37:42.000Z
#ifndef BOOK_PLAYER_HPP #define BOOK_PLAYER_HPP #include <SFML-Book/ActionTarget.hpp> //ActionTarget #include <SFML-Book/Entity.hpp> //Entity namespace book { class Player : public Entity , public ActionTarget<int> { public: Player(const Player&) = delete; Player& operator=(const Player&) = delete; Player(World& world); virtual bool isCollide(const Entity& other)const; virtual void update(sf::Time deltaTime); void processEvents(); void shoot(); void goToHyperspace(); virtual void onDestroy(); private: bool _isMoving; int _rotation; sf::Time _timeSinceLastShoot; }; } #endif
20.918919
61
0.576227
Krozark
7c4a20ef6c026977e9bb341654500cb624718f3f
437
hpp
C++
src/utils/types.hpp
LukaszSelwa/min-cut
f11eec7d3c55b886112179d8893ef6ed9b3fc2d5
[ "MIT" ]
null
null
null
src/utils/types.hpp
LukaszSelwa/min-cut
f11eec7d3c55b886112179d8893ef6ed9b3fc2d5
[ "MIT" ]
null
null
null
src/utils/types.hpp
LukaszSelwa/min-cut
f11eec7d3c55b886112179d8893ef6ed9b3fc2d5
[ "MIT" ]
null
null
null
#ifndef UTILS_TYPES_H #define UTILS_TYPES_H #include <memory> #include <vector> #include "../graphs/undirected_weighted_graph.hpp" struct algo_result { int minCutVal; std::vector<bool> cut; }; struct algo_input { std::shared_ptr<graphs::weighted_graph> graph; std::vector<bool> minCut; int minCutVal; }; bool validate_cuts(const std::vector<bool>& cutA, const std::vector<bool>& cutB); #endif /* UTILS_TYPES_H */
20.809524
81
0.718535
LukaszSelwa
7c4c0616aa4fa792076e6acee28793e04471ef6f
422
cpp
C++
机试/动态规划/leetcode300.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
机试/动态规划/leetcode300.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
机试/动态规划/leetcode300.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
class Solution { public: int lengthOfLIS(vector<int>& nums) { int n = nums.size(); vector<int> dp(n, 1); int res = dp[0]; for(int i = 0; i < n; i++){ for(int j = 0; j <= i; j++){ if(nums[i] > nums[j]){ dp[i] = max(dp[j] + 1, dp[i]); } } res = max(res, dp[i]); } return res; } };
24.823529
50
0.350711
codehuanglei
7c4c60fc018b62608c46fe0ec12d9b8de69d27c3
2,802
cpp
C++
trunk/uidesigner/uidframe/src/Core/HoldItem.cpp
OhmPopy/MPFUI
eac88d66aeb88d342f16866a8d54858afe3b6909
[ "MIT" ]
59
2017-08-27T13:27:55.000Z
2022-01-21T13:24:05.000Z
demos/uidesigner/uidframe/src/Core/HoldItem.cpp
BigPig0/MPFUI
7042e0a5527ab323e16d2106d715db4f8ee93275
[ "MIT" ]
5
2017-11-26T05:40:23.000Z
2019-04-02T08:58:21.000Z
demos/uidesigner/uidframe/src/Core/HoldItem.cpp
BigPig0/MPFUI
7042e0a5527ab323e16d2106d715db4f8ee93275
[ "MIT" ]
49
2017-08-24T08:00:50.000Z
2021-11-07T01:24:41.000Z
#include "stdafx.h" #include <Core/HoldItem.h> #include <Core/ResNode.h> void HoldItem::InitNode(suic::IXamlNode* pNode) { pNode->Reset(); InitNode(this, pNode); } void HoldItem::Clear() { for (int i = 0; i < children.GetCount(); ++i) { Clear(children.GetItem(i)); } attrs.Clear(); children.Clear(); } String HoldItem::GetResXml(const String& offset) { String strChild = GetResXml(this, offset); return strChild; } String HoldItem::GetChildResXml(const String& offset) { String strChild; for (int j = 0; j < children.GetCount(); ++j) { HoldItem* pChild = children.GetItem(j); strChild += GetResXml(pChild, offset); } return strChild; } void HoldItem::CloneTo(HoldItem* Other) { Other->Clear(); Other->name = name; for (int i = 0; i < attrs.GetCount(); ++i) { Other->attrs.Add(attrs.GetItem(i)); } for (int j = 0; j < children.GetCount(); ++j) { HoldItem* pChild = children.GetItem(j); HoldItem* pOtherChild = new HoldItem(); Other->children.Add(pOtherChild); pChild->CloneTo(pOtherChild); } } void HoldItem::Clear(HoldItem* pHold) { for (int i = 0; i < pHold->children.GetCount(); ++i) { Clear(pHold->children.GetItem(i)); } delete pHold; } void HoldItem::InitNode(HoldItem* pHold, suic::IXamlNode* pNode) { pHold->name = pNode->GetName(); suic::IXamlAttris* pAttris = pNode->GetAttris(); if (NULL != pAttris) { while (pAttris->HasNext()) { StringPair pair(pAttris->GetName(), pAttris->GetValue()); pHold->attrs.Add(pair); } } while (pNode->HasNext()) { suic::IXamlNode* childNode = pNode->Current(); if (NULL != childNode) { HoldItem* pChildItem = new HoldItem(); pHold->children.Add(pChildItem); InitNode(pChildItem, childNode); } } } String HoldItem::GetResXml(HoldItem* pHold, const String& offset) { String strXml; strXml += offset + _U("<") + pHold->name; for (int i = 0; i < pHold->attrs.GetCount(); ++i) { StringPair& pair = pHold->attrs.GetItem(i); strXml += _U(" ") + pair.GetKey() + _U("=\"") + pair.GetValue() + _U("\""); } if (pHold->children.GetCount() > 0) { strXml += _U(">\n"); String strChild; for (int j = 0; j < pHold->children.GetCount(); ++j) { HoldItem* pChildHold = pHold->children.GetItem(j); strChild += GetResXml(pChildHold, offset + ResNode::OFFSET1); } strXml += strChild; strXml += offset + _U("</") + pHold->name + _U(">\n"); } else { strXml += _U(" />\n"); } return strXml; }
22.416
83
0.552463
OhmPopy
7c50c242e93c7ac923266b8307ed15728e6e63f1
3,708
hpp
C++
src/sqlite/db.hpp
wesselj1/mx3playground
9b8c3e783f574a76cc17a9470b57e72a1b38be1a
[ "MIT" ]
766
2015-01-01T17:33:40.000Z
2022-02-23T08:20:20.000Z
src/sqlite/db.hpp
wesselj1/mx3playground
9b8c3e783f574a76cc17a9470b57e72a1b38be1a
[ "MIT" ]
43
2015-01-04T05:59:54.000Z
2017-06-19T10:53:59.000Z
src/sqlite/db.hpp
wesselj1/mx3playground
9b8c3e783f574a76cc17a9470b57e72a1b38be1a
[ "MIT" ]
146
2015-01-09T19:38:23.000Z
2021-09-30T08:39:44.000Z
#pragma once #include <set> #include <chrono> #include "stl.hpp" #include "stmt.hpp" namespace mx3 { namespace sqlite { // single param helpers for sqlite3_mprintf string mprintf(const char * format, const string& data); string mprintf(const char * format, int64_t data); string libversion(); string sourceid(); int libversion_number(); string escape_column(const string& column); enum class ChangeType { INSERT, UPDATE, DELETE }; enum class OpenFlag { READONLY, READWRITE, CREATE, URI, MEMORY, NOMUTEX, FULLMUTEX, SHAREDCACHE, PRIVATECACHE }; enum class Checkpoint { PASSIVE, FULL, RESTART }; enum class Affinity { TEXT, NUMERIC, INTEGER, REAL, NONE }; struct ColumnInfo final { int64_t cid; string name; string type; Affinity type_affinity() const; bool notnull; optional<string> dflt_value; int32_t pk; bool is_pk() const { return pk != 0; } }; struct TableInfo final { string name; string sql; int64_t rootpage; vector<ColumnInfo> columns; }; class Db final : public std::enable_shared_from_this<Db> { public: struct Change final { ChangeType type; string db_name; string table_name; int64_t rowid; }; using UpdateHookFn = function<void(Change)>; using CommitHookFn = function<bool()>; using RollbackHookFn = function<void()>; using WalHookFn = function<void(const string&, int)>; // use this constructor if you want to simply open the database with default settings static shared_ptr<Db> open(const string& path); // use this constructor if you want to simply open an in memory database with the default flags static shared_ptr<Db> open_memory(); // the most general Db constructor, directly mirrors sqlite3_open_v2 static shared_ptr<Db> open(const string& path, const std::set<OpenFlag>& flags, const optional<string>& vfs_name = nullopt); // use this constructor if you want to do anything custom to set up your database static shared_ptr<Db> inherit_db(sqlite3 * db); ~Db(); void update_hook(const UpdateHookFn& update_fn); void commit_hook(const CommitHookFn& commit_fn); void rollback_hook(const RollbackHookFn& rollback_fn); void wal_hook(const WalHookFn& wal_fn); std::pair<int, int> wal_checkpoint_v2(const optional<string>& db_name, Checkpoint mode); string journal_mode(); int64_t last_insert_rowid(); int32_t schema_version(); void busy_timeout(nullopt_t); void busy_timeout(std::chrono::system_clock::duration timeout); vector<TableInfo> schema_info(); optional<TableInfo> table_info(const string& table_name); vector<ColumnInfo> column_info(const string& table_name); int32_t user_version(); void set_user_version(int32_t user_ver); // give the ability to fetch the raw db pointer (in case you need to do anything special) sqlite3 * borrow_db(); shared_ptr<Stmt> prepare(const string& sql); void exec(const string& sql); int64_t exec_scalar(const string& sql); void enable_wal(); void close(); private: struct Closer final { void operator() (sqlite3 * db) const; }; struct only_for_internal_make_shared_t; public: // make_shared constructor Db(only_for_internal_make_shared_t flag, unique_ptr<sqlite3, Closer> db); private: unique_ptr<sqlite3, Closer> m_db; // To ensure proper memory management, these hooks are owned by the database. unique_ptr<UpdateHookFn> m_update_hook; unique_ptr<CommitHookFn> m_commit_hook; unique_ptr<RollbackHookFn> m_rollback_hook; unique_ptr<WalHookFn> m_wal_hook; }; } }
26.676259
128
0.699838
wesselj1
7c5115db2bd1096958da5285052bd6aa076b0e60
14,920
inl
C++
include/writer.inl
jpulidojr/VizAly-SNWPAC
ec30d5e50b8a7ab04a2888c8aae82dcb327e02bd
[ "Unlicense", "BSD-3-Clause" ]
2
2020-03-19T07:14:54.000Z
2022-03-11T19:29:33.000Z
include/writer.inl
jpulidojr/VizAly-SNWPAC
ec30d5e50b8a7ab04a2888c8aae82dcb327e02bd
[ "Unlicense", "BSD-3-Clause" ]
null
null
null
include/writer.inl
jpulidojr/VizAly-SNWPAC
ec30d5e50b8a7ab04a2888c8aae82dcb327e02bd
[ "Unlicense", "BSD-3-Clause" ]
2
2019-07-22T16:14:52.000Z
2020-03-19T07:14:56.000Z
#include "stdio.h" #include <iostream> #include <fstream> #include <cstdlib> #include <string.h> //#include <math.h> #include <sstream> //Use existing lossless compressors #include "lz4.h" /*static int * pfs1; static int dimx1, dimy1, dimz1; static int header_size1, scalar_fields1; static double field_len1;*/ // These functions typically used by LZ4 static size_t write_uint16(FILE* fp, uint16_t i) { return fwrite(&i, sizeof(i), 1, fp); } static size_t write_bin(FILE* fp, const void* array, int arrayBytes) { return fwrite(array, 1, arrayBytes, fp); } template <typename T> int arr_to_vti_3d_range_scale(T **** in, const char * filename,int xl,int xu, int yl,int yu, int zl, int zu, std::vector<std::string> names) { int sizeof_val = sizeof(in[0][0][0][0]); //if(!readConfigw()) //{ // std::cout << "Error reading configuration file. Exiting..." << std::endl; // return 0; //} //int *prefs = pfs1; //std::string * field_names = fn1; int dimx1 = (xu-xl)+1;//prefs[0]; int dimy1 = (yu-yl)+1;//prefs[1]; int dimz1 = (zu-zl)+1;//prefs[2]; //header_size1 = prefs[3]; int scalar_fields1 = names.size();//fld;//prefs[4]; //int num_blocks = prefs[5]; //std::cout << "Dimensions "<< dimx1 << " " << dimy1 << " " << dimz1 <<std::endl; //std::cout << "Header " << header_size1 << " Fields " << scalar_fields1<<std::endl; //std::cout << "Num Blocks " << num_blocks << std::endl; //field_len = (double)((length-header_size) / scalar_fields); size_t field_len1 = (double)dimx1*dimy1*dimz1*8; //std::cout << "Length per field: " << field_len1 << std::endl; // Skip the first bytes of the header //f.seekg (header_size, std::ios::cur); size_t len; len = strlen(filename); //std::string * part_filenames = new std::string[num_blocks+1]; int num_blocks=1; // Define arrays for extent lengths int ** ext_strt = new int*[num_blocks]; int ** ext_end = new int*[num_blocks]; for (int m = 0; m < num_blocks; ++m) { ext_strt[m] = new int[3]; ext_end[m] = new int[3]; } // Define a size for 1 block of data int * block_size=new int[3]; int blockID=0; // Set the extents for the entire dataset ext_strt[blockID][0]=xl; ext_strt[blockID][1]=yl; ext_strt[blockID][2]=zl; ext_end[blockID][0]=xu; ext_end[blockID][1]=yu; ext_end[blockID][2]=zu; // Set block size block_size[0]=(xu-xl)+1;block_size[1]=(yu-yl)+1;block_size[2]=(zu-zl)+1; // Start creating each individual block //for(int g=0; g<num_blocks; g++) //{ int g = 0; std::ofstream out; // Create the output file printf("Creating %s\n", filename); out.open(filename, std::ifstream::binary); out.precision(20); // Write VTK format header out << "<VTKFile type=\"ImageData\" version=\"0.1\" byte_order=\"LittleEndian\">"<<std::endl; out << " <ImageData WholeExtent=\""<<ext_strt[g][0]<<" "<<ext_end[g][0]<<" "<<ext_strt[g][1]; out << " "<<ext_end[g][1]<<" "<<ext_strt[g][2]<<" "<<ext_end[g][2]<<"\""; out << " Origin=\"0 0 0\" Spacing=\"1 1 1\">"<<std::endl; out << " <Piece Extent=\""<<ext_strt[g][0]<<" "<<ext_end[g][0]<<" "<<ext_strt[g][1]; out << " "<<ext_end[g][1]<<" "<<ext_strt[g][2]<<" "<<ext_end[g][2]<<"\">"<<std::endl; out << " <PointData Scalars=\"density_scalars\">"<<std::endl; int bin_offset = 0; int * ghost = new int[3]; // Write the headers for each of the scalar fields (assuming they're doubles) for(int i=0; i<scalar_fields1; i++) { // Factor in ghost data into the blocks if(ext_strt[g][0]!=0){ghost[0]=0;}else{ghost[0]=0;} if(ext_strt[g][1]!=0){ghost[1]=0;}else{ghost[1]=0;} if(ext_strt[g][2]!=0){ghost[2]=0;}else{ghost[2]=0;} //printf("%i %i %i\n", ghost[0], ghost[1], ghost[2]); if( sizeof_val == 8 ) out << " <DataArray type=\"Float64\" Name=\""<<names[i]<<"\" format=\"appended\" offset=\""<< (double)(i*((double)(block_size[0]+ghost[0])*(block_size[1]+ghost[1])*(block_size[2]+ghost[2])*8))+bin_offset <<"\"/>"<<std::endl; else if( sizeof_val == 4) out << " <DataArray type=\"Float32\" Name=\""<<names[i]<<"\" format=\"appended\" offset=\""<< (double)(i*((double)(block_size[0]+ghost[0])*(block_size[1]+ghost[1])*(block_size[2]+ghost[2])*4))+bin_offset <<"\"/>"<<std::endl; else { std::cout << "ERROR: Data size of " << sizeof_val << " bytes not supported for vti!" << std::endl; return -1; } bin_offset += 4; } out << " </PointData>"<<std::endl; out << " <CellData>" << std::endl; out << " </CellData>" << std::endl; out << " </Piece>"<<std::endl; out << " </ImageData>"<<std::endl; out << " <AppendedData encoding=\"raw\">"<<std::endl; // Denote that you are about to write in binary out << " _"; //char * bin_value= new char[sizeof_val];//[8]; //std::cout<< "["; for(int sf=0; sf < scalar_fields1; sf++) { // As per the API, first encode a 32-bit unsigned integer value specifying // the number of bytes in the block of data following it unsigned int block_byte_size = ((block_size[0]+ghost[0])*(block_size[1]+ghost[1])*(block_size[2]+ghost[2]))*8; if(((double)block_size[0]*block_size[1]*block_size[2]*8) > 4294967296.0) { printf("Error: Scalar field size is too large. Choose a larger\n"); printf("number of blocks to segment by.\n"); return 0; } out.write( reinterpret_cast<char*>( &block_byte_size ), 4 ); int c=0; for(int z=ext_strt[g][2]; z<=ext_end[g][2]; z++) { int b=0; for(int y=ext_strt[g][1]; y<=ext_end[g][1]; y++) { int a=0; for(int x=ext_strt[g][0]; x<=ext_end[g][0]; x++) { T dbl_val = (T)in[sf][a][b][c]; out.write(reinterpret_cast<char*>( &dbl_val ), sizeof_val);//sizeof(double)); a++; } b++; } c++; } //std::cout<<"] - "<<field_names[sf]<<" done!\n["; } //printf("Complete!"); //std::cout<<"]\n"; //Finish off the xml file out << std::endl; out << " </AppendedData>"<<std::endl; out << "</VTKFile>"; //printf("%s Done!\n", part_filenames[g+1].c_str()); out.close(); //} //std::cout<<"Done!"<<std::endl; return 0; } template <typename T> int save_coefficients(T * data, const char * filename, size_t total) { std::ofstream out; // Create the output file printf("Creating %s\n", filename); out.open(filename, std::ifstream::binary); out.precision(20); for(int sz=0; sz < total; sz++) { T dbl_val = data[sz]; out.write(reinterpret_cast<char*>( &dbl_val ), sizeof(T)); } std::cout<<"Coefficient's saved\n"; out.close(); return 1; } template <typename T> int save_coefficients_md(T * data, const char * filename, int * args) { std::ofstream out; // Create the output file printf("Creating %s\n", filename); out.open(filename, std::ifstream::binary); //out.precision(20); short * tmp_s = new short[1]; char * tmp_c = new char[1]; int * tmp_i = new int[1]; // Write the header tmp_s[0] = args[0]; out.write(reinterpret_cast<char*>( tmp_s ), sizeof(short)); tmp_s[0] = args[1]; out.write(reinterpret_cast<char*>( tmp_s ), sizeof(short)); tmp_c[0] = args[2]; out.write(reinterpret_cast<char*>( tmp_c ), sizeof(char)); tmp_s[0] = args[3]; out.write(reinterpret_cast<char*>( tmp_s ), sizeof(short)); tmp_i[0] = args[4]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int)); tmp_i[0] = args[5]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int)); tmp_i[0] = args[6]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int)); tmp_i[0] = args[7]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int)); tmp_i[0] = args[8]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int)); tmp_i[0] = args[9]; out.write(reinterpret_cast<char*>( tmp_i ), sizeof(int)); tmp_c[0] = args[10];out.write(reinterpret_cast<char*>( tmp_c ), sizeof(char)); delete [] tmp_s; delete [] tmp_c; delete [] tmp_i; size_t total = (size_t)args[4]*(size_t)args[5]*(size_t)args[6]; // Check if we are using lz4 on coefficients if (args[2] >= 118) { std::cout << "Beginning LZ4 Routines..."; // Optional: Perform floating point to integer requantization: // No Requantization if args[2]=128 // When it's 125, it's 128-125 = 3. We divide by 1000 // When it's 131, it's 128-131 = -3. Multibly by 1000 double mod_bits = 1; size_t oval_sz = sizeof(T); if( args[2] > 128 ) // Multiply (for small dyn range data) { int cnt = args[2]; while (cnt != 128) { mod_bits *= 10.0; cnt--; } oval_sz = sizeof(int); std::cout << "requantizing coefficients: 1*10^" << args[2] - 128 << std::endl; } if(args[2] < 128 ) // Divide (for high dyn range data) { int cnt = args[2]; while (cnt != 128) { mod_bits /= 10.0; cnt++; } oval_sz = sizeof(int); std::cout << "requantizing coefficients: 1*10^-" << 128 - args[2] << std::endl; } // Target output variable (type) T dbl_val; //int dbl_val; // INT SUPPORT const size_t totBytes = total * oval_sz; size_t datBytes = totBytes; // WARNING: LZ4_MAX_INPUT_SIZE is about 2MB so suggest using a sliding buffer // Restriction inside of srcSize if (totBytes > LZ4_MAX_INPUT_SIZE) { std::cout << "Warning: Data to write is larger than supported by Lz4. Use rolling buffer!!\n"; datBytes = LZ4_MAX_INPUT_SIZE; } LZ4_stream_t* lz4Stream = LZ4_createStream(); const size_t cmpBufBytes = LZ4_COMPRESSBOUND(datBytes); //messageMaxBytes //Preallocate buffers char * inBuf = new char[datBytes]; char * cmpBuf = new char[cmpBufBytes]; // Use a sliding window approach and reinterpert type cast to char * array. // Use a ring buffer???? size_t max_vals = datBytes / oval_sz; std::cout << " Encoding " << max_vals << " values.\n"; size_t sk = 0; char * cval; if (oval_sz == 4) { int dbl_val; // int for requantization for (size_t sz = 0; sz < max_vals; sz++) { //dbl_val = data[sz]*100000; // INT SUPPORT dbl_val = data[sz]*mod_bits; // INT SUPPORT sk = sz * sizeof(dbl_val); cval = reinterpret_cast<char*>(&dbl_val); for (size_t id = 0; id < sizeof(dbl_val); id++) { inBuf[sk + id] = cval[id]; } } } else if (oval_sz == 8) { T dbl_val; // No requant for (size_t sz = 0; sz < max_vals; sz++) { dbl_val = data[sz]; sk = sz * sizeof(dbl_val); cval = reinterpret_cast<char*>(&dbl_val); for (size_t id = 0; id < sizeof(dbl_val); id++) { inBuf[sk + id] = cval[id]; } //delete[] cval; //inBuf[sk] = reinterpret_cast<char*>(&dbl_val), sizeof(dbl_val); //Insert T val into character buffer //memcpy? } } else { std::cout << "ERROR: Invalid byte size!" << std::endl; return -1; } //const int cmpBytes = LZ4_compress_fast_continue(lz4Stream, inBuf, cmpBuf, datBytes, cmpBufBytes, 1); /rolling int cmpBytes = LZ4_compress_default(inBuf, cmpBuf, datBytes, cmpBufBytes); //Write out the buffer size first //write_uint16(FILE* fp, uint16_t i) out.write(reinterpret_cast<char*>(&cmpBytes), sizeof(cmpBytes)); std::cout << "LZ4: Encoding " << cmpBytes << " bytes.." << std::endl; // Write out bytestream out.write(cmpBuf, cmpBytes); delete[] inBuf; delete[] cmpBuf; LZ4_freeStream(lz4Stream); std::cout << "..Done LZ4!\n"; } // Check if we are encoding coefficients with RLE else if(args[2] >= 64) { std::cout<<"Encoding enabled..."; //unsigned char signal = 0x24; //$ sign UTF-8 char signal = '$'; char signal2 = '@'; char signal3 = '#'; char signal4 = 'h'; //std::cout << "Size of char=" << sizeof(signal) << " value " << signal << std::endl; unsigned short smax=0; float wbytes=0; int skips=0; for(size_t sz=0; sz < total; sz++) { if (data[sz] == 0) { skips++; int cont_block_cnt=0; while (data[sz]==0 && sz < total) { sz++; cont_block_cnt++; // DEBUG } // Encode the number of steps to skip while(cont_block_cnt>65535) //Exceeded u_short_int { smax = 65535; out.write(reinterpret_cast<char*>( &signal ), sizeof(signal)); out.write(reinterpret_cast<char*>( &signal2 ), sizeof(signal2)); out.write(reinterpret_cast<char*>( &signal3 ), sizeof(signal3)); out.write(reinterpret_cast<char*>( &signal4 ), sizeof(signal4)); out.write(reinterpret_cast<char*>( &smax ), sizeof(smax)); skips++; cont_block_cnt-=65535; wbytes+=sizeof(signal)*4+sizeof(smax); } smax = cont_block_cnt; //std::cout << "\nSkipping at byte_loc: " << wbytes << " for " << smax << std::endl; out.write(reinterpret_cast<char*>( &signal ), sizeof(signal)); out.write(reinterpret_cast<char*>( &signal2 ), sizeof(signal2)); out.write(reinterpret_cast<char*>( &signal3 ), sizeof(signal3)); out.write(reinterpret_cast<char*>( &signal4 ), sizeof(signal4)); out.write(reinterpret_cast<char*>( &smax ), sizeof(smax)); wbytes+=sizeof(signal)*4+sizeof(smax); } T dbl_val = data[sz]; out.write(reinterpret_cast<char*>( &dbl_val ), sizeof(dbl_val)); wbytes+=sizeof(dbl_val); } std::cout<<"...Coefficient's saved\n"; std::cout<<"Bytes written (w header): " << wbytes+32 << std::endl; std::cout << "Contiguous skips: " << skips << std::endl; } // Just write coefficients to storage with zeros intact else { for(size_t sz=0; sz < total; sz++) { T dbl_val = data[sz]; out.write(reinterpret_cast<char*>( &dbl_val ), sizeof(T)); } std::cout<<"Coefficient's saved\n"; } out.close(); return 1; }
35.105882
235
0.552413
jpulidojr
7c5976175e28b08a295516dc36fcc5cec67f35a8
1,263
cpp
C++
cpp-tower/Game.cpp
udupa-varun/coursera-cs400
cf073e6fe816c0d1f8fe95cae10448e979fec2ce
[ "MIT" ]
2
2021-05-19T02:49:55.000Z
2021-05-20T03:14:24.000Z
cpp-tower/Game.cpp
udupa-varun/coursera-cs400
cf073e6fe816c0d1f8fe95cae10448e979fec2ce
[ "MIT" ]
null
null
null
cpp-tower/Game.cpp
udupa-varun/coursera-cs400
cf073e6fe816c0d1f8fe95cae10448e979fec2ce
[ "MIT" ]
null
null
null
/** * C++ class for a game of the Tower of Hanoi puzzle. * * @author * Wade Fagen-Ulmschneider <waf@illinois.edu> */ #include "Game.h" #include "Stack.h" #include "uiuc/Cube.h" #include "uiuc/HSLAPixel.h" #include <iostream> using std::cout; using std::endl; // Solves the Tower of Hanoi puzzle. // (Feel free to call "helper functions" to help you solve the puzzle.) void Game::solve() { // Prints out the state of the game: cout << *this << endl; // @TODO -- Finish solving the game! } // Default constructor to create the initial state: Game::Game() { // Create the three empty stacks: for (int i = 0; i < 3; i++) { Stack stackOfCubes; stacks_.push_back( stackOfCubes ); } // Create the four cubes, placing each on the [0]th stack: Cube blue(4, uiuc::HSLAPixel::BLUE); stacks_[0].push_back(blue); Cube orange(3, uiuc::HSLAPixel::ORANGE); stacks_[0].push_back(orange); Cube purple(2, uiuc::HSLAPixel::PURPLE); stacks_[0].push_back(purple); Cube yellow(1, uiuc::HSLAPixel::YELLOW); stacks_[0].push_back(yellow); } std::ostream& operator<<(std::ostream & os, const Game & game) { for (unsigned i = 0; i < game.stacks_.size(); i++) { os << "Stack[" << i << "]: " << game.stacks_[i]; } return os; }
23.388889
71
0.642914
udupa-varun
7c5ce1103a68b63e3fc9d600adfa560a410222c7
488
hpp
C++
src/eepp/window/backend/SDL2/wminfo.hpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
37
2020-01-20T06:21:24.000Z
2022-03-21T17:44:50.000Z
src/eepp/window/backend/SDL2/wminfo.hpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
null
null
null
src/eepp/window/backend/SDL2/wminfo.hpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
9
2019-03-22T00:33:07.000Z
2022-03-01T01:35:59.000Z
#ifndef EE_BACKEND_SDL2_WMINFO_HPP #define EE_BACKEND_SDL2_WMINFO_HPP #include <eepp/window/backend/SDL2/base.hpp> #include <eepp/window/windowhandle.hpp> namespace EE { namespace Window { namespace Backend { namespace SDL2 { class EE_API WMInfo { public: WMInfo( SDL_Window* win ); ~WMInfo(); #if defined( EE_X11_PLATFORM ) X11Window getWindow(); #endif eeWindowHandle getWindowHandler(); protected: void* mWMInfo; }; }}}} // namespace EE::Window::Backend::SDL2 #endif
17.428571
70
0.745902
jayrulez
7c5ed60bd233d69bcd3fec76f48a78d1253ad5bf
2,664
hpp
C++
OptFrame/Experimental/Moves/MoveVVShiftk.hpp
216k155/bft-pos
80c1c84b8ca9a5c1c7462b21b011c89ae97666ae
[ "MIT" ]
2
2018-05-24T11:04:12.000Z
2020-03-03T13:37:07.000Z
OptFrame/Experimental/Moves/MoveVVShiftk.hpp
216k155/bft-pos
80c1c84b8ca9a5c1c7462b21b011c89ae97666ae
[ "MIT" ]
null
null
null
OptFrame/Experimental/Moves/MoveVVShiftk.hpp
216k155/bft-pos
80c1c84b8ca9a5c1c7462b21b011c89ae97666ae
[ "MIT" ]
1
2019-06-06T16:57:49.000Z
2019-06-06T16:57:49.000Z
// OptFrame - Optimization Framework // Copyright (C) 2009-2015 // http://optframe.sourceforge.net/ // // This file is part of the OptFrame optimization framework. This framework // is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License v3 as published by the // Free Software Foundation. // This framework is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License v3 for more details. // You should have received a copy of the GNU Lesser General Public License v3 // along with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. #ifndef OPTFRAME_MOVEVVSHIFTK_HPP_ #define OPTFRAME_MOVEVVSHIFTK_HPP_ // Framework includes #include "../../Move.hpp" #include "../NSVector.hpp" using namespace std; //============================================================================ // VVShiftk Move //============================================================================ template<class T, class DS > class MoveVVShiftk : public Move<vector<vector<T> >, DS > { public: int k,v1,p1,v2,p2; MoveVVShiftk(int k,int v1,int p1,int v2,int p2) { this->k = k; this->v1 = v1; this->p1 = p1; this->v2 = v2; this->p2 = p2; } virtual bool canBeApplied(const vector<vector<T> >&) { return true; } virtual Move<vector<vector<T> >, DS >& apply(vector<vector<T> >& rep) { pair<int,pair < pair<int,int> , pair<int,int> > > m; m.first = k; m.second.first.first = v1; m.second.first.second = p1; m.second.second.first = v2; m.second.second.second = p2; NSVector<T>::shiftk_apply(rep,m); return * new MoveVVShiftk<T,DS >(k,v2,p2,v1,p1); } virtual Move<vector<vector<T> >, DS >& apply(DS& m, vector<vector<T> > & r) { if (!m.empty()) { m[v1].first = m[v2].first = -1; m[v1].second.first = p1; m[v1].second.second = r[v1].size()-1; m[v2].second.first = p2; m[v2].second.second = r[v2].size()-1; } else { //e->setMemory(new MemVRP(r.size(),make_pair(-1,make_pair(0,r.size()-1)))); m = MemVRPTW(r.size(),make_pair(-1,make_pair(0,r.size()-1))); } return apply(r); } virtual void print() const { cout << "Move Vector Vector Shiftk("<< k << " " << v1 << " " << p1 << " " << v2 << " " << p2 <<")"<<endl; } virtual bool operator==(const Move<vector<vector<T> >,DS >& m) const { return false; //TODO } }; #endif /*OPTFRAME_MOVEVVSHIFTK_HPP_*/
27.183673
107
0.613739
216k155
7c61d1f10673dfa4e36c148cfe5116240b21778a
5,786
cpp
C++
src/core/taskmanager.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
2
2019-06-22T23:29:44.000Z
2019-07-07T18:34:04.000Z
src/core/taskmanager.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
src/core/taskmanager.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
/** * @file taskmanager.cpp * @brief Implementation of TaskManager.h * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) * @date 2009-10-05 * @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved. * @details */ #include "o3d/core/precompiled.h" #include "o3d/core/taskmanager.h" #include "o3d/core/debug.h" #include <algorithm> using namespace o3d; TaskManager* TaskManager::m_instance = nullptr; // Singleton instantiation TaskManager* TaskManager::instance() { if (!m_instance) m_instance = new TaskManager(); return m_instance; } // Singleton destruction void TaskManager::destroy() { if (m_instance) { delete m_instance; m_instance = nullptr; } } // Default constructor TaskManager::TaskManager() : m_maxTask(5) { m_instance = (TaskManager*)this; // Used to avoid recursive call when the ctor call himself... // connect himself to the delete task signal onDeleteTask.connect(this, &TaskManager::deleteTask, EvtHandler::CONNECTION_ASYNCH); onFinalizeTask.connect(this, &TaskManager::finalizeTask, EvtHandler::CONNECTION_ASYNCH); } // Destructor TaskManager::~TaskManager() { m_mutex.lock(); // don't wait for any events, so disconnect from all disconnect(); // delete pending task (we don't want they occur) for (IT_TaskList it = m_pendingTasksList.begin(); it != m_pendingTasksList.end(); ++it) { deletePtr(*it); } m_pendingTasksList.clear(); // wait for the end of any running task for (IT_TaskList it = m_runningTasksList.begin(); it != m_runningTasksList.end(); ++it) { (*it)->waitFinish(); // and finally delete it directly deletePtr(*it); } m_runningTasksList.clear(); m_mutex.unlock(); } // Add a task to process. A new task is started if tasks slots are available void TaskManager::addTask(Task *task) { O3D_ASSERT(task); if (!task) { return; } else { RecurMutexLocker locker(m_mutex); // to start the next pending task at finish, for finalize and next for auto deletion task->onTaskFinished.connect(this, &TaskManager::taskFinished, EvtHandler::CONNECTION_ASYNCH); // or when the task execution failed, call for its auto deletion without finalize task->onTaskFailed.connect(this, &TaskManager::taskFailed, EvtHandler::CONNECTION_ASYNCH); // process immediately by this thread if (m_maxTask == 0) { m_runningTasksList.push_back(task); // process the task task->start(False); } else { // empty slot ? if (m_runningTasksList.size() < m_maxTask) { m_runningTasksList.push_back(task); // and start it task->start(True); } else { // pending queue m_pendingTasksList.push_back(task); } } } } // Define the number of maximum simultaneous running tasks. void TaskManager::setNumMaxTasks(UInt32 max) { RecurMutexLocker locker(m_mutex); m_maxTask = max; // start many others tasks as possible while ((m_runningTasksList.size() < m_maxTask) && !m_pendingTasksList.empty()) { Task *task = m_pendingTasksList.front(); m_pendingTasksList.pop_front(); m_runningTasksList.push_back(task); // and start it task->start(True); } } // Get the current number of running tasks. UInt32 TaskManager::getNumRunningTasks() const { RecurMutexLocker locker(const_cast<RecursiveMutex&>(m_mutex)); Int32 size = m_runningTasksList.size(); return size; } // Kills any running tasks. void TaskManager::kill() { RecurMutexLocker locker(m_mutex); for (IT_TaskList it = m_runningTasksList.begin(); it != m_runningTasksList.end(); ++it) { (*it)->kill(); deletePtr(*it); } m_runningTasksList.clear(); for (IT_TaskList it = m_pendingTasksList.begin(); it != m_pendingTasksList.end(); ++it) { deletePtr(*it); } m_pendingTasksList.clear(); } // When a task execution is not a success it call for its deletion. void TaskManager::taskFailed(Task* task) { O3D_ASSERT(task); RecurMutexLocker locker(m_mutex); if (task) { IT_TaskList it = std::find(m_runningTasksList.begin(), m_runningTasksList.end(), task); if (it != m_runningTasksList.end()) { m_runningTasksList.erase(it); onDeleteTask(task); } else { O3D_ERROR(E_InvalidParameter("Unknown running task")); } } // start a new task if necessary if (m_runningTasksList.size() < m_maxTask) { if (!m_pendingTasksList.empty()) { Task *task = m_pendingTasksList.front(); m_pendingTasksList.pop_front(); m_runningTasksList.push_back(task); // and start it task->start(True); } } } // When a task is finished to process it call for its finalize. void TaskManager::taskFinished(Task* task) { O3D_ASSERT(task); if (task) { onFinalizeTask(task); } } // When a task is finalized it call for its deletion. void TaskManager::finalizeTask(Task* task) { O3D_ASSERT(task); if (task) { // finalize task->synchronize(); RecurMutexLocker locker(m_mutex); IT_TaskList it = std::find(m_runningTasksList.begin(), m_runningTasksList.end(), task); if (it != m_runningTasksList.end()) { m_runningTasksList.erase(it); onDeleteTask(task); } else { O3D_ERROR(E_InvalidParameter("Unknown running task")); } } // start a new task if necessary if (m_runningTasksList.size() < m_maxTask) { if (!m_pendingTasksList.empty()) { Task *task = m_pendingTasksList.front(); m_pendingTasksList.pop_front(); m_runningTasksList.push_back(task); // and start it task->start(True); } } } // When delete a task. void TaskManager::deleteTask(Task* task) { O3D_ASSERT(task); if (task) { o3d::deletePtr(task); } }
23.330645
102
0.674732
dream-overflow
7c624d369f6c94c89b1b5af5419e758b6c894c1c
4,325
cpp
C++
alert_db/src/get_images_from_bag.cpp
robotics-upo/siar_remote_packages
09bbbc88fb656524cc523a95704e7d353e260876
[ "MIT" ]
null
null
null
alert_db/src/get_images_from_bag.cpp
robotics-upo/siar_remote_packages
09bbbc88fb656524cc523a95704e7d353e260876
[ "MIT" ]
null
null
null
alert_db/src/get_images_from_bag.cpp
robotics-upo/siar_remote_packages
09bbbc88fb656524cc523a95704e7d353e260876
[ "MIT" ]
1
2020-01-10T07:39:33.000Z
2020-01-10T07:39:33.000Z
#include <rosbag/bag.h> #include <rosbag/view.h> #include <sensor_msgs/Image.h> #include <sensor_msgs/CompressedImage.h> #include <sensor_msgs/image_encodings.h> #include <cv_bridge/cv_bridge.h> #include <opencv/cvwimage.h> #include <opencv/highgui.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/opencv.hpp> #include <cv.h> #include <boost/foreach.hpp> #ifndef foreach #define foreach BOOST_FOREACH #endif // #include <compressed_image_transport/codec.h> #include <compressed_depth_image_transport/codec.h> #include <compressed_depth_image_transport/compression_common.h> #include "ros/ros.h" #include <limits> #include <string> #include <vector> #include <map> #include <fstream> #include <sstream> #include <algorithm> #include <iomanip> // std::setfill, std::setwidth #include <functions/functions.h> using namespace std; namespace enc = sensor_msgs::image_encodings; using namespace cv; double max_range = 10.0; int main(int argc, char **argv) { rosbag::Bag bag; std::string camera("/up"); if (argc < 3) { cerr << "Usage: " << argv[0] << " <bag file> <input_file> [<skip first n images = 0>] \n"; return -1; } int ignore = -1; if (argc > 3) { ignore = atoi(argv[3]); cout << "Ignoring ids with less than: " << ignore << endl; } std::string filename(argv[2]); std::string bag_file(argv[1]); std::vector<std::vector <double> > M; functions::getMatrixFromFile(filename, M); map<string, int> count_map; try { bag.open(string(argv[1]), rosbag::bagmode::Read); std::vector<std::string> topics; topics.push_back("/front/rgb/image_raw/compressed"); topics.push_back("/front_right/rgb/image_raw/compressed"); topics.push_back("/front_left/rgb/image_raw/compressed"); topics.push_back("/back/rgb/image_raw/compressed"); topics.push_back("/back_right/rgb/image_raw/compressed"); topics.push_back("/back_left/rgb/image_raw/compressed"); rosbag::View view(bag, rosbag::TopicQuery(topics)); bool initialized = false; bool _positive = false; bool ignoring = true; unsigned int last_defect = 0; unsigned long curr_msg = 0; unsigned long view_size = view.size(); foreach(rosbag::MessageInstance const m, view) { sensor_msgs::CompressedImage::Ptr im = m.instantiate<sensor_msgs::CompressedImage>(); ROS_INFO("%d%%", (int) ((float)curr_msg/view_size*100.0)); printf("\033[1A"); // Move up X lines; curr_msg++; if (im != NULL) { ros::Time t = im->header.stamp; for (unsigned int i = last_defect; i < M.size(); i++) { ros::Time t1(M[i][0], M[i][1]); ros::Time t2(M[i][2], M[i][3]); // if (t1 < t) { // ROS_INFO("T1 < T"); // // } // if (t < t2) { // ROS_INFO("T < T2"); // } // if (t1.sec < t2.sec) { // ROS_INFO("T1 < T2"); // } if (t1 <= t && t2 >= t) { ROS_INFO("Time: %f", t.toSec()); if (i != last_defect) { count_map.clear(); last_defect = i; ROS_INFO("Detected new defect. Number: %u", last_defect); } if ( count_map.find(m.getTopic()) == count_map.end() ) { count_map[m.getTopic()] = 1; } else { count_map[m.getTopic()]++; } ostringstream filename_; // filename_ filename_ << "defect_" << i << m.getTopic() << "_" << std::setfill ('0') << std::setw (4) << count_map[m.getTopic()] <<".jpg"; string s = filename_.str(); replace(s.begin(), s.end(), '/', '_'); Mat decompressed; try { // Decode image data decompressed = cv::imdecode(im->data, CV_LOAD_IMAGE_UNCHANGED); if (m.getTopic() == topics[2] || m.getTopic() == topics[4]) { // Front left and Back right should be flip flip(decompressed, decompressed, -1); } if (imwrite (s, decompressed)) { ROS_INFO("Exported file: %s", s.c_str()); } else { ROS_ERROR("Could not export file: %s", s.c_str()); } } catch (exception &e) { } } } } } bag.close(); } catch (exception &e) { cerr << "Exception while manipulating the bag " << argv[1] << endl; cerr << "Content " << e.what() << endl; return -2; } printf("\n"); return 0; }
26.863354
131
0.593988
robotics-upo
7c663a8084f25481450e8d5dafdfba19424140e8
883
cpp
C++
lib/bencode/BInteger.cpp
ss16118/torrent-client-cpp
fdc6b37d45ba6c8e798216fd874523fac3eceeed
[ "MIT" ]
24
2021-06-21T10:24:35.000Z
2022-03-21T07:00:36.000Z
lib/bencode/BInteger.cpp
BaiXious/torrent-client-cpp
fdc6b37d45ba6c8e798216fd874523fac3eceeed
[ "MIT" ]
2
2016-07-24T15:34:48.000Z
2018-04-21T13:33:33.000Z
lib/bencode/BInteger.cpp
BaiXious/torrent-client-cpp
fdc6b37d45ba6c8e798216fd874523fac3eceeed
[ "MIT" ]
10
2016-03-25T05:53:12.000Z
2022-02-06T01:28:10.000Z
/** * @file BInteger.cpp * @copyright (c) 2014 by Petr Zemek (s3rvac@gmail.com) and contributors * @license BSD, see the @c LICENSE file for more details * @brief Implementation of the BInteger class. */ #include "BInteger.h" #include "BItemVisitor.h" namespace bencoding { /** * @brief Constructs the integer with the given @a value. */ BInteger::BInteger(ValueType value): _value(value) {} /** * @brief Creates and returns a new integer. */ std::unique_ptr<BInteger> BInteger::create(ValueType value) { return std::unique_ptr<BInteger>(new BInteger(value)); } /** * @brief Returns the integer's value. */ auto BInteger::value() const -> ValueType { return _value; } /** * @brief Sets a new value. */ void BInteger::setValue(ValueType value) { _value = value; } void BInteger::accept(BItemVisitor *visitor) { visitor->visit(this); } } // namespace bencoding
19.622222
71
0.697622
ss16118
7c6a02ae781b48453f543d541aa3efa1524e8e21
4,048
cpp
C++
UVA Online Judge/628_Passwords.cpp
davimedio01/competitive-programming
e2a90f0183c11a90a50738a9a690efe03773d43f
[ "MIT" ]
2
2020-09-10T15:48:02.000Z
2020-09-12T00:05:35.000Z
UVA Online Judge/628_Passwords.cpp
davimedio01/competitive-programming
e2a90f0183c11a90a50738a9a690efe03773d43f
[ "MIT" ]
null
null
null
UVA Online Judge/628_Passwords.cpp
davimedio01/competitive-programming
e2a90f0183c11a90a50738a9a690efe03773d43f
[ "MIT" ]
2
2020-09-09T17:01:05.000Z
2020-09-09T17:02:27.000Z
/*Criado por Davi Augusto - BCC - UNESP Bauru*/ /* Resolvido com Backtracking: 1 - "Escolhas" 2 - "Restrições" 3 - "Objetivo" Escolhas: Colocar dígitos de 0 a 9 na senha com base nas "regras" (# e 0) Restrições: Regras e o dígito (ex: #0). O '#' ficará a palavra e o dígito '0' os números de 0 a 9. Printar crescente. Objetivos: Mostrar todo o conjunto de senha com as regras dadas Critério de parada: dígito alcançar 9 (i <= 9); forem todas as palavras do vetor; todos dígitos disponíveis Padrão: 1) Ir até o final da regra; 2) Ver qual campo é: -> Se for '#', mostrar a palavra atual -> Se for '0', mostrar dígitos de 0 a 9; CONTUDO... 3) Necessário mostrar crescente... Ciclo até fim do vector de palavras */ #include <bits/stdc++.h> #include <iostream> using namespace std; //Função para Mostrar todas as Palavras void mostraPalavras(vector<string> dicio, vector<string> auxfinal){ for(int i = 0; i < dicio.size(); i++){ for(int j = 0; j < auxfinal.size(); j++){ cout << auxfinal[j]; } cout << dicio[i] << endl; } } //Função para Mostrar todos os Dígitos (0 a 9) void mostraDigitos(vector<string> auxfinal){ for (int i = 0; i <= 9; i++) { for (int j = 0; j < auxfinal.size(); j++) { cout << auxfinal[j]; } cout << i << endl; } } //Backtracking void resolveSenha(vector<string> dicio, string regra, int caracRegra, vector<string> auxfinal) { //Caso chegue no último, analisar if(caracRegra == (regra.length()-1)){ //Verificar o caractere correspondente e printar //Dígito if (regra[caracRegra] == '0'){ mostraDigitos(auxfinal); } else if (regra[caracRegra] == '#'){ //Palavra mostraPalavras(dicio, auxfinal); } return; } //Dígito if(regra[caracRegra] == '0'){ for(int i = 0; i <= 9; i++){ //Copiar o dígito pra auxiliar auxfinal.push_back(to_string(i)); //Executando a função novamente e avançando o dígito da regra resolveSenha(dicio, regra, caracRegra + 1, auxfinal); //Removendo o Último Elemento da Auxiliar auxfinal.pop_back(); } } else if(regra[caracRegra] == '#'){ //Palavra for(int j = 0; j < dicio.size(); j++){ //Copiar a palavra pra auxiliar auxfinal.push_back(dicio[j]); //Executando a função novamente e avançando o dígito da regra resolveSenha(dicio, regra, caracRegra + 1, auxfinal); //Removendo o Último Elemento da Auxiliar auxfinal.pop_back(); } } } int main(){ int numpalavras, numregras; while(cin >> numpalavras){ //Vector contendo Dicionário vector<string> dicionario; dicionario.clear(); string dicioaux; //Lendo cada palavra for(int i = 0; i < numpalavras; i++){ cin >> dicioaux; dicionario.push_back(dicioaux); } //Lendo Qtd de Regras cin >> numregras; //Vector contendo as regras vector<string> regras; regras.clear(); string regraux; //Lendo cada regra for(int i = 0; i < numregras; i++){ cin >> regraux; regras.push_back(regraux); } //Mostrando resultado (Backtracking) cout << "--" << endl; //Passar cada regra vector<string> auxfinal; for(int i = 0; i < numregras; i++){ auxfinal.clear(); resolveSenha(dicionario, regras[i], 0, auxfinal); } } return 0; }
28.70922
118
0.516304
davimedio01
7c6a4d9e5140b66d9f8a1a9d1f899b93076511af
10,895
cpp
C++
Main/Libraries/Hunspell/HunspellExportFunctions.cpp
paulushub/SandAssists
ccd86a074e85b3588819253f241780fe9d9362e2
[ "MS-PL" ]
1
2018-12-13T19:41:01.000Z
2018-12-13T19:41:01.000Z
Main/Libraries/Hunspell/HunspellExportFunctions.cpp
paulushub/SandAssists
ccd86a074e85b3588819253f241780fe9d9362e2
[ "MS-PL" ]
null
null
null
Main/Libraries/Hunspell/HunspellExportFunctions.cpp
paulushub/SandAssists
ccd86a074e85b3588819253f241780fe9d9362e2
[ "MS-PL" ]
null
null
null
#include "hunspell/hunspell.hxx" #include <windows.h> #include <locale.h> #include <mbctype.h> #include "NHunspellExtensions.h" #include "EncodingToCodePage.h" #define DLLEXPORT extern "C" __declspec( dllexport ) class NHunspell: public Hunspell { // The methods aren't multi threaded, reentrant or whatever so a encapsulated buffer can be used for performance reasons void * marshalBuffer; size_t marshalBufferSize; void * wordBuffer; size_t wordBufferSize; void * word2Buffer; size_t word2BufferSize; void * affixBuffer; size_t affixBufferSize; public: UINT CodePage; inline NHunspell(const char *affpath, const char *dpath, const char * key = 0) : Hunspell(affpath,dpath,key) { marshalBuffer = 0; marshalBufferSize = 0; wordBuffer = 0; wordBufferSize = 0; word2Buffer = 0; word2BufferSize = 0; affixBuffer = 0; affixBufferSize = 0; char * encoding = get_dic_encoding(); CodePage = EncodingToCodePage( encoding ); } inline ~NHunspell() { if( marshalBuffer != 0 ) free( marshalBuffer ); if( wordBuffer != 0 ) free( wordBuffer ); if( word2Buffer != 0 ) free( word2Buffer ); if( affixBuffer != 0 ) free( affixBuffer ); } // Buffer for marshaling string lists back to .NET void * GetMarshalBuffer(size_t size) { if(size < marshalBufferSize ) return marshalBuffer; if( marshalBufferSize == 0 ) { size += 128; marshalBuffer = malloc( size ); } else { size += 256; marshalBuffer = realloc(marshalBuffer, size ); } marshalBufferSize = size; return marshalBuffer; } // Buffer for the mutibyte representation of a word void * GetWordBuffer(size_t size) { if(size < wordBufferSize ) return wordBuffer; if( wordBufferSize == 0 ) { size += 32; wordBuffer = malloc( size ); } else { size += 64; wordBuffer = realloc(wordBuffer, size ); } wordBufferSize = size; return wordBuffer; } // Buffer for the mutibyte representation of a word void * GetWord2Buffer(size_t size) { if(size < word2BufferSize ) return word2Buffer; if( word2BufferSize == 0 ) { size += 32; word2Buffer = malloc( size ); } else { size += 64; word2Buffer = realloc(wordBuffer, size ); } word2BufferSize = size; return word2Buffer; } inline char * GetWordBuffer( wchar_t * unicodeString ) { int buffersize = WideCharToMultiByte(CodePage,0,unicodeString,-1,0,0,0,0); char * buffer = (char *) GetWordBuffer( buffersize ); WideCharToMultiByte(CodePage,0,unicodeString,-1,buffer,buffersize,0,0); return buffer; } inline char * GetWord2Buffer( wchar_t * unicodeString ) { int buffersize = WideCharToMultiByte(CodePage,0,unicodeString,-1,0,0,0,0); char * buffer = (char *) GetWord2Buffer( buffersize ); WideCharToMultiByte(CodePage,0,unicodeString,-1,buffer,buffersize,0,0); return buffer; } // Buffer for the mutibyte representation of an affix void * GetAffixBuffer(size_t size) { if(size < affixBufferSize ) return affixBuffer; if( affixBufferSize == 0 ) { size += 32; affixBuffer = malloc( size ); } else { size += 64; affixBuffer = realloc(affixBuffer, size ); } affixBufferSize = size; return affixBuffer; } inline char * GetAffixBuffer( wchar_t * unicodeString ) { int buffersize = WideCharToMultiByte(CodePage,0,unicodeString,-1,0,0,0,0); char * buffer = (char *) GetAffixBuffer( buffersize ); WideCharToMultiByte(CodePage,0,unicodeString,-1,buffer,buffersize,0,0); return buffer; } }; inline char * AllocMultiByteBuffer( wchar_t * unicodeString ) { int buffersize = WideCharToMultiByte(CP_UTF8,0,unicodeString,-1,0,0,0,0); char * buffer = (char *) malloc( buffersize ); WideCharToMultiByte(CP_UTF8,0,unicodeString,-1,buffer,buffersize,0,0); return buffer; } /************************* Export Functions **************************************************************/ DLLEXPORT NHunspell * HunspellInit(void * affixBuffer, size_t affixBufferSize, void * dictionaryBuffer, size_t dictionaryBufferSize, wchar_t * key) { char * key_buffer = 0; if( key != 0 ) key_buffer = AllocMultiByteBuffer(key); MemoryBufferInformation affixBufferInfo; affixBufferInfo.magic = magicConstant; affixBufferInfo.buffer = affixBuffer; affixBufferInfo.bufferSize = affixBufferSize; MemoryBufferInformation dictionaryBufferInfo; dictionaryBufferInfo.magic = magicConstant; dictionaryBufferInfo.buffer = dictionaryBuffer; dictionaryBufferInfo.bufferSize = dictionaryBufferSize; NHunspell * result = new NHunspell((const char *) &affixBufferInfo, (const char *) &dictionaryBufferInfo,key_buffer); if( key_buffer != 0 ) free( key_buffer ); return result; } DLLEXPORT void HunspellFree(NHunspell * handle ) { delete handle; } DLLEXPORT bool HunspellAdd(NHunspell * handle, wchar_t * word ) { char * word_buffer = handle->GetWordBuffer(word); int success = handle->add(word_buffer); return success != 0; } DLLEXPORT bool HunspellAddWithAffix(NHunspell * handle, wchar_t * word, wchar_t * example ) { char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word); char * example_buffer = ((NHunspell *) handle)->GetWord2Buffer(example); bool success = handle->add_with_affix(word_buffer,example_buffer) != 0; return success; } DLLEXPORT bool HunspellSpell(NHunspell * handle, wchar_t * word ) { char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word); bool correct = ((NHunspell *) handle)->spell(word_buffer) != 0; return correct; } DLLEXPORT void * HunspellSuggest(NHunspell * handle, wchar_t * word ) { char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word); char ** wordList; int wordCount = ((NHunspell *) handle)->suggest(&wordList, word_buffer); // Cacculation of the Marshalling Buffer. // Layout: {Pointers- zero terminated}{Wide Strings - zero terminated} size_t bufferSize = (wordCount + 1) * sizeof (wchar_t **); for( int i = 0; i < wordCount; ++ i ) bufferSize += MultiByteToWideChar(handle->CodePage,0,wordList[i],-1,0,0) * sizeof( wchar_t); BYTE * marshalBuffer = (BYTE *) ((NHunspell *) handle)->GetMarshalBuffer( bufferSize ); wchar_t ** pointer = (wchar_t ** ) marshalBuffer; wchar_t * buffer = (wchar_t * ) (marshalBuffer + (wordCount + 1) * sizeof (wchar_t **)); for( int i = 0; i < wordCount; ++ i ) { *pointer = buffer; size_t wcsSize = MultiByteToWideChar(handle->CodePage,0,wordList[i],-1,0,0); MultiByteToWideChar(handle->CodePage,0,wordList[i],-1,buffer,wcsSize); // Prepare pointers for the next string buffer += wcsSize; ++pointer; } // Zero terminate the pointer list *pointer = 0; ((NHunspell *) handle)->free_list(&wordList, wordCount); return marshalBuffer; } DLLEXPORT void * HunspellAnalyze(NHunspell * handle, wchar_t * word ) { char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word); char ** morphList; int morphCount = ((NHunspell *) handle)->analyze(&morphList, word_buffer); // Cacculation of the Marshalling Buffer. Layout: {Pointers- zero terminated}{Wide Strings - zero terminated} size_t bufferSize = (morphCount + 1) * sizeof (wchar_t **); for( int i = 0; i < morphCount; ++ i ) bufferSize += MultiByteToWideChar(handle->CodePage,0,morphList[i],-1,0,0) * sizeof( wchar_t); BYTE * marshalBuffer = (BYTE *) ((NHunspell *) handle)->GetMarshalBuffer( bufferSize ); wchar_t ** pointer = (wchar_t ** ) marshalBuffer; wchar_t * buffer = (wchar_t * ) (marshalBuffer + (morphCount + 1) * sizeof (wchar_t **)); for( int i = 0; i < morphCount; ++ i ) { *pointer = buffer; size_t wcsSize = MultiByteToWideChar(handle->CodePage,0,morphList[i],-1,0,0); MultiByteToWideChar(handle->CodePage,0,morphList[i],-1,buffer,wcsSize); // Prepare pointers for the next string buffer += wcsSize; ++pointer; } // Zero terminate the pointer list *pointer = 0; ((NHunspell *) handle)->free_list(&morphList, morphCount); return marshalBuffer; } DLLEXPORT void * HunspellStem(NHunspell * handle, wchar_t * word ) { char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word); char ** stemList; int stemCount = ((NHunspell *) handle)->stem(&stemList, word_buffer); // Cacculation of the Marshalling Buffer. Layout: {Pointers- zero terminated}{Wide Strings - zero terminated} size_t bufferSize = (stemCount + 1) * sizeof (wchar_t **); for( int i = 0; i < stemCount; ++ i ) bufferSize += MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,0,0) * sizeof( wchar_t); BYTE * marshalBuffer = (BYTE *) ((NHunspell *) handle)->GetMarshalBuffer( bufferSize ); wchar_t ** pointer = (wchar_t ** ) marshalBuffer; wchar_t * buffer = (wchar_t * ) (marshalBuffer + (stemCount + 1) * sizeof (wchar_t **)); for( int i = 0; i < stemCount; ++ i ) { *pointer = buffer; size_t wcsSize = MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,0,0); MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,buffer,wcsSize); // Prepare pointers for the next string buffer += wcsSize; ++pointer; } // Zero terminate the pointer list *pointer = 0; ((NHunspell *) handle)->free_list(&stemList, stemCount); return marshalBuffer; } DLLEXPORT void * HunspellGenerate(NHunspell * handle, wchar_t * word, wchar_t * word2 ) { char * word_buffer = ((NHunspell *) handle)->GetWordBuffer(word); char * word2_buffer = ((NHunspell *) handle)->GetWord2Buffer(word2); char ** stemList; int stemCount = ((NHunspell *) handle)->generate(&stemList, word_buffer, word2_buffer); // Cacculation of the Marshalling Buffer. Layout: {Pointers- zero terminated}{Wide Strings - zero terminated} size_t bufferSize = (stemCount + 1) * sizeof (wchar_t **); for( int i = 0; i < stemCount; ++ i ) bufferSize += MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,0,0) * sizeof( wchar_t); BYTE * marshalBuffer = (BYTE *) ((NHunspell *) handle)->GetMarshalBuffer( bufferSize ); wchar_t ** pointer = (wchar_t ** ) marshalBuffer; wchar_t * buffer = (wchar_t * ) (marshalBuffer + (stemCount + 1) * sizeof (wchar_t **)); for( int i = 0; i < stemCount; ++ i ) { *pointer = buffer; size_t wcsSize = MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,0,0); MultiByteToWideChar(handle->CodePage,0,stemList[i],-1,buffer,wcsSize); // Prepare pointers for the next string buffer += wcsSize; ++pointer; } // Zero terminate the pointer list *pointer = 0; ((NHunspell *) handle)->free_list(&stemList, stemCount); return marshalBuffer; }
27.935897
148
0.663148
paulushub
7c7271cd1bc6633e31eff5ad8cfbeb76ab576099
11,886
hpp
C++
libraries/protocol/include/deip/protocol/deip_virtual_operations.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
1
2021-08-16T12:44:43.000Z
2021-08-16T12:44:43.000Z
libraries/protocol/include/deip/protocol/deip_virtual_operations.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
null
null
null
libraries/protocol/include/deip/protocol/deip_virtual_operations.hpp
DEIPworld/deip-chain
d3fdcfdde179f700156156ea87522a807ec52532
[ "MIT" ]
2
2021-08-16T12:44:46.000Z
2021-12-31T17:09:45.000Z
#pragma once #include <deip/protocol/base.hpp> #include <deip/protocol/block_header.hpp> #include <deip/protocol/asset.hpp> #include <deip/protocol/eci_diff.hpp> #include <fc/utf8.hpp> namespace deip { namespace protocol { struct fill_common_tokens_withdraw_operation : public virtual_operation { fill_common_tokens_withdraw_operation() {} fill_common_tokens_withdraw_operation(const string& f, const string& t, const share_type& w, const share_type& d, const bool tr) : from_account(f) , to_account(t) , withdrawn(w) , deposited(d) , transfer(tr) { } account_name_type from_account; account_name_type to_account; share_type withdrawn; share_type deposited; bool transfer; }; struct shutdown_witness_operation : public virtual_operation { shutdown_witness_operation() {} shutdown_witness_operation(const string& o) : owner(o) { } account_name_type owner; }; struct hardfork_operation : public virtual_operation { hardfork_operation() {} hardfork_operation(uint32_t hf_id) : hardfork_id(hf_id) { } uint32_t hardfork_id = 0; }; struct producer_reward_operation : public virtual_operation { producer_reward_operation() {} producer_reward_operation(const string& p, const share_type c) : producer(p) , common_tokens_amount(c) { } account_name_type producer; share_type common_tokens_amount; }; struct token_sale_contribution_to_history_operation : public virtual_operation { token_sale_contribution_to_history_operation() {} token_sale_contribution_to_history_operation(const int64_t& research_id, const external_id_type& research_external_id, const int64_t& research_token_sale_id, const external_id_type& research_token_sale_external_id, const string& contributor, const asset& amount) : research_id(research_id) , research_external_id(research_external_id) , research_token_sale_id(research_token_sale_id) , research_token_sale_external_id(research_token_sale_external_id) , contributor(contributor) , amount(amount) { } int64_t research_id; external_id_type research_external_id; int64_t research_token_sale_id; external_id_type research_token_sale_external_id; account_name_type contributor; asset amount; }; struct research_content_reference_history_operation : public virtual_operation { research_content_reference_history_operation() {} research_content_reference_history_operation(const int64_t& research_content_id, const external_id_type& research_content_external_id, const int64_t& research_id, const external_id_type& research_external_id, const std::string& content, const int64_t& research_content_reference_id, const external_id_type& research_content_reference_external_id, const int64_t& research_reference_id, const external_id_type& research_reference_external_id, const std::string& content_reference) : research_content_id(research_content_id) , research_content_external_id(research_content_external_id) , research_id(research_id) , research_external_id(research_external_id) , content(content) , research_content_reference_id(research_content_reference_id) , research_content_reference_external_id(research_content_reference_external_id) , research_reference_id(research_reference_id) , research_reference_external_id(research_reference_external_id) , content_reference(content_reference) { } int64_t research_content_id; external_id_type research_content_external_id; int64_t research_id; external_id_type research_external_id; std::string content; int64_t research_content_reference_id; external_id_type research_content_reference_external_id; int64_t research_reference_id; external_id_type research_reference_external_id; std::string content_reference; }; struct research_content_eci_history_operation : public virtual_operation { research_content_eci_history_operation() {} research_content_eci_history_operation(const int64_t& research_content_id, const int64_t& discipline_id, const eci_diff& diff) : research_content_id(research_content_id) , discipline_id(discipline_id) , diff(diff) { } int64_t research_content_id; int64_t discipline_id; eci_diff diff; }; struct research_eci_history_operation : public virtual_operation { research_eci_history_operation() {} research_eci_history_operation(const int64_t& research_id, const int64_t& discipline_id, const eci_diff& diff) : research_id(research_id) , discipline_id(discipline_id) , diff(diff) { } int64_t research_id; int64_t discipline_id; eci_diff diff; }; struct account_eci_history_operation : public virtual_operation { account_eci_history_operation() {} account_eci_history_operation(const account_name_type& account, const int64_t& discipline_id, const uint16_t& recipient_type, const eci_diff& diff) : account(account) , discipline_id(discipline_id) , recipient_type(recipient_type) , diff(diff) { } account_name_type account; int64_t discipline_id; uint16_t recipient_type; eci_diff diff; }; struct disciplines_eci_history_operation : public virtual_operation { disciplines_eci_history_operation(){} disciplines_eci_history_operation(const flat_map<int64_t, vector<eci_diff>>& contributions_map, const fc::time_point_sec& timestamp) : timestamp(timestamp) { for (const auto& pair : contributions_map) { contributions.insert(pair); } } flat_map<int64_t, vector<eci_diff>> contributions; fc::time_point_sec timestamp; }; struct account_revenue_income_history_operation : public virtual_operation { account_revenue_income_history_operation() {} account_revenue_income_history_operation(const account_name_type& account, const asset& security_token, const asset& revenue, const fc::time_point_sec& timestamp) : account(account) , security_token(security_token) , revenue(revenue) , timestamp(timestamp) { } account_name_type account; asset security_token; asset revenue; fc::time_point_sec timestamp; }; struct proposal_status_changed_operation : public virtual_operation { proposal_status_changed_operation() { } proposal_status_changed_operation(const external_id_type& external_id, const uint8_t& status) : external_id(external_id) , status(status) { } external_id_type external_id; uint8_t status; }; struct create_genesis_proposal_operation : public virtual_operation { create_genesis_proposal_operation() { } create_genesis_proposal_operation(const external_id_type& external_id, const account_name_type& proposer, const string& serialized_proposed_transaction, const time_point_sec& expiration_time, const time_point_sec& created_at, const optional<time_point_sec>& review_period, const flat_set<account_name_type>& available_active_approvals, const flat_set<account_name_type>& available_owner_approvals, const flat_set<public_key_type>& available_key_approvals) : external_id(external_id) , proposer(proposer) , serialized_proposed_transaction(serialized_proposed_transaction) , expiration_time(expiration_time) , created_at(created_at) { if (review_period.valid()) { review_period_time = *review_period; } for (const auto& approver : available_active_approvals) { active_approvals.insert(approver); } for (const auto& approver : available_owner_approvals) { owner_approvals.insert(approver); } for (const auto& approver : key_approvals) { key_approvals.insert(approver); } } external_id_type external_id; uint8_t status; account_name_type proposer; string serialized_proposed_transaction; time_point_sec expiration_time; time_point_sec created_at; optional<time_point_sec> review_period_time; flat_set<account_name_type> active_approvals; flat_set<account_name_type> owner_approvals; flat_set<public_key_type> key_approvals; }; struct create_genesis_account_operation : public virtual_operation { create_genesis_account_operation() {} create_genesis_account_operation(const account_name_type& account) : account(account) { } account_name_type account; }; } } // deip::protocol FC_REFLECT(deip::protocol::fill_common_tokens_withdraw_operation, (from_account)(to_account)(withdrawn)(deposited)(transfer)) FC_REFLECT(deip::protocol::shutdown_witness_operation, (owner)) FC_REFLECT(deip::protocol::hardfork_operation, (hardfork_id)) FC_REFLECT(deip::protocol::producer_reward_operation, (producer)(common_tokens_amount)) FC_REFLECT(deip::protocol::token_sale_contribution_to_history_operation, (research_id)(research_external_id)(research_token_sale_id)(research_token_sale_external_id)(contributor)(amount)) FC_REFLECT(deip::protocol::research_content_reference_history_operation, (research_content_id)(research_content_external_id)(research_id)(research_external_id)(content)(research_content_reference_id)(research_content_reference_external_id)(research_reference_id)(research_reference_external_id)(content_reference)) FC_REFLECT(deip::protocol::research_content_eci_history_operation, (research_content_id)(discipline_id)(diff)) FC_REFLECT(deip::protocol::research_eci_history_operation, (research_id)(discipline_id)(diff)) FC_REFLECT(deip::protocol::account_eci_history_operation, (account)(discipline_id)(recipient_type)(diff)) FC_REFLECT(deip::protocol::disciplines_eci_history_operation, (contributions)(timestamp)) FC_REFLECT(deip::protocol::account_revenue_income_history_operation, (account)(security_token)(revenue)(timestamp)) FC_REFLECT(deip::protocol::proposal_status_changed_operation, (external_id)(status)) FC_REFLECT(deip::protocol::create_genesis_proposal_operation, (external_id)(proposer)(serialized_proposed_transaction)(expiration_time)(created_at)(review_period_time)(active_approvals)(owner_approvals)(key_approvals)) FC_REFLECT(deip::protocol::create_genesis_account_operation, (account))
37.377358
314
0.673481
DEIPworld
7c7333192b8c9fb7bf453a63ea77769f1c00283e
128
hpp
C++
Blob_Lib/Include/glm/ext/matrix_uint2x4.hpp
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
Blob_Lib/Include/glm/ext/matrix_uint2x4.hpp
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
Blob_Lib/Include/glm/ext/matrix_uint2x4.hpp
antholuo/Blob_Traffic
5d6acf88044e9abc63c0ff356714179eaa4b75bf
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:dc05769835c1662878111c8555c4d59f668a9a3a8ca31f2cb035da4016f33b2e size 737
32
75
0.882813
antholuo
7c75c42e66b58e3633067cab6b3d32cf091eb355
1,230
hpp
C++
Engine/Src/Runtime/Core/Public/Core/Pimpl.hpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
Engine/Src/Runtime/Core/Public/Core/Pimpl.hpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
Engine/Src/Runtime/Core/Public/Core/Pimpl.hpp
Septus10/Fade-Engine
285a2a1cf14a4e9c3eb8f6d30785d1239cef10b6
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <Core/CoreApi.hpp> #include <Core/Containers/UniquePointer.hpp> #define FADE_MAKE_PIMPL \ private: \ class CImpl; \ __pragma(warning(push)) \ __pragma(warning(disable : 4251)) \ TPimpl<CImpl> m_Impl; \ __pragma(warning(pop)) #define FADE_INIT_PIMPL(ClassName) \ m_Impl(MakeUnique<ClassName::CImpl>()) /* Brief: * Creates pimpl object using a unique_ptr */ template <typename T> class TPimpl { private: Fade::TUniquePtr<T> m_Ptr; public: template <typename... Args> TPimpl(Args&&... args) : m_Ptr(std::forward<Args>(args)...) { } // copy ctor & copy assignment TPimpl(const TPimpl& rhs) = default; TPimpl& operator=(const TPimpl& rhs) = default; // move ctor & move assignment TPimpl(TPimpl&& rhs) = default; TPimpl& operator=(TPimpl&& rhs) = default; // pointer operator T& operator*() { return *m_Ptr; } const T& operator*() const { return *m_Ptr; } // arrow operator T* operator->() { return m_Ptr.Get(); } const T* operator->() const { return m_Ptr.Get(); } // get() function T* get() { return m_Ptr.Get(); } const T* get() const { return m_Ptr.Get(); } };
23.207547
52
0.621951
Septus10
7c7b086b8a08cf99e589f533582f1c4b2692f5d6
11,108
hpp
C++
source/zisc/core/zisc/string/json_value_parser-inl.hpp
byzin/Zisc
c74f50c51f82c847f39a603607d73179004436bb
[ "MIT" ]
2
2017-10-18T13:24:11.000Z
2018-05-15T00:40:52.000Z
source/zisc/core/zisc/string/json_value_parser-inl.hpp
byzin/Zisc
c74f50c51f82c847f39a603607d73179004436bb
[ "MIT" ]
9
2016-09-05T11:07:03.000Z
2019-07-05T15:31:04.000Z
source/zisc/core/zisc/string/json_value_parser-inl.hpp
byzin/Zisc
c74f50c51f82c847f39a603607d73179004436bb
[ "MIT" ]
null
null
null
/*! \file json_value_parser-inl.hpp \author Sho Ikeda \brief No brief description \details No detailed description. \copyright Copyright (c) 2015-2021 Sho Ikeda This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ #ifndef ZISC_JSON_VALUE_PARSER_INL_HPP #define ZISC_JSON_VALUE_PARSER_INL_HPP #include "json_value_parser.hpp" // Standard C++ library #include <cstddef> #include <cstdlib> #include <regex> #include <string_view> #include <type_traits> #include <utility> // Zisc #include "constant_string.hpp" #include "zisc/concepts.hpp" #include "zisc/utility.hpp" #include "zisc/zisc_config.hpp" namespace zisc { /*! \details No detailed description \return No description */ inline constexpr auto JsonValueParser::truePattern() noexcept { auto pattern = toString(R"(true)"); return pattern; } /*! \details No detailed description \return No description */ inline constexpr auto JsonValueParser::falsePattern() noexcept { auto pattern = toString(R"(false)"); return pattern; } /*! \details No detailed description \return No description */ inline constexpr auto JsonValueParser::booleanPattern() noexcept { auto pattern = truePattern() + R"(|)" + falsePattern(); return pattern; } /*! \details No detailed description \return No description */ inline constexpr auto JsonValueParser::integerPattern() noexcept { auto pattern = toString(R"(-?(?:[1-9][0-9]*|0))"); return pattern; } /*! \details No detailed description \return No description */ inline constexpr auto JsonValueParser::floatPattern() noexcept { auto pattern = integerPattern() + R"((?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)"; return pattern; } /*! \details No detailed description \return No description */ inline constexpr auto JsonValueParser::stringPattern() noexcept { auto character = toString(R"([^"\\[:cntrl:]])"); auto escaped = toString(R"(\\["\\bfnrt])"); auto pattern = R"("(?:)" + character + R"(|)" + escaped + R"()*")"; return pattern; } /*! \details No detailed description */ inline JsonValueParser::JsonValueParser() noexcept : int_pattern_{integerPattern().toCStr(), regexInsOptions()}, float_pattern_{floatPattern().toCStr(), regexInsOptions()}, string_pattern_{stringPattern().toCStr(), regexInsOptions()} { } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline std::size_t JsonValueParser::getCxxStringSize(const std::string_view json_value) noexcept { const std::size_t size = toCxxStringImpl(json_value, nullptr); return size; } /*! \details No detailed description \return No description */ inline constexpr std::regex::flag_type JsonValueParser::regexInsOptions() noexcept { constexpr std::regex::flag_type flag = std::regex_constants::nosubs | std::regex_constants::optimize | std::regex_constants::ECMAScript; return flag; } /*! \details No detailed description \return No description */ inline constexpr std::regex::flag_type JsonValueParser::regexTempOptions() noexcept { constexpr std::regex::flag_type flag = std::regex_constants::nosubs | std::regex_constants::ECMAScript; return flag; } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::toCxxBool(const std::string_view json_value) noexcept { constexpr auto true_value = truePattern(); const bool result = true_value == json_value; return result; } /*! \details No detailed description \tparam Float No description. \param [in] json_value No description. \return No description */ template <FloatingPoint Float> inline Float JsonValueParser::toCxxFloat(const std::string_view json_value) noexcept { const Float result = toCxxFloatImpl<Float>(json_value); return result; } /*! \details No detailed description \tparam Int No description. \param [in] json_value No description. \return No description */ template <Integer Int> inline Int JsonValueParser::toCxxInteger(const std::string_view json_value) noexcept { const Int result = toCxxIntegerImpl<Int>(json_value); return result; } /*! \details No detailed description \param [in] json_value No description. \param [out] value No description. */ inline void JsonValueParser::toCxxString(const std::string_view json_value, char* value) noexcept { toCxxStringImpl(json_value, value); } // For temporary use /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isBoolValue(const std::string_view json_value) noexcept { constexpr auto true_value = truePattern(); constexpr auto false_value = falsePattern(); const bool result = (true_value == json_value) || (false_value == json_value); return result; } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isFloatValue(const std::string_view json_value) noexcept { const std::regex float_pattern{floatPattern().toCStr(), regexTempOptions()}; const bool result = isValueOf(float_pattern, json_value); return result; } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isIntegerValue(const std::string_view json_value) noexcept { const std::regex int_pattern{integerPattern().toCStr(), regexTempOptions()}; const bool result = isValueOf(int_pattern, json_value); return result; } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isStringValue(const std::string_view json_value) noexcept { const std::regex string_pattern{stringPattern().toCStr(), regexTempOptions()}; const bool result = isValueOf(string_pattern, json_value); return result; } // For instance /*! \details No detailed description \return No description */ inline const std::regex& JsonValueParser::floatRegex() const noexcept { return float_pattern_; } /*! \details No detailed description \return No description */ inline const std::regex& JsonValueParser::integerRegex() const noexcept { return int_pattern_; } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isBool(const std::string_view json_value) const noexcept { const bool result = isBoolValue(json_value); return result; } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isFloat(const std::string_view json_value) const noexcept { const bool result = isValueOf(floatRegex(), json_value); return result; } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isInteger(const std::string_view json_value) const noexcept { const bool result = isValueOf(integerRegex(), json_value); return result; } /*! \details No detailed description \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isString(const std::string_view json_value) const noexcept { const bool result = isValueOf(stringRegex(), json_value); return result; } /*! \details No detailed description \return No description */ inline const std::regex& JsonValueParser::stringRegex() const noexcept { return string_pattern_; } /*! \details No detailed description \param [in] c No description. \return No description */ inline char JsonValueParser::getEscapedCharacter(const char c) noexcept { char result = '\0'; switch (c) { case '\"': result = '\"'; break; case '\\': result = '\\'; break; case 'b': result = '\b'; break; case 'f': result = '\f'; break; case 'n': result = '\n'; break; case 'r': result = '\r'; break; case 't': result = '\t'; break; default: break; } return result; } /*! \details No detailed description \param [in] pattern No description. \param [in] json_value No description. \return No description */ inline bool JsonValueParser::isValueOf(const std::regex& pattern, const std::string_view json_value) noexcept { const bool result = std::regex_match(json_value.begin(), json_value.end(), pattern); return result; } /*! \details No detailed description \tparam Float No description. \param [in] json_value No description. \return No description */ template <FloatingPoint Float> inline Float JsonValueParser::toCxxFloatImpl(const std::string_view json_value) noexcept { using FType = std::remove_cv_t<Float>; Float result; if constexpr (std::is_same_v<float, FType>) result = std::strtof(json_value.data(), nullptr); else if constexpr (std::is_same_v<double, FType>) result = std::strtod(json_value.data(), nullptr); else if constexpr (std::is_same_v<long double, FType>) result = std::strtold(json_value.data(), nullptr); return result; } /*! \details No detailed description \tparam Int No description. \param [in] json_value No description. \return No description */ template <SignedInteger Int> inline Int JsonValueParser::toCxxIntegerImpl(const std::string_view json_value) noexcept { Int result = 0; if constexpr (Integer64<Int>) result = std::strtoll(json_value.data(), nullptr, 10); else result = cast<Int>(std::strtol(json_value.data(), nullptr, 10)); return result; } /*! \details No detailed description \tparam Int No description. \param [in] json_value No description. \return No description */ template <UnsignedInteger Int> inline Int JsonValueParser::toCxxIntegerImpl(const std::string_view json_value) noexcept { Int result = 0; if constexpr (Integer64<Int>) result = std::strtoull(json_value.data(), nullptr, 10); else result = cast<Int>(std::strtoul(json_value.data(), nullptr, 10)); return result; } /*! \details No detailed description \param [in] json_value No description. \param [out] value No description. \return No description */ inline std::size_t JsonValueParser::toCxxStringImpl(std::string_view json_value, char* value) noexcept { // Remove prefix and suffix '"' json_value.remove_prefix(1); json_value.remove_suffix(1); std::size_t size = 0; for (auto i = json_value.begin(); i != json_value.end(); ++i) { char c = *i; if (c == '\\') { ++i; c = getEscapedCharacter(*i); } if (value) value[size] = c; ++size; } return size; } } // namespace zisc #endif // _Z_JSON_VALUE_PARSER_INL_HPP__
22.039683
89
0.692384
byzin
75acb2eb9cd3d25bd94aacd1f8ba7c3e27ba8fda
7,937
cpp
C++
lemon-based-parser/lemon-9-final/Value.cpp
PS-Group/compiler-theory-samples
c916af50eb42020024257ecd17f9be1580db7bf0
[ "MIT" ]
null
null
null
lemon-based-parser/lemon-9-final/Value.cpp
PS-Group/compiler-theory-samples
c916af50eb42020024257ecd17f9be1580db7bf0
[ "MIT" ]
null
null
null
lemon-based-parser/lemon-9-final/Value.cpp
PS-Group/compiler-theory-samples
c916af50eb42020024257ecd17f9be1580db7bf0
[ "MIT" ]
null
null
null
#include "Value.h" #include <stdexcept> #include <boost/format.hpp> #include <cmath> namespace { bool FuzzyEquals(double left, double right) { return std::fabs(left - right) >= std::numeric_limits<double>::epsilon(); } std::string ToPrettyString(double value) { std::string result = std::to_string(value); // Преобразуем 2.00000 в 2. while (!result.empty() && result.back() == '0') { result.pop_back(); } if (!result.empty() && result.back() == '.') { result.pop_back(); } return result; } std::string ToPrettyString(bool value) { return value ? "true" : "false"; } // Конвертирует значение в Boolean (C++ bool). struct BooleanConverter : boost::static_visitor<bool> { bool operator ()(double const& value) const { return FuzzyEquals(value, 0); } bool operator ()(bool const& value) const { return value; } bool operator ()(std::string const& value) const { return !value.empty(); } bool operator ()(std::exception_ptr const&) { return false; } }; // Конвертирует значение в String (C++ std::string). struct StringConverter : boost::static_visitor<std::string> { std::string operator ()(double const& value) const { return ToPrettyString(value); } std::string operator ()(bool const& value) const { return ToPrettyString(value); } std::string operator ()(std::string const& value) const { return value; } std::string operator ()(std::exception_ptr const& value) { std::rethrow_exception(value); } }; struct TypeNameVisitor : boost::static_visitor<std::string> { std::string operator ()(double const&) const { return "Number"; } std::string operator ()(bool const&) const { return "Boolean"; } std::string operator ()(std::string const&) const { return "String"; } std::string operator ()(std::exception_ptr const& value) { m_exception = value; return "Error"; } std::exception_ptr m_exception; }; } // anonymous namespace. CValue CValue::FromError(const std::exception_ptr &value) { return Value(value); } CValue CValue::FromErrorMessage(const std::string &message) { return CValue::FromError(std::make_exception_ptr(std::runtime_error(message))); } CValue CValue::FromDouble(double value) { return Value(value); } CValue CValue::FromBoolean(bool value) { return Value(value); } CValue CValue::FromString(const std::string &value) { return Value(value); } CValue::operator bool() const { return ConvertToBool(); } std::string CValue::ToString() const { return TryConvertToString(); } void CValue::RethrowIfException() const { if (m_value.type() == typeid(std::exception_ptr)) { std::rethrow_exception(boost::get<std::exception_ptr>(m_value)); } } bool CValue::AsBool() const { return boost::get<bool>(m_value); } const std::string &CValue::AsString() const { return boost::get<std::string>(m_value); } double CValue::AsDouble() const { return boost::get<double>(m_value); } CValue CValue::operator +() const { if (m_value.type() == typeid(double)) { return *this; } return GenerateError(*this, "+"); } CValue CValue::operator -() const { if (m_value.type() == typeid(double)) { return Value(-AsDouble()); } return GenerateError(*this, "-"); } CValue CValue::operator !() const { if (m_value.type() == typeid(bool)) { return Value(!AsBool()); } return GenerateError(*this, "!"); } CValue CValue::operator <(const CValue &other) const { if (AreBothValues<double>(*this, other)) { return Value(AsDouble() < other.AsDouble()); } if (AreBothValues<std::string>(*this, other)) { return Value(AsString() < other.AsString()); } return GenerateError(*this, other, "<"); } CValue CValue::operator ==(const CValue &other) const { if (AreBothValues<double>(*this, other)) { return Value(FuzzyEquals(AsDouble(), other.AsDouble())); } if (AreBothValues<std::string>(*this, other)) { return Value(AsString() == other.AsString()); } if (AreBothValues<bool>(*this, other)) { return Value(AsBool() == other.AsBool()); } return GenerateError(*this, other, "=="); } CValue CValue::operator &&(const CValue &other) const { if (AreBothValues<bool>(*this, other)) { return Value(AsBool() && other.AsBool()); } return GenerateError(*this, other, "&&"); } CValue CValue::operator ||(const CValue &other) const { if (AreBothValues<bool>(*this, other)) { return Value(AsBool() || other.AsBool()); } return GenerateError(*this, other, "||"); } CValue CValue::operator +(const CValue &other) const { const auto &leftType = m_value.type(); const auto &rightType = other.m_value.type(); if (leftType == typeid(double)) { if (rightType == typeid(double)) { return Value(AsDouble() + other.AsDouble()); } if (rightType == typeid(std::string)) { return Value(::ToPrettyString(AsDouble()) + other.AsString()); } } if (leftType == typeid(std::string)) { if (rightType == typeid(double)) { return Value(AsString() + ::ToPrettyString(other.AsDouble())); } if (rightType == typeid(std::string)) { return Value(AsString() + other.AsString()); } } return GenerateError(*this, other, "+"); } CValue CValue::operator -(const CValue &other) const { if (AreBothValues<double>(*this, other)) { return Value(AsDouble() - other.AsDouble()); } return GenerateError(*this, other, "-"); } CValue CValue::operator *(const CValue &other) const { if (AreBothValues<double>(*this, other)) { return Value(AsDouble() * other.AsDouble()); } return GenerateError(*this, other, "*"); } CValue CValue::operator /(const CValue &other) const { if (AreBothValues<double>(*this, other)) { return Value(AsDouble() / other.AsDouble()); } return GenerateError(*this, other, "/"); } CValue CValue::operator %(const CValue &other) const { if (AreBothValues<double>(*this, other)) { return Value(fmod(AsDouble(), other.AsDouble())); } return GenerateError(*this, other, "%"); } template<class TType> bool CValue::AreBothValues(const CValue &left, const CValue &right) { return (left.m_value.type() == typeid(TType)) && (right.m_value.type() == typeid(TType)); } CValue CValue::GenerateError(const CValue &value, const char *description) { TypeNameVisitor visitor; std::string valueType = value.m_value.apply_visitor(visitor); // Прокидываем информацию об ошибке дальше. if (visitor.m_exception) { return CValue::FromError(visitor.m_exception); } boost::format formatter("No such unary operation: %1%%2%"); formatter % description % valueType; return CValue::FromErrorMessage(boost::str(formatter)); } CValue CValue::GenerateError(const CValue &left, const CValue &right, const char *description) { TypeNameVisitor visitor; std::string leftType = left.m_value.apply_visitor(visitor); std::string rightType = right.m_value.apply_visitor(visitor); // Прокидываем информацию об ошибке дальше. if (visitor.m_exception) { return CValue::FromError(visitor.m_exception); } boost::format formatter("No such binary operation: %1% %2% %3%"); formatter % leftType % description % rightType; return CValue::FromErrorMessage(boost::str(formatter)); } CValue::CValue(const CValue::Value &value) : m_value(value) { } std::string CValue::TryConvertToString() const { StringConverter converter; std::string value = m_value.apply_visitor(converter); return value; } bool CValue::ConvertToBool() const { BooleanConverter converter; return m_value.apply_visitor(converter); }
24.649068
101
0.63815
PS-Group
75b5214b40cee70531bb1c2b785b7721472ba137
4,100
cpp
C++
src/TotalGeneralizedVariation.cpp
DanonOfficial/TGVDenoising
20446d9c89d75cf43056f43ed42f37965b4e7b6e
[ "MIT" ]
8
2019-04-06T06:13:53.000Z
2021-04-30T09:49:18.000Z
src/TotalGeneralizedVariation.cpp
DanonOfficial/TGVDenoising
20446d9c89d75cf43056f43ed42f37965b4e7b6e
[ "MIT" ]
1
2021-06-22T15:26:13.000Z
2021-06-23T05:45:21.000Z
src/TotalGeneralizedVariation.cpp
DanonOfficial/TGVDenoising
20446d9c89d75cf43056f43ed42f37965b4e7b6e
[ "MIT" ]
2
2020-07-13T09:05:51.000Z
2021-02-01T04:15:58.000Z
// // Created by roundedglint585 on 3/11/19. // #include "TotalGeneralizedVariation.hpp" TotalGeneralizedVariation::TotalGeneralizedVariation(const std::vector<TotalGeneralizedVariation::Image> &images) : m_images(images), m_result(m_images[0]), m_width(m_result[0].size()), m_height(m_result.size()) { init(); initWs(); initStacked(); calculateHist(); } TotalGeneralizedVariation::TotalGeneralizedVariation(std::vector<TotalGeneralizedVariation::Image> &&images) : m_images( std::move(images)), m_result(m_images[0]), m_width(m_result[0].size()), m_height(m_result.size()) { init(); initWs(); initStacked(); calculateHist(); } void TotalGeneralizedVariation::init() { v = mathRoutine::calculateGradient(m_result); p = mathRoutine::calculateGradient(m_result); q = mathRoutine::calculateEpsilon(v); } void TotalGeneralizedVariation::initWs() { Ws.resize(m_images.size()); for (auto &ws: Ws) { ws.resize(m_height); for (auto &i : ws) { i = std::vector<float>(m_width, 0.0f); } } } void TotalGeneralizedVariation::initStacked() { stacked = std::vector(m_height, std::vector<std::vector<float>>(m_width, std::vector<float>(Ws.size() + m_images.size(), 0))); } void TotalGeneralizedVariation::calculateHist() { for (size_t histNum = 0; histNum < Ws.size(); histNum++) { for (auto &image: m_images) { for (size_t i = 0; i < m_height; i++) { for (size_t j = 0; j < m_width; j++) { if (m_images[histNum][i][j] > image[i][j]) { Ws[histNum][i][j] += 1.f; } else { if (m_images[histNum][i][j] < image[i][j]) Ws[histNum][i][j] -= 1.f; } } } } } } TotalGeneralizedVariation::Image TotalGeneralizedVariation::prox(const TotalGeneralizedVariation::Image &image, float tau, float lambda_data) { Image result = Image(m_height, std::vector<float>(m_width, 0)); //need to swap dimensions to calculate median for (size_t i = 0; i < m_height; i++) { for (size_t j = 0; j < m_width; j++) { for (size_t k = 0; k < m_images.size(); k++) { stacked[i][j][k] = m_images[k][i][j]; } for (size_t k = 0; k < Ws.size(); k++) { stacked[i][j][m_images.size() + k] = image[i][j] + tau * lambda_data * Ws[k][i][j]; } } } for (size_t i = 0; i < m_height; i++) { for (size_t j = 0; j < m_width; j++) { std::stable_sort(stacked[i][j].begin(), stacked[i][j].end()); if (stacked[i][j].size() % 2 == 1) { result[i][j] = stacked[i][j][stacked[i][j].size() / 2 + 1]; } else { result[i][j] = (stacked[i][j][stacked[i][j].size() / 2] + stacked[i][j][stacked[i][j].size() / 2 - 1]) / 2; } } } return result; } void TotalGeneralizedVariation::iteration(float tau, float lambda_tv, float lambda_tgv, float lambda_data) { using namespace mathRoutine; float tau_u, tau_v, tau_p, tau_q; tau_u = tau; tau_v = tau; tau_p = tau; tau_q = tau; Image un = prox(m_result + (-tau_u * lambda_tv) * (mathRoutine::calculateTranspondedGradient(p)), tau_u, lambda_data); Gradient vn = v + (-lambda_tgv * tau_v) * mathRoutine::calculateTranspondedEpsilon(q) + (tau_v * lambda_tv) * p; Gradient pn = project( p + (tau_p * lambda_tv) * (mathRoutine::calculateGradient((-1) * ((-2) * un + m_result)) + ((-2) * vn + v)), lambda_tv); Epsilon qn = project(q + (-tau_q * lambda_tgv) * mathRoutine::calculateEpsilon(-2 * vn + v), lambda_tgv); m_result = std::move(un); v = std::move(vn); p = std::move(pn); q = std::move(qn); } auto TotalGeneralizedVariation::getImage() const -> Image{ return m_result; }
33.064516
120
0.54878
DanonOfficial
75b5a22f172625f6a8c744363d6f830d8f9313f2
2,254
hpp
C++
include/codegen/include/Zenject/AddToCurrentGameObjectComponentProvider_--c__DisplayClass15_0.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Zenject/AddToCurrentGameObjectComponentProvider_--c__DisplayClass15_0.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Zenject/AddToCurrentGameObjectComponentProvider_--c__DisplayClass15_0.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:45 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" // Including type: Zenject.AddToCurrentGameObjectComponentProvider #include "Zenject/AddToCurrentGameObjectComponentProvider.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; } // Forward declaring namespace: Zenject namespace Zenject { // Forward declaring type: InjectContext class InjectContext; } // Completed forward declares // Type namespace: Zenject namespace Zenject { // Autogenerated type: Zenject.AddToCurrentGameObjectComponentProvider/<>c__DisplayClass15_0 class AddToCurrentGameObjectComponentProvider::$$c__DisplayClass15_0 : public ::Il2CppObject { public: // public Zenject.AddToCurrentGameObjectComponentProvider <>4__this // Offset: 0x10 Zenject::AddToCurrentGameObjectComponentProvider* $$4__this; // public System.Collections.Generic.List`1<Zenject.TypeValuePair> args // Offset: 0x18 System::Collections::Generic::List_1<Zenject::TypeValuePair>* args; // public System.Object instance // Offset: 0x20 ::Il2CppObject* instance; // public Zenject.InjectContext context // Offset: 0x28 Zenject::InjectContext* context; // System.Void <GetAllInstancesWithInjectSplit>b__0() // Offset: 0xD4F730 void $GetAllInstancesWithInjectSplit$b__0(); // public System.Void .ctor() // Offset: 0xD4F728 // Implemented from: System.Object // Base method: System.Void Object::.ctor() static AddToCurrentGameObjectComponentProvider::$$c__DisplayClass15_0* New_ctor(); }; // Zenject.AddToCurrentGameObjectComponentProvider/<>c__DisplayClass15_0 } DEFINE_IL2CPP_ARG_TYPE(Zenject::AddToCurrentGameObjectComponentProvider::$$c__DisplayClass15_0*, "Zenject", "AddToCurrentGameObjectComponentProvider/<>c__DisplayClass15_0"); #pragma pack(pop)
40.25
173
0.741349
Futuremappermydud
75b87972b857fbd84c695831f982b272ada18fa2
965
hpp
C++
common/include/bib/OrnsteinUhlenbeckNoise.hpp
matthieu637/ddrl
a454d09a3ac9be5db960ff180b3d075c2f9e4a70
[ "MIT" ]
27
2017-11-27T09:32:41.000Z
2021-03-02T13:50:23.000Z
common/include/bib/OrnsteinUhlenbeckNoise.hpp
matthieu637/ddrl
a454d09a3ac9be5db960ff180b3d075c2f9e4a70
[ "MIT" ]
10
2018-10-09T14:39:14.000Z
2020-11-10T15:01:00.000Z
common/include/bib/OrnsteinUhlenbeckNoise.hpp
matthieu637/ddrl
a454d09a3ac9be5db960ff180b3d075c2f9e4a70
[ "MIT" ]
3
2019-05-16T09:14:15.000Z
2019-08-15T14:35:40.000Z
#ifndef ORNSTEINUHLENBECK_HPP #define ORNSTEINUHLENBECK_HPP #include <vector> namespace bib { template<typename Real> class OrnsteinUhlenbeckNoise { public: OrnsteinUhlenbeckNoise(uint action_size, Real sigma_=.2, Real theta_=.15, Real dt_=0.01) : x_t (action_size, 0) { sigma = sigma_; theta = theta_; dt = dt_; } void reset() { for(uint i=0;i<x_t.size();i++) x_t[i] = 0; } void step(std::vector<Real>& mu) { std::normal_distribution<Real> dist(0, 1.); for (uint i = 0; i < mu.size(); i++) { Real normal = dist(*bib::Seed::random_engine()); Real x_tplus = x_t[i] - theta * dt * x_t[i] + sigma * sqrt(dt) * normal; mu[i] += x_tplus; if(mu[i] < (Real) -1.) mu[i] = (Real) -1.; else if (mu[i] > (Real) 1.) mu[i] = (Real) 1.; x_t[i] = x_tplus; } } private: std::vector<Real> x_t; Real sigma; Real theta; Real dt; }; } #endif
19.693878
115
0.557513
matthieu637
75b90ec3f22c09aa37cd74b9beb9a071c2601b66
1,959
cpp
C++
Source/Driver/API/SQLSetConnectOption.cpp
yichenghuang/bigobject-odbc
c6d947ea3d18d79684adfbac1c492282a075d48d
[ "MIT" ]
null
null
null
Source/Driver/API/SQLSetConnectOption.cpp
yichenghuang/bigobject-odbc
c6d947ea3d18d79684adfbac1c492282a075d48d
[ "MIT" ]
null
null
null
Source/Driver/API/SQLSetConnectOption.cpp
yichenghuang/bigobject-odbc
c6d947ea3d18d79684adfbac1c492282a075d48d
[ "MIT" ]
null
null
null
/* * ---------------------------------------------------------------------------- * Copyright (c) 2014-2015 BigObject Inc. * All Rights Reserved. * * Use of, copying, modifications to, and distribution of this software * and its documentation without BigObject's written permission can * result in the violation of U.S., Taiwan and China Copyright and Patent laws. * Violators will be prosecuted to the highest extent of the applicable laws. * * BIGOBJECT MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. * ---------------------------------------------------------------------------- */ #include "Driver.hpp" /* https://msdn.microsoft.com/en-us/library/ms713564%28v=vs.85%29.aspx https://msdn.microsoft.com/en-us/library/ms714008%28v=vs.85%29.aspx WE DON'T EXPORT THIS API. */ SQLRETURN SQL_API SQLSetConnectOption(SQLHDBC hDrvDbc, UWORD nOption, SQLULEN vParam) { HDRVDBC hDbc = (HDRVDBC)hDrvDbc; LOG_DEBUG_F_FUNC( TEXT("%s: hDrvDbc = 0x%08lX, nOption = %d, vParam = %d"), LOG_FUNCTION_NAME, (long)hDrvDbc, nOption, vParam); API_HOOK_ENTRY(SQLSetConnectOption, hDrvDbc, nOption, vParam); /* SANITY CHECKS */ if(hDbc == SQL_NULL_HDBC) return SQL_INVALID_HANDLE; switch(nOption) { case SQL_TRANSLATE_DLL: case SQL_TRANSLATE_OPTION: /* case SQL_CONNECT_OPT_DRVR_START: */ case SQL_ODBC_CURSORS: case SQL_OPT_TRACE: switch(vParam) { case SQL_OPT_TRACE_ON: case SQL_OPT_TRACE_OFF: default: ; } break; case SQL_OPT_TRACEFILE: case SQL_ACCESS_MODE: case SQL_AUTOCOMMIT: default: ; } LOG_WARN_F_FUNC(TEXT("%s: This function not supported."), LOG_FUNCTION_NAME); LOG_DEBUG_F_FUNC(TEXT("%s: SQL_ERROR"), LOG_FUNCTION_NAME); return SQL_ERROR; }
27.208333
79
0.663604
yichenghuang