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
f599d9642710d3378e3cf23fd1b892b2c221f6bf
790
cc
C++
chrome/browser/ui/tabs/tab_strip_model_utils.cc
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "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/tabs/tab_strip_model_utils.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/tabs/tab_strip_model_utils.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/tabs/tab_strip_model_utils.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "components/history/core/browser/top_sites.h" #include "content/public/browser/web_contents.h" namespace chrome { void GetOpenUrls(const TabStripModel& tabs, const history::TopSites& top_sites, std::set<std::string>* urls) { for (int i = 0; i < tabs.count(); ++i) { content::WebContents* web_contents = tabs.GetWebContentsAt(i); if (web_contents) urls->insert(top_sites.GetCanonicalURLString(web_contents->GetURL())); } } } // namespace chrome
32.916667
76
0.706329
xzhan96
f59aada8dd2a16a3e0044628da6196866b8a6968
554
cpp
C++
src/noj_am/BOJ_18870.cpp
ginami0129g/my-problem-solving
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
1
2020-06-01T12:19:31.000Z
2020-06-01T12:19:31.000Z
src/noj_am/BOJ_18870.cpp
ginami0129g/my-study-history
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
23
2020-11-08T07:14:02.000Z
2021-02-11T11:16:00.000Z
src/noj_am/BOJ_18870.cpp
ginami0129g/my-problem-solving
b173b5df42354b206839711fa166fcd515c6a69c
[ "Beerware" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int n, num, cnt; vector<pair<int, int> > arr; vector<int> ans; int main(void) { cin.tie(NULL); ios_base::sync_with_stdio(false); cin >> n; for (int i = 0; i < n; ++i) { cin >> num; arr.push_back({num, i}); } sort(arr.begin(), arr.end()); ans.assign(n, 0); ans[arr[0].second] = 0; for (int i = 1; i < arr.size(); ++i) { if (arr[i - 1].first == arr[i].first) cnt++; ans[arr[i].second] = i - cnt; } for (int i = 0; i < ans.size(); ++i) { cout << ans[i] << ' '; } }
20.518519
48
0.516245
ginami0129g
f59dceeaa59eccbc4a9a0dd43b0ab7c11ef19dcc
11,421
hpp
C++
include/Nazara/Network/ENetPeer.hpp
waruqi/NazaraEngine
a64de1ffe8b0790622a0b1cae5759c96b4f86907
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
376
2015-01-09T03:14:48.000Z
2022-03-26T17:59:18.000Z
include/Nazara/Network/ENetPeer.hpp
waruqi/NazaraEngine
a64de1ffe8b0790622a0b1cae5759c96b4f86907
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
252
2015-01-21T17:34:39.000Z
2022-03-20T16:15:50.000Z
include/Nazara/Network/ENetPeer.hpp
waruqi/NazaraEngine
a64de1ffe8b0790622a0b1cae5759c96b4f86907
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
104
2015-01-18T11:03:41.000Z
2022-03-11T05:40:47.000Z
/* Copyright(c) 2002 - 2016 Lee Salzman 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. */ // Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - Network module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_ENETPEER_HPP #define NAZARA_ENETPEER_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Core/Bitset.hpp> #include <Nazara/Core/MovablePtr.hpp> #include <Nazara/Network/ENetPacket.hpp> #include <Nazara/Network/ENetProtocol.hpp> #include <Nazara/Network/IpAddress.hpp> #include <array> #include <list> #include <random> #include <vector> namespace Nz { class ENetHost; class NAZARA_NETWORK_API ENetPeer { friend ENetHost; friend struct PacketRef; public: inline ENetPeer(ENetHost* host, UInt16 peerId); ENetPeer(const ENetPeer&) = delete; ENetPeer(ENetPeer&&) = default; ~ENetPeer() = default; void Disconnect(UInt32 data); void DisconnectLater(UInt32 data); void DisconnectNow(UInt32 data); inline const IpAddress& GetAddress() const; inline UInt32 GetLastReceiveTime() const; inline UInt32 GetMtu() const; inline UInt32 GetPacketThrottleAcceleration() const; inline UInt32 GetPacketThrottleDeceleration() const; inline UInt32 GetPacketThrottleInterval() const; inline UInt16 GetPeerId() const; inline UInt32 GetRoundTripTime() const; inline ENetPeerState GetState() const; inline UInt64 GetTotalByteReceived() const; inline UInt64 GetTotalByteSent() const; inline UInt32 GetTotalPacketReceived() const; inline UInt32 GetTotalPacketLost() const; inline UInt32 GetTotalPacketSent() const; inline bool HasPendingCommands(); inline bool IsConnected() const; inline bool IsSimulationEnabled() const; void Ping(); bool Receive(ENetPacketRef* packet, UInt8* channelId); void Reset(); bool Send(UInt8 channelId, ENetPacketRef packetRef); bool Send(UInt8 channelId, ENetPacketFlags flags, NetPacket&& packet); void SimulateNetwork(double packetLossProbability, UInt16 minDelay, UInt16 maxDelay); void ThrottleConfigure(UInt32 interval, UInt32 acceleration, UInt32 deceleration); ENetPeer& operator=(const ENetPeer&) = delete; ENetPeer& operator=(ENetPeer&&) = default; private: void InitIncoming(std::size_t channelCount, const IpAddress& address, ENetProtocolConnect& incomingCommand); void InitOutgoing(std::size_t channelCount, const IpAddress& address, UInt32 connectId, UInt32 windowSize); struct Channel; struct IncomingCommmand; struct OutgoingCommand; inline void ChangeState(ENetPeerState state); bool CheckTimeouts(ENetEvent* event); void DispatchState(ENetPeerState state); void DispatchIncomingReliableCommands(Channel& channel); void DispatchIncomingUnreliableCommands(Channel& channel); bool HandleAcknowledge(const ENetProtocol* command, ENetEvent* event); bool HandleBandwidthLimit(const ENetProtocol* command); bool HandleDisconnect(const ENetProtocol* command); bool HandlePing(const ENetProtocol* command); bool HandleSendFragment(const ENetProtocol* command, UInt8** data); bool HandleSendReliable(const ENetProtocol* command, UInt8** data); bool HandleSendUnreliable(const ENetProtocol* command, UInt8** data); bool HandleSendUnreliableFragment(const ENetProtocol* command, UInt8** data); bool HandleSendUnsequenced(const ENetProtocol* command, UInt8** data); bool HandleThrottleConfigure(const ENetProtocol* command); bool HandleVerifyConnect(const ENetProtocol* command, ENetEvent* event); void OnConnect(); void OnDisconnect(); ENetProtocolCommand RemoveSentReliableCommand(UInt16 reliableSequenceNumber, UInt8 channelId); void RemoveSentUnreliableCommands(); void ResetQueues(); bool QueueAcknowledgement(ENetProtocol* command, UInt16 sentTime); IncomingCommmand* QueueIncomingCommand(const ENetProtocol& command, const void* data, std::size_t dataLength, UInt32 flags, UInt32 fragmentCount); inline void QueueOutgoingCommand(ENetProtocol& command); void QueueOutgoingCommand(ENetProtocol& command, ENetPacketRef packet, UInt32 offset, UInt16 length); void SetupOutgoingCommand(OutgoingCommand& outgoingCommand); int Throttle(UInt32 rtt); struct Acknowledgement { ENetProtocol command; UInt32 sentTime; }; struct Channel { Channel() { incomingReliableSequenceNumber = 0; incomingUnreliableSequenceNumber = 0; outgoingReliableSequenceNumber = 0; outgoingUnreliableSequenceNumber = 0; usedReliableWindows = 0; reliableWindows.fill(0); } std::array<UInt16, ENetPeer_ReliableWindows> reliableWindows; std::list<IncomingCommmand> incomingReliableCommands; std::list<IncomingCommmand> incomingUnreliableCommands; UInt16 incomingReliableSequenceNumber; UInt16 incomingUnreliableSequenceNumber; UInt16 outgoingReliableSequenceNumber; UInt16 outgoingUnreliableSequenceNumber; UInt16 usedReliableWindows; }; struct IncomingCommmand { ENetProtocol command; Bitset<> fragments; ENetPacketRef packet; UInt16 reliableSequenceNumber; UInt16 unreliableSequenceNumber; UInt32 fragmentsRemaining; }; struct OutgoingCommand { ENetProtocol command; ENetPacketRef packet; UInt16 fragmentLength; UInt16 reliableSequenceNumber; UInt16 sendAttempts; UInt16 unreliableSequenceNumber; UInt32 fragmentOffset; UInt32 roundTripTimeout; UInt32 roundTripTimeoutLimit; UInt32 sentTime; }; static constexpr std::size_t unsequencedWindow = ENetPeer_ReliableWindowSize / 32; MovablePtr<ENetHost> m_host; IpAddress m_address; //< Internet address of the peer std::array<UInt32, unsequencedWindow> m_unsequencedWindow; std::bernoulli_distribution m_packetLossProbability; std::list<IncomingCommmand> m_dispatchedCommands; std::list<OutgoingCommand> m_outgoingReliableCommands; std::list<OutgoingCommand> m_outgoingUnreliableCommands; std::list<OutgoingCommand> m_sentReliableCommands; std::list<OutgoingCommand> m_sentUnreliableCommands; std::size_t m_totalWaitingData; std::uniform_int_distribution<UInt16> m_packetDelayDistribution; std::vector<Acknowledgement> m_acknowledgements; std::vector<Channel> m_channels; ENetPeerState m_state; UInt8 m_incomingSessionID; UInt8 m_outgoingSessionID; UInt16 m_incomingPeerID; UInt16 m_incomingUnsequencedGroup; UInt16 m_outgoingPeerID; UInt16 m_outgoingReliableSequenceNumber; UInt16 m_outgoingUnsequencedGroup; UInt32 m_connectID; UInt32 m_earliestTimeout; UInt32 m_eventData; UInt32 m_highestRoundTripTimeVariance; UInt32 m_incomingBandwidth; /**< Downstream bandwidth of the client in bytes/second */ UInt32 m_incomingBandwidthThrottleEpoch; UInt32 m_incomingDataTotal; UInt32 m_lastReceiveTime; UInt32 m_lastRoundTripTime; UInt32 m_lastRoundTripTimeVariance; UInt32 m_lastSendTime; UInt32 m_lowestRoundTripTime; UInt32 m_mtu; UInt32 m_nextTimeout; UInt32 m_outgoingBandwidth; /**< Upstream bandwidth of the client in bytes/second */ UInt32 m_outgoingBandwidthThrottleEpoch; UInt32 m_outgoingDataTotal; UInt32 m_packetLoss; /**< mean packet loss of reliable packets as a ratio with respect to the constant ENET_PEER_PACKET_LOSS_SCALE */ UInt32 m_packetLossEpoch; UInt32 m_packetLossVariance; UInt32 m_packetThrottle; UInt32 m_packetThrottleAcceleration; UInt32 m_packetThrottleCounter; UInt32 m_packetThrottleDeceleration; UInt32 m_packetThrottleEpoch; UInt32 m_packetThrottleInterval; UInt32 m_packetThrottleLimit; UInt32 m_packetsLost; UInt32 m_packetsSent; UInt32 m_pingInterval; UInt32 m_reliableDataInTransit; UInt32 m_roundTripTime; /**< mean round trip time (RTT), in milliseconds, between sending a reliable packet and receiving its acknowledgment */ UInt32 m_roundTripTimeVariance; UInt32 m_timeoutLimit; UInt32 m_timeoutMaximum; UInt32 m_timeoutMinimum; UInt32 m_totalPacketReceived; UInt32 m_totalPacketLost; UInt32 m_totalPacketSent; UInt32 m_windowSize; UInt64 m_totalByteReceived; UInt64 m_totalByteSent; bool m_isSimulationEnabled; }; } #include <Nazara/Network/ENetPeer.inl> #endif // NAZARA_ENETPEER_HPP
44.788235
460
0.637685
waruqi
f59e440a647b2c2c41f5832f27f3be9cac755a8b
6,483
cpp
C++
csgo-crow/AntiCheatServer/NoCheatZ/server-plugin/Code/Systems/Testers/EyeAnglesTester.cpp
im6705/csgo_full
6c50221c5b6441ebf689e3a1cb4978510fab0b27
[ "Apache-2.0" ]
null
null
null
csgo-crow/AntiCheatServer/NoCheatZ/server-plugin/Code/Systems/Testers/EyeAnglesTester.cpp
im6705/csgo_full
6c50221c5b6441ebf689e3a1cb4978510fab0b27
[ "Apache-2.0" ]
null
null
null
csgo-crow/AntiCheatServer/NoCheatZ/server-plugin/Code/Systems/Testers/EyeAnglesTester.cpp
im6705/csgo_full
6c50221c5b6441ebf689e3a1cb4978510fab0b27
[ "Apache-2.0" ]
null
null
null
/* Copyright 2012 - Le Padellec Sylvain 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 <stdio.h> #include <cmath> #include "EyeAnglesTester.h" #include "Misc/EntityProps.h" #include "Systems/BanRequest.h" EyeAnglesTester::EyeAnglesTester(void) : BaseTesterSystem("EyeAnglesTester"), playerdata_class(), PlayerRunCommandHookListener(), UserMessageHookListener(), Singleton() { } EyeAnglesTester::~EyeAnglesTester(void) { Unload(); } void EyeAnglesTester::Init() { InitDataStruct(); } void EyeAnglesTester::Load() { for (PlayerHandler::iterator it(PlayerHandler::begin()); it != PlayerHandler::end(); ++it) { ResetPlayerDataStructByIndex(it.GetIndex()); } PlayerRunCommandHookListener::RegisterPlayerRunCommandHookListener(this, SystemPriority::EyeAnglesTester); UserMessageHookListener::RegisterUserMessageHookListener(this); } void EyeAnglesTester::Unload() { PlayerRunCommandHookListener::RemovePlayerRunCommandHookListener(this); UserMessageHookListener::RemoveUserMessageHookListener(this); } bool EyeAnglesTester::GotJob() const { // Create a filter ProcessFilter::HumanAtLeastConnected const filter_class; // Initiate the iterator at the first match in the filter PlayerHandler::iterator it(&filter_class); // Return if we have job to do or not ... return it != PlayerHandler::end(); } PlayerRunCommandRet EyeAnglesTester::RT_PlayerRunCommandCallback(PlayerHandler::iterator ph, void *const pCmd, double const &curtime) { int const *const flags(g_EntityProps.GetPropValue<int, PROP_FLAGS>(ph->GetEdict())); EyeAngleInfoT *playerData(GetPlayerDataStructByIndex(ph.GetIndex())); playerData->x.abs_value = fabs(playerData->x.value = static_cast<SourceSdk::CUserCmd_csgo *>(pCmd)->viewangles.x); playerData->y.abs_value = fabs(playerData->y.value = static_cast<SourceSdk::CUserCmd_csgo *>(pCmd)->viewangles.y); playerData->z.abs_value = fabs(playerData->z.value = static_cast<SourceSdk::CUserCmd_csgo *>(pCmd)->viewangles.z); /* FL_FROZEN (1 << 5) FL_ATCONTROLS (1 << 6) */ if ((*flags & (3 << 5)) == 0) { if (playerData->x.abs_value > 89.0f && playerData->past_x.abs_value > 89.0f && playerData->x.value != playerData->past_x.value) { ++playerData->x.detectionsCount; //drop_cmd = PlayerRunCommandRet::INERT; if (playerData->x.lastDetectionPrintTime + ANTIFLOOD_LOGGING_TIME < curtime) { playerData->x.lastDetectionPrintTime = curtime; if (playerData->x.detectionsCount > 5) { ProcessDetectionAndTakeAction<Detection_EyeAngleX::data_type>(Detection_EyeAngleX(), playerData, ph, this); } } } if (playerData->y.abs_value > 180.0f && playerData->past_y.abs_value > 180.0f && playerData->y.value != playerData->past_y.value) { ++playerData->y.detectionsCount; //drop_cmd = PlayerRunCommandRet::INERT; if (playerData->y.lastDetectionPrintTime + ANTIFLOOD_LOGGING_TIME < curtime) { playerData->y.lastDetectionPrintTime = curtime; if (playerData->y.detectionsCount > 5) { ProcessDetectionAndTakeAction<Detection_EyeAngleY::data_type>(Detection_EyeAngleY(), playerData, ph, this); } } } if (playerData->z.abs_value > 0.5f && playerData->past_z.abs_value > 0.5f && playerData->z.value != playerData->past_z.value) { if (!Helpers::IsInt(playerData->z.value)) // Don't detect ""fun"" plugins { ++playerData->z.detectionsCount; //drop_cmd = PlayerRunCommandRet::INERT; if (playerData->z.lastDetectionPrintTime + ANTIFLOOD_LOGGING_TIME < curtime) { playerData->z.lastDetectionPrintTime = curtime; if (playerData->z.detectionsCount > 5) { ProcessDetectionAndTakeAction<Detection_EyeAngleZ::data_type>(Detection_EyeAngleZ(), playerData, ph, this); } } } } } playerData->past_x = playerData->x; playerData->past_y = playerData->y; playerData->past_z = playerData->z; return PlayerRunCommandRet::CONTINUE; } bool EyeAnglesTester::RT_SendUserMessageCallback(SourceSdk::IRecipientFilter const &filter, int const message_id, google::protobuf::Message const &buffer) { DebugMessage(Helpers::format("EyeAnglesTester::RT_SendUserMessageCallback : %d, %s", message_id, buffer.DebugString().c_str())); return false; } bool EyeAnglesTester::RT_UserMessageBeginCallback(SourceSdk::IRecipientFilter const *const filter, int const message_id) { return false; } void EyeAnglesTester::RT_MessageEndCallback(SourceSdk::IRecipientFilter const *const filter, int const message_id, SourceSdk::bf_write *buffer) { } EyeAnglesTester g_EyeAnglesTester; basic_string Detection_EyeAngle::GetDataDump() { return Helpers::format( ":::: EyeAngleInfo {\n" ":::::::: EyeAngleX {\n" ":::::::::::: Angle : %f,\n" ":::::::::::: Previous Angle : %f,\n" ":::::::::::: Detections Count : %u\n" ":::::::: }," "\n:::::::: EyeAngleY {\n" ":::::::::::: Angle : %f,\n" ":::::::::::: Previous Angle : %f,\n" ":::::::::::: Detections Count : %u\n" ":::::::: },\n" ":::::::: EyeAngleZ {\n" ":::::::::::: Angle : %f,\n" ":::::::::::: Previous Angle : %f,\n" ":::::::::::: Detections Count : %u\n" ":::::::: }\n" ":::: }", GetDataStruct()->x.value, GetDataStruct()->past_x.value, GetDataStruct()->x.detectionsCount, GetDataStruct()->y.value, GetDataStruct()->past_y.value, GetDataStruct()->y.detectionsCount, GetDataStruct()->z.value, GetDataStruct()->past_z.value, GetDataStruct()->z.detectionsCount); } basic_string Detection_EyeAngleX::GetDetectionLogMessage() { if (Helpers::IsInt(GetDataStruct()->x.value)) { return "Anti-Aim"; } else { return "No recoil"; } } basic_string Detection_EyeAngleY::GetDetectionLogMessage() { if (Helpers::IsInt(GetDataStruct()->y.value)) { return "Anti-Aim"; } else { return "No recoil"; } } basic_string Detection_EyeAngleZ::GetDetectionLogMessage() { if (Helpers::IsInt(GetDataStruct()->z.value)) { return "Anti-Aim"; } else { return "No recoil"; } }
29.202703
154
0.700602
im6705
f59ee6395e1e11db0bd828cbd26bb2eabff33dd1
320
cpp
C++
algorithms/MaximumSubarray/solution.cpp
senlinzhan/algorithms
8a8ba89844d645f3e0461e81e25c0bb44b837521
[ "MIT" ]
2
2017-12-02T05:47:10.000Z
2018-01-08T08:43:15.000Z
algorithms/MaximumSubarray/solution.cpp
senlinzhan/algorithms
8a8ba89844d645f3e0461e81e25c0bb44b837521
[ "MIT" ]
null
null
null
algorithms/MaximumSubarray/solution.cpp
senlinzhan/algorithms
8a8ba89844d645f3e0461e81e25c0bb44b837521
[ "MIT" ]
1
2018-07-06T02:14:18.000Z
2018-07-06T02:14:18.000Z
class Solution { public: int maxSubArray(vector<int>& nums) { int maxSum = INT_MIN; int sum = 0; for (int i = 0; i < nums.size(); i++) { sum = std::max(sum + nums[i], nums[i]); maxSum = std::max(maxSum, sum); } return maxSum; } };
21.333333
51
0.44375
senlinzhan
f5a0b653ea5123444f44a63d1c5db33502ead90a
1,528
hpp
C++
include/engge/Engine/Camera.hpp
scemino/engge
3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f
[ "MIT" ]
127
2018-12-09T18:40:02.000Z
2022-03-06T00:10:07.000Z
include/engge/Engine/Camera.hpp
scemino/engge
3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f
[ "MIT" ]
267
2019-02-26T22:16:48.000Z
2022-02-09T09:49:22.000Z
include/engge/Engine/Camera.hpp
scemino/engge
3362ad56b67f58bdc89f7eb1a77f0f75bd350e1f
[ "MIT" ]
17
2019-02-26T20:45:34.000Z
2021-06-17T15:06:26.000Z
#pragma once #include <memory> #include <optional> #include "Interpolations.hpp" #include <glm/vec2.hpp> #include <ngf/System/TimeSpan.h> #include <ngf/Graphics/Rect.h> namespace ng { class Engine; class Camera { public: Camera(); virtual ~Camera(); /// @brief Pans the camera to the target position in a specified time using a given interpolation. /// \param target Position where the camera needs to go. /// \param time Time needed for the camera to reach the target position. /// \param interpolation Interpolation method to use between the current position and the target position. void panTo(glm::vec2 target, ngf::TimeSpan time, InterpolationMethod interpolation); /// @brief Sets the position of the camera. /// @details The position is the center of the camera. /// \param at Position of the camera to set. void at(const glm::vec2 &at); /// @brief Gets the position of the camera. /// @details The position is the center of the camera. /// \return The current position of the camera. [[nodiscard]] glm::vec2 getAt() const; /// @brief Gets the rectangle of the camera. [[nodiscard]] ngf::frect getRect() const; void move(const glm::vec2 &offset); [[nodiscard]] bool isMoving() const; void setBounds(const ngf::irect &cameraBounds); [[nodiscard]] std::optional<ngf::irect> getBounds() const; void resetBounds(); void setEngine(Engine *pEngine); void update(const ngf::TimeSpan &elapsed); private: struct Impl; std::unique_ptr<Impl> m_pImpl; }; } // namespace ng
31.183673
108
0.712042
scemino
f5a2fe8e78bf109afa2d188699109d4d1c727f36
1,110
cpp
C++
leetcode/word-search.cpp
sounishnath003/practice-180D-strategy
2778c861407a2be04168d5dfa6135a4b624029fc
[ "Apache-2.0" ]
null
null
null
leetcode/word-search.cpp
sounishnath003/practice-180D-strategy
2778c861407a2be04168d5dfa6135a4b624029fc
[ "Apache-2.0" ]
null
null
null
leetcode/word-search.cpp
sounishnath003/practice-180D-strategy
2778c861407a2be04168d5dfa6135a4b624029fc
[ "Apache-2.0" ]
1
2020-10-07T15:02:09.000Z
2020-10-07T15:02:09.000Z
class Solution { public:     bool dfs(vector<vector<char>> &board, int row, int col, string &word, int wc) {    if(wc == (int) word.length()){        return true;   }    if(row < 0 or row >= board.size() or col < 0 or col >= board[row].size() or board[row][col] != word[wc])   {        return false;   }    {        char temp = board[row][col];        board[row][col] = ' ';        bool found = (dfs(board, row+1, col, word, wc+1) || dfs(board, row-1, col, word, wc+1)                      || dfs(board, row, col+1, word, wc+1) || dfs(board, row, col-1, word, wc+1));        board[row][col] = temp;        return found;    } } ​        bool exist(vector<vector<char>>& board, string word) {                int M = board.size(), N = board[0].size();        if(board.empty()){            return false;       }        for(int row = 0; row < M; row++){            for(int col = 0; col < N; col++){                if(board[row][col] == word[0] && dfs(board, row, col, word, 0)){                    return true;               }           }       }        return false;   } };
27.75
108
0.455856
sounishnath003
f5a716fac30584103d6f23cb125394106392f88d
4,166
cpp
C++
lecture21/Graph.cpp
jamesmtuck/ncstate_ece309_examples
4f36ac249af8a7910c146994abd541b03d7fdbd9
[ "MIT" ]
11
2018-08-09T14:35:14.000Z
2019-12-12T02:34:28.000Z
lecture21/Graph.cpp
jamesmtuck/ncstate_ece309_examples
4f36ac249af8a7910c146994abd541b03d7fdbd9
[ "MIT" ]
null
null
null
lecture21/Graph.cpp
jamesmtuck/ncstate_ece309_examples
4f36ac249af8a7910c146994abd541b03d7fdbd9
[ "MIT" ]
30
2018-09-02T16:59:17.000Z
2020-01-07T19:21:43.000Z
#include <stdio.h> #include <iostream> #include "Graph.h" #include "IntegerSet.h" #include "Queue.h" SparseGraph::SparseGraph(int n) : Graph(n) { nodes = new Node[numNodes]; } void SparseGraph::addEdge(int v1, int v2) { nodes[v1].edge.append(v2); nodes[v2].edge.append(v1); } bool SparseGraph::isAdjacent(int v1, int v2) { List::iterator it = nodes[v1].edge.begin(); while (!it.end()) { if (it.getItem() == v2) { return true; } it.increment(); } return false; } DenseGraph::DenseGraph(int n) : Graph(n) { edges = new bool[numNodes * numNodes]; for (int i = 0; i < numNodes * numNodes; i++) edges[i] = false; } void DenseGraph::addEdge(int v1, int v2) { edges[v1 * numNodes + v2] = true; edges[v2 * numNodes + v1] = true; } bool DenseGraph::isAdjacent(int v1, int v2) { return edges[v1 * numNodes + v2]; } bool doesPathExist(Graph &g, int *path, int length) { for (int i = 0; i < length - 1; i++) { if (!g.isAdjacent(path[i], path[i + 1])) return false; } return true; } void visit(int node) { printf("%d ", node); } void BreadthFirstSearch(SparseGraph &graph, int start) { IntegerSetHT discovered(1000); Queue frontier; frontier.push(start); discovered.insert(start); while (!frontier.empty()) { int node = frontier.peek(); visit(node); SparseGraph::adjacency_iterator it = graph.getAdjacencyList(node); while (!it.end()) { int j = it.getItem(); if (!discovered.search(j)) { frontier.push(j); discovered.insert(j); } it.increment(); } frontier.pop(); } } void DepthFirstSearch(SparseGraph &g, IntegerSet &visitedSet, int node){ if ( !visitedSet.search(node) ) { visit(node); // take action upon visit to node visitedSet.insert(node); for (SparseGraph::adjacency_iterator it=g.getAdjacencyList(node); !it.end(); it.increment()) DepthFirstSearch(g,visitedSet,it.getItem()); } // end if } // end function class DepthFirstSearch { protected: SparseGraph &g; IntegerSetHT visitedSet; void dfs_helper(int node) { //modified code from prior slide if ( !visitedSet.search(node) ) { visit(node); // take action upon visit to node visitedSet.insert(node); for (SparseGraph::adjacency_iterator it=g.getAdjacencyList(node); !it.end(); it.increment()) dfs_helper(it.getItem()); } } public: DepthFirstSearch(SparseGraph &ag):g(ag),visitedSet(1000){}; void run(int start) { dfs_helper(start); } virtual void visit(int node){}// extend this class to customize visit }; class PrintDFSOrder : public DepthFirstSearch { public: PrintDFSOrder(SparseGraph &g):DepthFirstSearch(g){} void visit(int node) override { printf("%d,",node); }; }; template <class F> class DFS { protected: SparseGraph &g; IntegerSetHT visitedSet; F visit; // functor object void dfs_helper(int node) { if ( !visitedSet.search(node) ) { visit(node); // take action upon visit to node visitedSet.insert(node); for (SparseGraph::adjacency_iterator it=g.getAdjacencyList(node); !it.end(); it.increment()) dfs_helper(it.getItem()); } } public: DFS(SparseGraph &ag):g(ag),visitedSet(1000){}; void run(int start) { dfs_helper(start); } }; class Visit { public: void operator() (int node) { printf("%d-",node); } }; int main() { SparseGraph g(14); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(0, 3); g.addEdge(1, 4); g.addEdge(3, 5); g.addEdge(2, 6); g.addEdge(3, 6); g.addEdge(2, 7); g.addEdge(1, 8); g.addEdge(7, 8); g.addEdge(1, 9); g.addEdge(4, 10); g.addEdge(6, 11); g.addEdge(7, 12); g.addEdge(8, 13); /* int path[3] = {0, 1, 9}; if (doesPathExist(g, path, 3)) printf("Exists!\n");*/ printf("BFS(0)="); BreadthFirstSearch(g, 0); printf("\nBFS(13)="); BreadthFirstSearch(g, 13); IntegerSetHT set(1000); printf("\nDFS(0)="); DepthFirstSearch(g,set,0); printf("\n"); PrintDFSOrder print(g); printf("\nDFS(0)="); print.run(0); DFS<Visit> print2(g); printf("\nDFS(0)="); print2.run(0); return 0; }
21.147208
74
0.621459
jamesmtuck
f5a934acb2b63f19c61facd572b01b01fbe5d2c8
3,532
hpp
C++
src/hash_map.hpp
kophy/TinySTL
366c2f585344a249846f4087904d509fa71e419e
[ "MIT" ]
5
2017-05-04T12:21:09.000Z
2019-03-28T09:29:50.000Z
src/hash_map.hpp
kophy/TinySTL
366c2f585344a249846f4087904d509fa71e419e
[ "MIT" ]
null
null
null
src/hash_map.hpp
kophy/TinySTL
366c2f585344a249846f4087904d509fa71e419e
[ "MIT" ]
null
null
null
#ifndef __TINYSTL_HASH_MAP__ #define __TINYSTL_HASH_MAP__ #include "hash_table.hpp" #include "allocator.hpp" #include "utils.hpp" namespace TinySTL { template <typename Key, typename Value> static bool isEqualKey(const Pair<const Key, Value> &a, const Pair<const Key, Value> &b) { return a.first == b.first; } template <typename Key, typename Value> static unsigned long hashByKey(const Pair<const Key, Value> &a) { return Hash<Key>(a.first); } template <typename Key, typename Value, class Alloc = Allocator<Pair<const Key, Value>>> class HashMap : public HashTable<Pair<const Key, Value>, Alloc> { public: class Iterator : public ForwardIterator { public: bool operator ==(const Iterator &I) { return (this->data == I.data && this->e == I.e); } bool operator !=(const Iterator &I) { return (this->data != I.data || this->e != I.e); } Pair<const Key, Value> &operator *() { return *(e.second); } Pair<const Key, Value> *operator ->() { return &(*(e.second)); } Iterator operator ++() { advance(); return *this; } Iterator operator ++(int dummy) { auto temp = *this; advance(); return temp; } Iterator(HashMap<Key, Value, Alloc> *_data, typename HashMap<Key, Value>::HashEntry _e) : data(_data), e(_e) {} private: HashMap<Key, Value, Alloc> *data; typename HashMap<Key, Value>::HashEntry e; void advance() { e = data->findNext(e); } friend class HashMap<Key, Value>; }; // iterator to the beginning Iterator begin() { return Iterator(this, base::findBegin()); } // iterator to the end Iterator end() { return Iterator(this, base::findEnd()); } // iterator to element with specific key Iterator find(const Key &k) { auto kv = MakePair<const Key, Value>(k, Value()); return Iterator(this, base::find(kv)); } // access element Value &operator [](const Key &k) { auto iter = find(k); if (iter == this->end()) { insert(k, Value()); iter = find(k); } return iter->second; } // insert wrapper void insert(const Key &k, const Value &v) { base::insert(MakePair<const Key, Value>(k, v)); } // erase wrapper void erase(const Key &k) { base::erase(MakePair<const Key, Value>(k, Value())); } // count wrapper unsigned int count(const Key &k) { return base::count(MakePair<const Key, Value>(k, Value())); } HashMap(bool (*_pred)(const Pair<const Key, Value> &a, const Pair<const Key, Value> &b) = isEqualKey<Key, Value>, unsigned long (*_hash)(const Pair<const Key, Value> &val) = hashByKey<Key, Value>, double _alpha = 1.0) : HashTable<Pair<const Key, Value>, Alloc>::HashTable(_pred, _hash, _alpha) {} private: typedef HashTable<Pair<const Key, Value>> base; friend class Iterator; }; }; #endif
36.791667
125
0.507928
kophy
f5aa0118dcc76527f14b2d6720f25e56214cddd7
5,115
cpp
C++
src/StdvNormalizer.cpp
BR903/percolator
2d9315699cf3309421b83c4c21ce8275ede87089
[ "Apache-2.0" ]
71
2015-03-30T17:22:52.000Z
2022-01-01T14:19:23.000Z
src/StdvNormalizer.cpp
BR903/percolator
2d9315699cf3309421b83c4c21ce8275ede87089
[ "Apache-2.0" ]
190
2015-01-27T16:18:58.000Z
2022-03-31T16:49:58.000Z
src/StdvNormalizer.cpp
BR903/percolator
2d9315699cf3309421b83c4c21ce8275ede87089
[ "Apache-2.0" ]
45
2015-04-13T13:42:35.000Z
2021-12-17T08:26:21.000Z
/******************************************************************************* Copyright 2006-2012 Lukas Käll <lukas.kall@scilifelab.se> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ #include <iostream> #ifdef WIN32 #include <float.h> #define isfinite _finite #endif #include <math.h> #include <vector> #include <string> using namespace std; #include "Normalizer.h" #include "StdvNormalizer.h" #include "Globals.h" StdvNormalizer::StdvNormalizer() { } StdvNormalizer::~StdvNormalizer() { } void StdvNormalizer::unnormalizeweight(const std::vector<double>& in, std::vector<double>& out) { double sum = 0; unsigned int i = 0; for (; i < numFeatures; i++) { out[i] = in[i] / div[i]; sum += sub[i] * in[i] / div[i]; } out[i] = in[i] - sum; } void StdvNormalizer::normalizeweight(const std::vector<double>& in, std::vector<double>& out) { double sum = 0; size_t i = 0; for (; i < numFeatures; i++) { out[i] = in[i] * div[i]; sum += sub[i] * in[i]; } out[i] = in[i] + sum; } void StdvNormalizer::setSet(std::vector<double*>& featuresV, std::vector<double*>& rtFeaturesV, size_t nf, size_t nrf) { numFeatures = nf; numRetentionFeatures = nrf; sub.resize(nf + nrf, 0.0); div.resize(nf + nrf, 0.0); double n = 0.0; double* features; size_t ix; vector<double*>::iterator it = featuresV.begin(); for (; it != featuresV.end(); ++it) { features = *it; n++; for (ix = 0; ix < numFeatures; ++ix) { sub[ix] += features[ix]; } } for (it = rtFeaturesV.begin(); it != rtFeaturesV.end(); ++it) { features = *it; for (ix = numFeatures; ix < numFeatures + numRetentionFeatures; ++ix) { sub[ix] += features[ix - numFeatures]; } } if (VERB > 2) { cerr.precision(2); cerr << "Normalization factors" << endl << "Avg "; } for (ix = 0; ix < numFeatures + numRetentionFeatures; ++ix) { if (n > 0.0) { sub[ix] /= n; } if (VERB > 2) { cerr << "\t" << sub[ix]; } } for (it = featuresV.begin(); it != featuresV.end(); ++it) { features = *it; for (ix = 0; ix < numFeatures; ++ix) { if (!isfinite(features[ix])) { cerr << "Reached strange feature with val=" << features[ix] << " at col=" << ix << endl; } double d = features[ix] - sub[ix]; div[ix] += d * d; } } for (it = rtFeaturesV.begin(); it != rtFeaturesV.end(); ++it) { features = *it; for (ix = numFeatures; ix < numFeatures + numRetentionFeatures; ++ix) { if (!isfinite(features[ix-numFeatures])) { cerr << "Reached strange feature with val=" << features[ix - numFeatures] << " at col=" << ix << endl; } double d = features[ix - numFeatures] - sub[ix]; div[ix] += d * d; } } if (VERB > 2) { cerr << endl << "Stdv"; } for (ix = 0; ix < numFeatures + numRetentionFeatures; ++ix) { if (div[ix] <= 0 || n == 0) { div[ix] = 1.0; } else { div[ix] = sqrt(div[ix] / n); } if (VERB > 2) { cerr << "\t" << div[ix]; } } if (VERB > 2) { cerr << endl; } } void StdvNormalizer::updateSet(vector<double*> & featuresV, size_t offset, size_t numFeatures) { double n = 0.0; double* features; size_t ix; vector<double*>::iterator it = featuresV.begin(); for (; it != featuresV.end(); ++it) { features = *it; n++; for (ix = 0; ix < numFeatures; ++ix) { sub[offset + ix] += features[ix]; } } if (VERB > 2) { cerr.precision(2); cerr << "Normalization factors" << endl << "Avg "; } for (ix = 0; ix < numFeatures; ++ix) { if (n > 0.0) { sub[offset + ix] /= n; } if (VERB > 2) { cerr << "\t" << sub[offset + ix]; } } for (it = featuresV.begin(); it != featuresV.end(); ++it) { features = *it; for (ix = 0; ix < numFeatures; ++ix) { if (!isfinite(features[ix])) { cerr << "Reached strange feature with val=" << features[ix] << " at col=" << ix << endl; } double d = features[ix] - sub[offset + ix]; div[offset + ix] += d * d; } } if (VERB > 2) { cerr << endl << "Stdv"; } for (ix = 0; ix < numFeatures; ++ix) { if (div[offset + ix] <= 0 || n == 0) { div[offset + ix] = 1.0; } else { div[offset + ix] = sqrt(div[offset + ix] / n); } if (VERB > 2) { cerr << "\t" << div[offset + ix]; } } if (VERB > 2) { cerr << endl; } }
26.640625
81
0.527273
BR903
f5aab048acb471224d4968ff15a833a9a6ab7672
4,241
cpp
C++
iai/src/v20180301/model/GetPersonBaseInfoResponse.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
null
null
null
iai/src/v20180301/model/GetPersonBaseInfoResponse.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
null
null
null
iai/src/v20180301/model/GetPersonBaseInfoResponse.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/iai/v20180301/model/GetPersonBaseInfoResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Iai::V20180301::Model; using namespace rapidjson; using namespace std; GetPersonBaseInfoResponse::GetPersonBaseInfoResponse() : m_personNameHasBeenSet(false), m_genderHasBeenSet(false), m_faceIdsHasBeenSet(false) { } CoreInternalOutcome GetPersonBaseInfoResponse::Deserialize(const string &payload) { Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Error("response `Response` is null or not object")); } Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Error(errorCode, errorMsg).SetRequestId(requestId)); } if (rsp.HasMember("PersonName") && !rsp["PersonName"].IsNull()) { if (!rsp["PersonName"].IsString()) { return CoreInternalOutcome(Error("response `PersonName` IsString=false incorrectly").SetRequestId(requestId)); } m_personName = string(rsp["PersonName"].GetString()); m_personNameHasBeenSet = true; } if (rsp.HasMember("Gender") && !rsp["Gender"].IsNull()) { if (!rsp["Gender"].IsInt64()) { return CoreInternalOutcome(Error("response `Gender` IsInt64=false incorrectly").SetRequestId(requestId)); } m_gender = rsp["Gender"].GetInt64(); m_genderHasBeenSet = true; } if (rsp.HasMember("FaceIds") && !rsp["FaceIds"].IsNull()) { if (!rsp["FaceIds"].IsArray()) return CoreInternalOutcome(Error("response `FaceIds` is not array type")); const Value &tmpValue = rsp["FaceIds"]; for (Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { m_faceIds.push_back((*itr).GetString()); } m_faceIdsHasBeenSet = true; } return CoreInternalOutcome(true); } string GetPersonBaseInfoResponse::GetPersonName() const { return m_personName; } bool GetPersonBaseInfoResponse::PersonNameHasBeenSet() const { return m_personNameHasBeenSet; } int64_t GetPersonBaseInfoResponse::GetGender() const { return m_gender; } bool GetPersonBaseInfoResponse::GenderHasBeenSet() const { return m_genderHasBeenSet; } vector<string> GetPersonBaseInfoResponse::GetFaceIds() const { return m_faceIds; } bool GetPersonBaseInfoResponse::FaceIdsHasBeenSet() const { return m_faceIdsHasBeenSet; }
30.956204
122
0.674841
li5ch
f5aca9b4c15da8e2a8ea61c8a7b9bdb82aff1c26
542
cpp
C++
ModelViewer/LoadingWrapper.cpp
peted70/glTF-DXViewer
1857e630fc14d19ced41c3ae9b895b017f937ab7
[ "MIT" ]
null
null
null
ModelViewer/LoadingWrapper.cpp
peted70/glTF-DXViewer
1857e630fc14d19ced41c3ae9b895b017f937ab7
[ "MIT" ]
null
null
null
ModelViewer/LoadingWrapper.cpp
peted70/glTF-DXViewer
1857e630fc14d19ced41c3ae9b895b017f937ab7
[ "MIT" ]
null
null
null
#include "pch.h" #include "LoadingWrapper.h" using namespace std; LoadingWrapper::LoadingWrapper(function<void()> ctor, function<void()> dtor) : _dtor(dtor) { Schedule(ctor); } future<void> LoadingWrapper::Schedule(function<void()> fn) { auto disp = Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher; co_await disp->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([fn]() { fn(); })); } LoadingWrapper::~LoadingWrapper() { Schedule(_dtor); }
23.565217
96
0.732472
peted70
f5adf6c6a995ca354b6279e8078d9b238cd2b123
800
cpp
C++
Dataset/Leetcode/train/98/219.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/98/219.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/98/219.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: // left记录当前节点的上一个节点的值 long long left = LONG_MIN; bool XXX(TreeNode* root) { return XXX2(root, NULL, NULL); } bool XXX1(TreeNode* root) { if(!root) return true; if(XXX(root->left)) { // 如果上一个节点的值小于当前节点,说明满足升序,继续遍历,否则返回false if(root->val > left) { left = root->val; return XXX(root->right); } } return false; } bool XXX2(TreeNode* root, TreeNode* min, TreeNode* max) { if(!root) return true; if(min && root->val <= min->val) return false; if(max && root->val >= max->val) return false; // 判断左子树时,值不能超过root;判断右子树,值不能小于root return XXX2(root->left, min, root) && XXX2(root->right, root, max); } };
28.571429
75
0.53
kkcookies99
f5ae25e03cd71f1b1c8137f547d5c598add9ba63
2,524
cpp
C++
src/collate_result.cpp
lsilvest/crpcut
e9d694fb04599b72ebdcf6fea7d6ad598807ff41
[ "BSD-2-Clause" ]
1
2019-04-09T12:48:41.000Z
2019-04-09T12:48:41.000Z
src/collate_result.cpp
lsilvest/crpcut
e9d694fb04599b72ebdcf6fea7d6ad598807ff41
[ "BSD-2-Clause" ]
2
2020-05-06T16:22:07.000Z
2020-05-07T04:02:41.000Z
src/collate_result.cpp
lsilvest/crpcut
e9d694fb04599b72ebdcf6fea7d6ad598807ff41
[ "BSD-2-Clause" ]
1
2019-04-10T12:47:11.000Z
2019-04-10T12:47:11.000Z
/* * Copyright 2011 Bjorn Fahller <bjorn@fahller.se> * All rights reserved * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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 <crpcut.hpp> namespace crpcut { collate_result ::collate_result(const char *refstr, std::string comp, const std::locale& l) : r(refstr), intl(comp), locale(l), side(right) { } collate_result ::collate_result(const collate_result& o) : r(o.r), intl(o.intl), locale(o.locale), side(o.side) { } collate_result ::operator const collate_result::comparator*() const { return operator()(); } const collate_result::comparator* collate_result ::operator()() const { return reinterpret_cast<const comparator*>(r ? 0 : this); } collate_result& collate_result ::set_lh() { side = left; return *this; } std::ostream &operator<<(std::ostream& os, const collate_result &obj) { static const char rs[] = "\"\n" " and right hand value = \""; os << "Failed in locale \"" << obj.locale.name() << "\"\n" " with left hand value = \""; if (obj.side == collate_result::right) { os << obj.intl << rs << obj.r << "\""; } else { os << obj.r << rs << obj.intl << "\""; } return os; } }
29.348837
78
0.669176
lsilvest
f5ae32e32a5638d8fef7af97cff86068943bda25
201
cpp
C++
ComputerGraphics/Script.cpp
ylzf0000/TinyGameEngine
d15c3eb80189d91ed430eca1089475213ef0cad3
[ "MIT" ]
null
null
null
ComputerGraphics/Script.cpp
ylzf0000/TinyGameEngine
d15c3eb80189d91ed430eca1089475213ef0cad3
[ "MIT" ]
null
null
null
ComputerGraphics/Script.cpp
ylzf0000/TinyGameEngine
d15c3eb80189d91ed430eca1089475213ef0cad3
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Script.h" #include "Object.h" #include "Mesh.h" #include "Transform.h" cg::Script::Script(Object *pObj) :pObject(pObj), transform(pObj->transform), pMesh(pObj->pMesh) {}
22.333333
95
0.706468
ylzf0000
f5aedeeaf31c124b8443217321b012f263ebce23
1,065
hpp
C++
src/backend/cuda/Param.hpp
ckeitz/arrayfire
a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b
[ "BSD-3-Clause" ]
4
2015-12-16T09:41:32.000Z
2018-10-29T10:38:53.000Z
src/backend/cuda/Param.hpp
ckeitz/arrayfire
a1a1bbbc8487a032eb27a6c894b1b3dfb19d123b
[ "BSD-3-Clause" ]
3
2015-11-15T18:43:47.000Z
2015-12-16T09:43:14.000Z
src/backend/cuda/Param.hpp
pavanky/arrayfire
f983a79c7d402450bd2a704bbc1015b89f0cd504
[ "BSD-3-Clause" ]
null
null
null
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #pragma once #include <af/defines.h> #include <backend.hpp> namespace cuda { template<typename T> struct Param { T *ptr; dim_type dims[4]; dim_type strides[4]; }; template<typename T> class CParam { public: const T *ptr; dim_type dims[4]; dim_type strides[4]; __DH__ CParam(const T *iptr, const dim_type *idims, const dim_type *istrides) : ptr(iptr) { for (int i = 0; i < 4; i++) { dims[i] = idims[i]; strides[i] = istrides[i]; } } __DH__ CParam(Param<T> &in) : ptr(in.ptr) { for (int i = 0; i < 4; i++) { dims[i] = in.dims[i]; strides[i] = in.strides[i]; } } __DH__ ~CParam() {} }; }
19.722222
83
0.504225
ckeitz
f5af81e36cbe38e3109c5ba6427a06852577b146
24,656
cpp
C++
src/ports/SkFontMgr_mac_ct.cpp
JimmySoftware/skia
d5a244e6c00c12f8c91c94ff4549191177dd817e
[ "BSD-3-Clause" ]
null
null
null
src/ports/SkFontMgr_mac_ct.cpp
JimmySoftware/skia
d5a244e6c00c12f8c91c94ff4549191177dd817e
[ "BSD-3-Clause" ]
null
null
null
src/ports/SkFontMgr_mac_ct.cpp
JimmySoftware/skia
d5a244e6c00c12f8c91c94ff4549191177dd817e
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkTypes.h" #if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS) #ifdef SK_BUILD_FOR_MAC #import <ApplicationServices/ApplicationServices.h> #endif #ifdef SK_BUILD_FOR_IOS #include <CoreText/CoreText.h> #include <CoreText/CTFontManager.h> #include <CoreGraphics/CoreGraphics.h> #include <CoreFoundation/CoreFoundation.h> #include <dlfcn.h> #endif #include "include/core/SkData.h" #include "include/core/SkFontArguments.h" #include "include/core/SkFontMgr.h" #include "include/core/SkFontStyle.h" #include "include/core/SkStream.h" #include "include/core/SkString.h" #include "include/core/SkTypeface.h" #include "include/ports/SkFontMgr_mac_ct.h" #include "include/private/SkFixed.h" #include "include/private/SkOnce.h" #include "include/private/SkTPin.h" #include "include/private/SkTemplates.h" #include "include/private/SkTo.h" #include "src/core/SkFontDescriptor.h" #include "src/ports/SkTypeface_mac_ct.h" #include "src/utils/SkUTF.h" #include <string.h> #include <memory> #if (defined(SK_BUILD_FOR_IOS) && defined(__IPHONE_14_0) && \ __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_14_0) || \ (defined(SK_BUILD_FOR_MAC) && defined(__MAC_11_0) && \ __MAC_OS_VERSION_MIN_REQUIRED >= __MAC_11_0) static uint32_t SkGetCoreTextVersion() { // If compiling for iOS 14.0+ or macOS 11.0+, the CoreText version number // must be derived from the OS version number. static const uint32_t kCoreTextVersionNEWER = 0x000D0000; return kCoreTextVersionNEWER; } #else static uint32_t SkGetCoreTextVersion() { // Check for CoreText availability before calling CTGetCoreTextVersion(). static const bool kCoreTextIsAvailable = (&CTGetCoreTextVersion != nullptr); if (kCoreTextIsAvailable) { return CTGetCoreTextVersion(); } // Default to a value that's smaller than any known CoreText version. static const uint32_t kCoreTextVersionUNKNOWN = 0; return kCoreTextVersionUNKNOWN; } #endif static SkUniqueCFRef<CFStringRef> make_CFString(const char s[]) { return SkUniqueCFRef<CFStringRef>(CFStringCreateWithCString(nullptr, s, kCFStringEncodingUTF8)); } /** Creates a typeface from a descriptor, searching the cache. */ static sk_sp<SkTypeface> create_from_desc(CTFontDescriptorRef desc) { SkUniqueCFRef<CTFontRef> ctFont(CTFontCreateWithFontDescriptor(desc, 0, nullptr)); if (!ctFont) { return nullptr; } return SkTypeface_Mac::Make(std::move(ctFont), OpszVariation(), nullptr); } static SkUniqueCFRef<CTFontDescriptorRef> create_descriptor(const char familyName[], const SkFontStyle& style) { SkUniqueCFRef<CFMutableDictionaryRef> cfAttributes( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); SkUniqueCFRef<CFMutableDictionaryRef> cfTraits( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); if (!cfAttributes || !cfTraits) { return nullptr; } // TODO(crbug.com/1018581) Some CoreText versions have errant behavior when // certain traits set. Temporary workaround to omit specifying trait for those // versions. // Long term solution will involve serializing typefaces instead of relying upon // this to match between processes. // // Compare CoreText.h in an up to date SDK for where these values come from. static const uint32_t kSkiaLocalCTVersionNumber10_14 = 0x000B0000; static const uint32_t kSkiaLocalCTVersionNumber10_15 = 0x000C0000; // CTFontTraits (symbolic) // macOS 14 and iOS 12 seem to behave badly when kCTFontSymbolicTrait is set. // macOS 15 yields LastResort font instead of a good default font when // kCTFontSymbolicTrait is set. if (SkGetCoreTextVersion() < kSkiaLocalCTVersionNumber10_14) { CTFontSymbolicTraits ctFontTraits = 0; if (style.weight() >= SkFontStyle::kBold_Weight) { ctFontTraits |= kCTFontBoldTrait; } if (style.slant() != SkFontStyle::kUpright_Slant) { ctFontTraits |= kCTFontItalicTrait; } SkUniqueCFRef<CFNumberRef> cfFontTraits( CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &ctFontTraits)); if (cfFontTraits) { CFDictionaryAddValue(cfTraits.get(), kCTFontSymbolicTrait, cfFontTraits.get()); } } // CTFontTraits (weight) CGFloat ctWeight = SkCTFontCTWeightForCSSWeight(style.weight()); SkUniqueCFRef<CFNumberRef> cfFontWeight( CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &ctWeight)); if (cfFontWeight) { CFDictionaryAddValue(cfTraits.get(), kCTFontWeightTrait, cfFontWeight.get()); } // CTFontTraits (width) CGFloat ctWidth = SkCTFontCTWidthForCSSWidth(style.width()); SkUniqueCFRef<CFNumberRef> cfFontWidth( CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &ctWidth)); if (cfFontWidth) { CFDictionaryAddValue(cfTraits.get(), kCTFontWidthTrait, cfFontWidth.get()); } // CTFontTraits (slant) // macOS 15 behaves badly when kCTFontSlantTrait is set. if (SkGetCoreTextVersion() != kSkiaLocalCTVersionNumber10_15) { CGFloat ctSlant = style.slant() == SkFontStyle::kUpright_Slant ? 0 : 1; SkUniqueCFRef<CFNumberRef> cfFontSlant( CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &ctSlant)); if (cfFontSlant) { CFDictionaryAddValue(cfTraits.get(), kCTFontSlantTrait, cfFontSlant.get()); } } // CTFontTraits CFDictionaryAddValue(cfAttributes.get(), kCTFontTraitsAttribute, cfTraits.get()); // CTFontFamilyName if (familyName) { SkUniqueCFRef<CFStringRef> cfFontName = make_CFString(familyName); if (cfFontName) { CFDictionaryAddValue(cfAttributes.get(), kCTFontFamilyNameAttribute, cfFontName.get()); } } return SkUniqueCFRef<CTFontDescriptorRef>( CTFontDescriptorCreateWithAttributes(cfAttributes.get())); } // Same as the above function except style is included so we can // compare whether the created font conforms to the style. If not, we need // to recreate the font with symbolic traits. This is needed due to MacOS 10.11 // font creation problem https://bugs.chromium.org/p/skia/issues/detail?id=8447. static sk_sp<SkTypeface> create_from_desc_and_style(CTFontDescriptorRef desc, const SkFontStyle& style) { SkUniqueCFRef<CTFontRef> ctFont(CTFontCreateWithFontDescriptor(desc, 0, nullptr)); if (!ctFont) { return nullptr; } const CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(ctFont.get()); CTFontSymbolicTraits expected_traits = traits; if (style.slant() != SkFontStyle::kUpright_Slant) { expected_traits |= kCTFontItalicTrait; } if (style.weight() >= SkFontStyle::kBold_Weight) { expected_traits |= kCTFontBoldTrait; } if (expected_traits != traits) { SkUniqueCFRef<CTFontRef> ctNewFont(CTFontCreateCopyWithSymbolicTraits( ctFont.get(), 0, nullptr, expected_traits, expected_traits)); if (ctNewFont) { ctFont = std::move(ctNewFont); } } return SkTypeface_Mac::Make(std::move(ctFont), OpszVariation(), nullptr); } /** Creates a typeface from a name, searching the cache. */ static sk_sp<SkTypeface> create_from_name(const char familyName[], const SkFontStyle& style) { SkUniqueCFRef<CTFontDescriptorRef> desc = create_descriptor(familyName, style); if (!desc) { return nullptr; } return create_from_desc_and_style(desc.get(), style); } static const char* map_css_names(const char* name) { static const struct { const char* fFrom; // name the caller specified const char* fTo; // "canonical" name we map to } gPairs[] = { { "sans-serif", "Helvetica" }, { "serif", "Times" }, { "monospace", "Courier" } }; for (size_t i = 0; i < SK_ARRAY_COUNT(gPairs); i++) { if (strcmp(name, gPairs[i].fFrom) == 0) { return gPairs[i].fTo; } } return name; // no change } namespace { static sk_sp<SkData> skdata_from_skstreamasset(std::unique_ptr<SkStreamAsset> stream) { size_t size = stream->getLength(); if (const void* base = stream->getMemoryBase()) { return SkData::MakeWithProc(base, size, [](const void*, void* ctx) -> void { delete (SkStreamAsset*)ctx; }, stream.release()); } return SkData::MakeFromStream(stream.get(), size); } static SkUniqueCFRef<CFDataRef> cfdata_from_skdata(sk_sp<SkData> data) { void const * const addr = data->data(); size_t const size = data->size(); CFAllocatorContext ctx = { 0, // CFIndex version data.release(), // void* info nullptr, // const void *(*retain)(const void *info); nullptr, // void (*release)(const void *info); nullptr, // CFStringRef (*copyDescription)(const void *info); nullptr, // void * (*allocate)(CFIndex size, CFOptionFlags hint, void *info); nullptr, // void*(*reallocate)(void* ptr,CFIndex newsize,CFOptionFlags hint,void* info); [](void*,void* info) -> void { // void (*deallocate)(void *ptr, void *info); SkASSERT(info); ((SkData*)info)->unref(); }, nullptr, // CFIndex (*preferredSize)(CFIndex size, CFOptionFlags hint, void *info); }; SkUniqueCFRef<CFAllocatorRef> alloc(CFAllocatorCreate(kCFAllocatorDefault, &ctx)); return SkUniqueCFRef<CFDataRef>(CFDataCreateWithBytesNoCopy( kCFAllocatorDefault, (const UInt8 *)addr, size, alloc.get())); } static SkUniqueCFRef<CTFontRef> ctfont_from_skdata(sk_sp<SkData> data, int ttcIndex) { // TODO: Use CTFontManagerCreateFontDescriptorsFromData when available. if (ttcIndex != 0) { return nullptr; } SkUniqueCFRef<CFDataRef> cfData(cfdata_from_skdata(std::move(data))); SkUniqueCFRef<CTFontDescriptorRef> desc( CTFontManagerCreateFontDescriptorFromData(cfData.get())); if (!desc) { return nullptr; } return SkUniqueCFRef<CTFontRef>(CTFontCreateWithFontDescriptor(desc.get(), 0, nullptr)); } static bool find_desc_str(CTFontDescriptorRef desc, CFStringRef name, SkString* value) { SkUniqueCFRef<CFStringRef> ref((CFStringRef)CTFontDescriptorCopyAttribute(desc, name)); if (!ref) { return false; } SkStringFromCFString(ref.get(), value); return true; } static inline int sqr(int value) { SkASSERT(SkAbs32(value) < 0x7FFF); // check for overflow return value * value; } // We normalize each axis (weight, width, italic) to be base-900 static int compute_metric(const SkFontStyle& a, const SkFontStyle& b) { return sqr(a.weight() - b.weight()) + sqr((a.width() - b.width()) * 100) + sqr((a.slant() != b.slant()) * 900); } class SkFontStyleSet_Mac : public SkFontStyleSet { public: SkFontStyleSet_Mac(CTFontDescriptorRef desc) : fArray(CTFontDescriptorCreateMatchingFontDescriptors(desc, nullptr)) , fCount(0) { if (!fArray) { fArray.reset(CFArrayCreate(nullptr, nullptr, 0, nullptr)); } fCount = SkToInt(CFArrayGetCount(fArray.get())); } int count() override { return fCount; } void getStyle(int index, SkFontStyle* style, SkString* name) override { SkASSERT((unsigned)index < (unsigned)fCount); CTFontDescriptorRef desc = (CTFontDescriptorRef)CFArrayGetValueAtIndex(fArray.get(), index); if (style) { *style = SkCTFontDescriptorGetSkFontStyle(desc, false); } if (name) { if (!find_desc_str(desc, kCTFontStyleNameAttribute, name)) { name->reset(); } } } SkTypeface* createTypeface(int index) override { SkASSERT((unsigned)index < (unsigned)CFArrayGetCount(fArray.get())); CTFontDescriptorRef desc = (CTFontDescriptorRef)CFArrayGetValueAtIndex(fArray.get(), index); return create_from_desc(desc).release(); } SkTypeface* matchStyle(const SkFontStyle& pattern) override { if (0 == fCount) { return nullptr; } return create_from_desc(findMatchingDesc(pattern)).release(); } private: SkUniqueCFRef<CFArrayRef> fArray; int fCount; CTFontDescriptorRef findMatchingDesc(const SkFontStyle& pattern) const { int bestMetric = SK_MaxS32; CTFontDescriptorRef bestDesc = nullptr; for (int i = 0; i < fCount; ++i) { CTFontDescriptorRef desc = (CTFontDescriptorRef)CFArrayGetValueAtIndex(fArray.get(), i); int metric = compute_metric(pattern, SkCTFontDescriptorGetSkFontStyle(desc, false)); if (0 == metric) { return desc; } if (metric < bestMetric) { bestMetric = metric; bestDesc = desc; } } SkASSERT(bestDesc); return bestDesc; } }; SkUniqueCFRef<CFArrayRef> SkCopyAvailableFontFamilyNames(CTFontCollectionRef collection) { // Create a CFArray of all available font descriptors. SkUniqueCFRef<CFArrayRef> descriptors( CTFontCollectionCreateMatchingFontDescriptors(collection)); // Copy the font family names of the font descriptors into a CFSet. auto addDescriptorFamilyNameToSet = [](const void* value, void* context) -> void { CTFontDescriptorRef descriptor = static_cast<CTFontDescriptorRef>(value); CFMutableSetRef familyNameSet = static_cast<CFMutableSetRef>(context); SkUniqueCFRef<CFTypeRef> familyName( CTFontDescriptorCopyAttribute(descriptor, kCTFontFamilyNameAttribute)); if (familyName) { CFSetAddValue(familyNameSet, familyName.get()); } }; SkUniqueCFRef<CFMutableSetRef> familyNameSet( CFSetCreateMutable(kCFAllocatorDefault, 0, &kCFTypeSetCallBacks)); CFArrayApplyFunction(descriptors.get(), CFRangeMake(0, CFArrayGetCount(descriptors.get())), addDescriptorFamilyNameToSet, familyNameSet.get()); // Get the set of family names into an array; this does not retain. CFIndex count = CFSetGetCount(familyNameSet.get()); std::unique_ptr<const void*[]> familyNames(new const void*[count]); CFSetGetValues(familyNameSet.get(), familyNames.get()); // Sort the array of family names (to match CTFontManagerCopyAvailableFontFamilyNames). std::sort(familyNames.get(), familyNames.get() + count, [](const void* a, const void* b){ return CFStringCompare((CFStringRef)a, (CFStringRef)b, 0) == kCFCompareLessThan; }); // Copy family names into a CFArray; this does retain. return SkUniqueCFRef<CFArrayRef>( CFArrayCreate(kCFAllocatorDefault, familyNames.get(), count, &kCFTypeArrayCallBacks)); } /** Use CTFontManagerCopyAvailableFontFamilyNames if available, simulate if not. */ SkUniqueCFRef<CFArrayRef> SkCTFontManagerCopyAvailableFontFamilyNames() { #ifdef SK_BUILD_FOR_IOS using CTFontManagerCopyAvailableFontFamilyNamesProc = CFArrayRef (*)(void); CTFontManagerCopyAvailableFontFamilyNamesProc ctFontManagerCopyAvailableFontFamilyNames; *(void**)(&ctFontManagerCopyAvailableFontFamilyNames) = dlsym(RTLD_DEFAULT, "CTFontManagerCopyAvailableFontFamilyNames"); if (ctFontManagerCopyAvailableFontFamilyNames) { return SkUniqueCFRef<CFArrayRef>(ctFontManagerCopyAvailableFontFamilyNames()); } SkUniqueCFRef<CTFontCollectionRef> collection( CTFontCollectionCreateFromAvailableFonts(nullptr)); return SkUniqueCFRef<CFArrayRef>(SkCopyAvailableFontFamilyNames(collection.get())); #else return SkUniqueCFRef<CFArrayRef>(CTFontManagerCopyAvailableFontFamilyNames()); #endif } } // namespace class SkFontMgr_Mac : public SkFontMgr { SkUniqueCFRef<CFArrayRef> fNames; int fCount; CFStringRef getFamilyNameAt(int index) const { SkASSERT((unsigned)index < (unsigned)fCount); return (CFStringRef)CFArrayGetValueAtIndex(fNames.get(), index); } static SkFontStyleSet* CreateSet(CFStringRef cfFamilyName) { SkUniqueCFRef<CFMutableDictionaryRef> cfAttr( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); CFDictionaryAddValue(cfAttr.get(), kCTFontFamilyNameAttribute, cfFamilyName); SkUniqueCFRef<CTFontDescriptorRef> desc( CTFontDescriptorCreateWithAttributes(cfAttr.get())); return new SkFontStyleSet_Mac(desc.get()); } public: SkUniqueCFRef<CTFontCollectionRef> fFontCollection; SkFontMgr_Mac(CTFontCollectionRef fontCollection) : fNames(fontCollection ? SkCopyAvailableFontFamilyNames(fontCollection) : SkCTFontManagerCopyAvailableFontFamilyNames()) , fCount(fNames ? SkToInt(CFArrayGetCount(fNames.get())) : 0) , fFontCollection(fontCollection ? (CTFontCollectionRef)CFRetain(fontCollection) : CTFontCollectionCreateFromAvailableFonts(nullptr)) {} protected: int onCountFamilies() const override { return fCount; } void onGetFamilyName(int index, SkString* familyName) const override { if ((unsigned)index < (unsigned)fCount) { SkStringFromCFString(this->getFamilyNameAt(index), familyName); } else { familyName->reset(); } } SkFontStyleSet* onCreateStyleSet(int index) const override { if ((unsigned)index >= (unsigned)fCount) { return nullptr; } return CreateSet(this->getFamilyNameAt(index)); } SkFontStyleSet* onMatchFamily(const char familyName[]) const override { if (!familyName) { return nullptr; } SkUniqueCFRef<CFStringRef> cfName = make_CFString(familyName); return CreateSet(cfName.get()); } SkTypeface* onMatchFamilyStyle(const char familyName[], const SkFontStyle& style) const override { SkUniqueCFRef<CTFontDescriptorRef> desc = create_descriptor(familyName, style); return create_from_desc(desc.get()).release(); } SkTypeface* onMatchFamilyStyleCharacter(const char familyName[], const SkFontStyle& style, const char* bcp47[], int bcp47Count, SkUnichar character) const override { SkUniqueCFRef<CTFontDescriptorRef> desc = create_descriptor(familyName, style); SkUniqueCFRef<CTFontRef> familyFont(CTFontCreateWithFontDescriptor(desc.get(), 0, nullptr)); // kCFStringEncodingUTF32 is BE unless there is a BOM. // Since there is no machine endian option, explicitly state machine endian. #ifdef SK_CPU_LENDIAN constexpr CFStringEncoding encoding = kCFStringEncodingUTF32LE; #else constexpr CFStringEncoding encoding = kCFStringEncodingUTF32BE; #endif SkUniqueCFRef<CFStringRef> string(CFStringCreateWithBytes( kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(&character), sizeof(character), encoding, false)); // If 0xD800 <= codepoint <= 0xDFFF || 0x10FFFF < codepoint 'string' may be nullptr. // No font should be covering such codepoints (even the magic fallback font). if (!string) { return nullptr; } CFRange range = CFRangeMake(0, CFStringGetLength(string.get())); // in UniChar units. SkUniqueCFRef<CTFontRef> fallbackFont( CTFontCreateForString(familyFont.get(), string.get(), range)); return SkTypeface_Mac::Make(std::move(fallbackFont), OpszVariation(), nullptr).release(); } sk_sp<SkTypeface> onMakeFromData(sk_sp<SkData> data, int ttcIndex) const override { if (ttcIndex != 0) { return nullptr; } SkUniqueCFRef<CTFontRef> ct = ctfont_from_skdata(data, ttcIndex); if (!ct) { return nullptr; } return SkTypeface_Mac::Make(std::move(ct), OpszVariation(), SkMemoryStream::Make(std::move(data))); } sk_sp<SkTypeface> onMakeFromStreamIndex(std::unique_ptr<SkStreamAsset> stream, int ttcIndex) const override { if (ttcIndex != 0) { return nullptr; } sk_sp<SkData> data = skdata_from_skstreamasset(stream->duplicate()); if (!data) { return nullptr; } SkUniqueCFRef<CTFontRef> ct = ctfont_from_skdata(std::move(data), ttcIndex); if (!ct) { return nullptr; } return SkTypeface_Mac::Make(std::move(ct), OpszVariation(), std::move(stream)); } sk_sp<SkTypeface> onMakeFromStreamArgs(std::unique_ptr<SkStreamAsset> stream, const SkFontArguments& args) const override { // TODO: Use CTFontManagerCreateFontDescriptorsFromData when available. int ttcIndex = args.getCollectionIndex(); if (ttcIndex != 0) { return nullptr; } sk_sp<SkData> data = skdata_from_skstreamasset(stream->duplicate()); if (!data) { return nullptr; } SkUniqueCFRef<CTFontRef> ct = ctfont_from_skdata(std::move(data), ttcIndex); if (!ct) { return nullptr; } SkUniqueCFRef<CFArrayRef> axes(CTFontCopyVariationAxes(ct.get())); CTFontVariation ctVariation = SkCTVariationFromSkFontArguments(ct.get(), axes.get(), args); SkUniqueCFRef<CTFontRef> ctVariant; if (ctVariation.variation) { SkUniqueCFRef<CFMutableDictionaryRef> attributes( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); CFDictionaryAddValue(attributes.get(), kCTFontVariationAttribute, ctVariation.variation.get()); SkUniqueCFRef<CTFontDescriptorRef> varDesc( CTFontDescriptorCreateWithAttributes(attributes.get())); ctVariant.reset(CTFontCreateCopyWithAttributes(ct.get(), 0, nullptr, varDesc.get())); } else { ctVariant.reset(ct.release()); } if (!ctVariant) { return nullptr; } return SkTypeface_Mac::Make(std::move(ctVariant), ctVariation.opsz, std::move(stream)); } sk_sp<SkTypeface> onMakeFromFile(const char path[], int ttcIndex) const override { if (ttcIndex != 0) { return nullptr; } sk_sp<SkData> data = SkData::MakeFromFileName(path); if (!data) { return nullptr; } return this->onMakeFromData(std::move(data), ttcIndex); } sk_sp<SkTypeface> onLegacyMakeTypeface(const char familyName[], SkFontStyle style) const override { if (familyName) { familyName = map_css_names(familyName); } sk_sp<SkTypeface> face = create_from_name(familyName, style); if (face) { return face; } static SkTypeface* gDefaultFace; static SkOnce lookupDefault; static const char FONT_DEFAULT_NAME[] = "Lucida Sans"; lookupDefault([]{ gDefaultFace = create_from_name(FONT_DEFAULT_NAME, SkFontStyle()).release(); }); return sk_ref_sp(gDefaultFace); } }; sk_sp<SkFontMgr> SkFontMgr_New_CoreText(CTFontCollectionRef fontCollection) { return sk_make_sp<SkFontMgr_Mac>(fontCollection); } #endif//defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
39.261146
103
0.658258
JimmySoftware
f5b37d1b06dc760e0ba78f9280eeca201e8afdef
3,200
cpp
C++
ExplorerXP/TextUtil.cpp
avrionov/explorerxp
c68bf161bb77bf5c9b3476be0e795d23bb0b6b5f
[ "Apache-2.0" ]
12
2016-11-10T01:21:48.000Z
2022-02-16T00:03:50.000Z
ExplorerXP/TextUtil.cpp
avrionov/explorerxp
c68bf161bb77bf5c9b3476be0e795d23bb0b6b5f
[ "Apache-2.0" ]
4
2021-05-28T03:58:27.000Z
2022-01-02T13:13:36.000Z
ExplorerXP/TextUtil.cpp
avrionov/explorerxp
c68bf161bb77bf5c9b3476be0e795d23bb0b6b5f
[ "Apache-2.0" ]
2
2016-12-21T15:06:39.000Z
2022-01-26T08:43:44.000Z
/* Copyright 2002-2020 Nikolay Avrionov. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "stdafx.h" #include "TextUtil.h" #include "SplitPath.h" #include "Resource.h" #include "globals.h" void MakeUpper (CString &str) { int last = str.GetLength (); /*int ext_pos = str.ReverseFind ('.'); if (ext_pos != -1) last = ext_pos;*/ for (int i = 0; i < last; i++) str.SetAt (i, _totupper (str[i])); } void TitleCase (CString& str) { if (str.GetLength () == 0) return; str.MakeLower (); bool bNewWord = true; int last = str.GetLength (); /* int ext_pos = str.ReverseFind ('.'); if (ext_pos != -1) last = ext_pos;*/ for (int i = 0; i < last; i++) { if (_istalpha (str[i])) { if (bNewWord) { bNewWord = false; str.SetAt (i, _totupper (str[i])); } } else bNewWord = true; } } void ToggleCase (CString& str) { if (str.GetLength () == 0) return; MakeUpper (str); bool bNewWord = true; int last = str.GetLength (); /*int ext_pos = str.ReverseFind ('.'); if (ext_pos != -1) last = ext_pos;*/ for (int i = 0; i < last; i++) { if (_istalpha (str[i])) { if (bNewWord) { bNewWord = false; str.SetAt (i, _tolower (str[i])); } } else bNewWord = true; } } void SentenceCase (CString& str) { if (str.GetLength () == 0) return; str.MakeLower (); str.SetAt (0, _toupper (str[0])); } void ChangeCase (int iCmd , CString &str) { switch (iCmd) { case ID_SENTENCECASE: SentenceCase (str); break; case ID_LOWERCASE: str.MakeLower (); break; case ID_UPPERCASE: MakeUpper (str); break; case ID_TITLECASE: TitleCase (str); break; case ID_TOGGLECASE: ToggleCase (str); break; } } void Space2Underscore (CString & str) { while (str.Replace (' ','_')); } void Underscore2Space (CString & str) { while (str.Replace ('_',' ')); } void Convert202Space (CString & str) { while (str.Replace (_T("%20"), _T(" "))); } void ConvertPoint2Space (CString & str, bool bExtentions) { if (bExtentions) { CSplitPath path (str); CString tmp; tmp = path.GetDrive(); tmp += path.GetDir(); tmp += path.GetFName(); while (tmp.Replace (_T("."), _T(" "))); tmp += path.GetExt(); str = tmp; } else while (str.Replace (_T("."), _T(" "))); } void ConvertSpaces (int iCmd, CString &str, bool bExtentions) { switch (iCmd) { case ID_CONVERT20TOSPACE: Convert202Space (str); break; case ID_CONVERTUNDERSCORETOSPACE: Underscore2Space (str); break; case ID_CONVERTSPACETOUNDERSCORE: Space2Underscore (str); break; case ID_CONVERTPOINTTOSPACE: ConvertPoint2Space (str, bExtentions); break; } }
17.486339
74
0.632188
avrionov
f5b442608e25181a2e86f9403215f627de5eb23e
305
hpp
C++
src/renderbufferformat.hpp
mharrys/gust
db458cd604d5d560844c0f7c2364f098fd6937a0
[ "MIT" ]
6
2016-07-25T06:44:23.000Z
2020-11-08T11:19:11.000Z
src/renderbufferformat.hpp
mharrys/gust
db458cd604d5d560844c0f7c2364f098fd6937a0
[ "MIT" ]
null
null
null
src/renderbufferformat.hpp
mharrys/gust
db458cd604d5d560844c0f7c2364f098fd6937a0
[ "MIT" ]
1
2019-06-05T13:02:32.000Z
2019-06-05T13:02:32.000Z
#ifndef RENDERBUFFERFORMAT_HPP_INCLUDED #define RENDERBUFFERFORMAT_HPP_INCLUDED namespace gst { // Supported renderbuffer storage formats. enum class RenderbufferFormat { DEPTH_COMPONENT16, DEPTH_COMPONENT24, DEPTH_COMPONENT32, DEPTH_COMPONENT32F }; } #endif
19.0625
46
0.727869
mharrys
f5b6db362dcc5ecd02e6ee4a7395142a99910b9b
6,560
cpp
C++
video__win32__dx5_mouse.cpp
poikilos/golgotha
d3184dea6b061f853423e0666dba23218042e5ba
[ "CC0-1.0" ]
5
2015-12-09T20:37:49.000Z
2021-08-10T08:06:29.000Z
video__win32__dx5_mouse.cpp
poikilos/golgotha
d3184dea6b061f853423e0666dba23218042e5ba
[ "CC0-1.0" ]
13
2021-09-20T16:25:30.000Z
2022-03-17T04:59:40.000Z
video__win32__dx5_mouse.cpp
poikilos/golgotha
d3184dea6b061f853423e0666dba23218042e5ba
[ "CC0-1.0" ]
5
2016-01-04T22:54:22.000Z
2021-09-20T16:09:03.000Z
/********************************************************************** <BR> This file is part of Crack dot Com's free source code release of Golgotha. <a href="http://www.crack.com/golgotha_release"> <BR> for information about compiling & licensing issues visit this URL</a> <PRE> If that doesn't help, contact Jonathan Clark at golgotha_source@usa.net (Subject should have "GOLG" in it) ***********************************************************************/ #include "pch.h" #include "video/win32/dx5_util.h" #include "video/win32/dx5_mouse.h" #include "image/context.h" #include "video/win32/dx5_error.h" #include <ddraw.h> dx5_mouse_class::dx5_mouse_class(i4_bool page_flipped) : page_flipped(page_flipped) { cursor.pict=0; cursor.hot_x=0; cursor.hot_y=0; last.save_buffer=0; current.save_buffer=0; last_was_gdi=i4_T; } void dx5_mouse_class::set_cursor(i4_cursor_class * c) { /*if (cursor.pict) { delete cursor.pict; cursor.pict=0; }*/ if (c && c->pict) { int cw=c->pict->width(), ch=c->pict->height(); i4_draw_context_class context(0,0, cw-1, ch-1); i4_dx5_image_class * dx5_image=(i4_dx5_image_class *)cursor.pict; if ((!cursor.pict)||(cw!=cursor.pict->width())||ch!=cursor.pict->height()) { delete cursor.pict; cursor.pict=0; dx5_image = new i4_dx5_image_class(cw, ch, DX5_SYSTEM_RAM | DX5_CLEAR); //currently, it is not possible to use vram, as we'll lose the cursor on //DDERR_SURFACELOST cursor = *c; cursor.pict = dx5_image; } //setup the color-key value for the mouse (black) DDCOLORKEY colorkey; memset(&colorkey,0,sizeof(DDCOLORKEY)); //i4_color converted_transparent = c->pict->pal.pal->convert(c->trans,&dx5_common.i4_fmt_565); colorkey.dwColorSpaceLowValue = 0; //converted_transparent; colorkey.dwColorSpaceHighValue = 0; //converted_transparent; dx5_image->surface->SetColorKey(DDCKEY_SRCBLT,&colorkey); short w=dx5_image->width()-1; short h=dx5_image->height()-1; i4_draw_context_class ctx(0,0,w,h); //all drawing functions, including the contexts always _include_ //the rightmost pixel //so if the context and the requested operation is greater than the //image nothing is clipped away and we silently overwrite some //memory. (remove the -1 up here and see how the kernel likes you....) dx5_image->bar(0,0,w,h, 0,ctx); //change everything to black dx5_image->lock(); c->pict->put_image_trans(cursor.pict, 0,0, c->trans, context); dx5_image->unlock(); } else { delete cursor.pict; cursor.pict=0; //hide cursor } i4_bool g=primary_is_gdi(); last_was_gdi=!g; current.isgdi=g; last.isgdi=!g; } dx5_mouse_class::~dx5_mouse_class() { if (cursor.pict) { delete cursor.pict; cursor.pict=0; } } i4_bool dx5_mouse_class::primary_is_gdi() { //i4_bool ret; LPDIRECTDRAWSURFACE lpgdi=0; LPDIRECTDRAWSURFACE3 lpgdi3=0; //LPSURFACEDESC lpsd=0; //DDSCAPS caps; //dx5_common.primary_surface->GetCaps(&caps); //if (caps.dwCaps&DDSCAPS_PRIMARYSURFACE) // return i4_T; //else // return i4_F; i4_dx5_check(dx5_common.ddraw->GetGDISurface(&lpgdi)); i4_dx5_check(lpgdi->QueryInterface(IID_IDirectDrawSurface3,(void * *)&lpgdi3)); if (lpgdi) { lpgdi->Release(); } if (dx5_common.primary_surface==lpgdi3) { if (lpgdi3) { lpgdi3->Release(); } return i4_T; } else { if (lpgdi3) { lpgdi3->Release(); } return i4_F; } } void dx5_mouse_class::save_and_draw(int x, int y) { if (!cursor.pict) { return ; } // i4_bool g=primary_is_gdi(); // if (page_flipped&&(g==last_was_gdi)) //current frame buffer same as last: something has happenened // { // // } //i4_warning("TRACE: Mouse first part"); if (!current.save_buffer || current.save_buffer->width() != cursor.pict->width() || current.save_buffer->height() != cursor.pict->height()) { if (current.save_buffer) { delete current.save_buffer; } current.save_buffer=new i4_dx5_image_class(cursor.pict->width(), cursor.pict->height(), DX5_VRAM); } current.x=x - cursor.hot_x; current.y=y - cursor.hot_y; if (current.x<0) { current.x=0; } if (current.y<0) { current.y=0; } RECT src; i4_display_class * disp=i4_current_app->get_display(); //PG: Not having these two conditions allows the cursor //to move all the way to the right or bottom of the screen, //but may cause trouble with the BltFast operation if (current.x+cursor.pict->width()>disp->width()) { current.x=disp->width()-cursor.pict->width()-1; } if (current.y+cursor.pict->height()>disp->height()) { current.y=disp->height()-cursor.pict->height()-1; } src.left = current.x; src.right = current.x + cursor.pict->width(); src.top = current.y; src.bottom = current.y + cursor.pict->height(); HRESULT hr=0; //i4_warning("TRACE: Mouse second part"); //no i4_dx5_check here as we allways get an error when the cursor is outside the window if (i4_dx5_check(hr=current.save_buffer->surface->BltFast(0,0, dx5_common.back_surface, &src,DDBLTFAST_NOCOLORKEY|DDBLTFAST_WAIT))) { //i4_warning("TRACE: Mouse third part"); i4_dx5_check(dx5_common.back_surface->BltFast(current.x, current.y, ((i4_dx5_image_class *)cursor.pict)->surface,0, DDBLTFAST_SRCCOLORKEY|DDBLTFAST_WAIT)); } else { if (current.save_buffer&&current.save_buffer->surface) { current.save_buffer->surface->Restore(); } if (last.save_buffer&&last.save_buffer->surface) { last.save_buffer->surface->Restore(); } } if (page_flipped) { save_struct tmp=current; current=last; last=tmp; tmp.save_buffer=0; } } void dx5_mouse_class::restore() { if (current.save_buffer) { RECT src; src.left = 0; src.right = cursor.pict->width(); src.top = 0; src.bottom = cursor.pict->height(); i4_bool g=primary_is_gdi(); if (page_flipped&&(g==current.isgdi)) //current frame buffer same as last: something has happenened { dx5_common.primary_surface->BltFast(current.x,current.y,current.save_buffer->surface,&src, DDBLTFAST_NOCOLORKEY|DDBLTFAST_WAIT); current.isgdi=!current.isgdi; last.isgdi=!last.isgdi; } dx5_common.back_surface->BltFast(current.x, current.y, current.save_buffer->surface, &src, DDBLTFAST_NOCOLORKEY); //DDBLTFAST_NOCOLORKEY|DDBLTFAST_WAIT } }
26.885246
133
0.653049
poikilos
f5bb9e00f615f3bb76cc87691eb8a7aab5dc1fd4
7,660
hpp
C++
include/Core/Transform/Polygon.hpp
mjopenglsdl/ObEngine
a56116c8cdf1ce30b7fadb749f8ca4df54e5ee36
[ "MIT" ]
null
null
null
include/Core/Transform/Polygon.hpp
mjopenglsdl/ObEngine
a56116c8cdf1ce30b7fadb749f8ca4df54e5ee36
[ "MIT" ]
null
null
null
include/Core/Transform/Polygon.hpp
mjopenglsdl/ObEngine
a56116c8cdf1ce30b7fadb749f8ca4df54e5ee36
[ "MIT" ]
null
null
null
#pragma once #include <functional> #include <memory> #include <optional> #include <vector> #include <Transform/Movable.hpp> #include <Transform/Rect.hpp> #include <Transform/UnitBasedObject.hpp> #include <Transform/UnitVector.hpp> namespace obe::Transform { class Polygon; using point_index_t = unsigned int; class PolygonPoint : public UnitVector { private: friend class Polygon; Polygon* m_parent; point_index_t rw_index; public: enum class RelativePositionFrom { Point0, Centroid }; explicit PolygonPoint(Polygon* parent, unsigned int index); explicit PolygonPoint(Polygon* parent, unsigned int index, const Transform::UnitVector& position); const point_index_t& index = rw_index; void remove() const; double distance(const Transform::UnitVector& position) const; UnitVector getRelativePosition(RelativePositionFrom from) const; void setRelativePosition(RelativePositionFrom from, const Transform::UnitVector& position); void move(const Transform::UnitVector& position); }; class PolygonSegment { public: const PolygonPoint& first; const PolygonPoint& second; double getAngle() const; double getLength() const; PolygonSegment(const PolygonPoint& first, const PolygonPoint& second); }; using PolygonPath = std::vector<std::unique_ptr<PolygonPoint>>; /** * \brief Class used for all Collisions in the engine, it's a Polygon containing n points * @Bind */ class Polygon : public Transform::UnitBasedObject, public Transform::Movable { protected: friend class PolygonPoint; PolygonPath m_points; float m_angle = 0; void resetUnit(Transform::Units unit) override; public: static constexpr double DefaultTolerance = 0.02; /** * \brief Adds a new Point to the Polygon at Position (x, y) * \param position Coordinate of the Position where to add the new Point * \param pointIndex Index where to insert the new Point, Use pointIndex = -1 <DefaultArg> to insert at the end (between last and first Point) */ void addPoint(const Transform::UnitVector& position, int pointIndex = -1); /** * \brief Finds the closest Line from the given Position * \param position Position used to get the closest Line * \return The index of the line that is the closest one of the given Position (Line between point 0 and point 1 is index 0) */ PolygonSegment findClosestSegment(const Transform::UnitVector& position); /** * \brief Find the closest Point from the given Position(x, y) * \param position Coordinate of the Position used to get the closest Point * \param neighbor Get the closest neighboor of the closest Point instead of the Point * \param excludedPoints A std::vector containing points you want to exclude from the calculus (Not used in neighboor check step) * \return The index of the Point (or one of its neighboor) that is the closest one of the given Position */ PolygonPoint& findClosestPoint(const Transform::UnitVector& position, bool neighbor = false, const std::vector<point_index_t>& excludedPoints = {}); /** * \brief Get all the Points of the Polygon * \return A Path containing all the Points of the Polygon */ PolygonPath& getAllPoints(); /** * \brief Get the position of the Master Point (centroid) of the Polygon * \return An UnitVector containing the position of the Master Point (centroid) of the Polygon */ Transform::UnitVector getCentroid() const; /** * \brief Get the number of points in the Polygon * \return An unsigned int containing the number of points of the Polygon */ unsigned int getPointsAmount() const; /** * \brief Get the Position of the first point (index 0) of the Polygon * \return An UnitVector containing the position of the first point of the Polygon */ Transform::UnitVector getPosition() const override; /** * \brief Gets the current angle of the PolygonalCollider * \return A float containing the value of the current angle of the PolygonalCollider */ float getRotation() const; /* * \brief Gets the segment of the Polygon at index segment * \param segment Index of the Segment to get * \return The segment of the Polygon at index segment */ PolygonSegment getSegment(point_index_t segment); /** * \brief Get if the Position (x, y) is on one of the side of the Polygon * \param position Coordinate of the Position to test * \param tolerance * \return An unsigned int containing the index of the side containing the position or -1 if not found */ std::optional<PolygonSegment> getSegmentContainingPoint(const Transform::UnitVector& position, double tolerance = DefaultTolerance); /** * \brief Check if the MasterPoint of the Polygon is on Position (x - tolerance <= x <= x + tolerance, y - tolerance <= tolerance <= y + tolerance) * \param position Coordinate of the Position to test * \param tolerance Position tolerance, bigger number means less precise * \return true if the MasterPoint is on the given Positon, false otherwise */ bool isCentroidAroundPosition(const Transform::UnitVector& position, const Transform::UnitVector& tolerance) const; /** * \brief Check if a point of the Polygon is on Position (x - tolerance <= x <= x + tolerance, y - tolerance <= tolerance <= y + tolerance) * \param position Coordinate of the Position to test * \param tolerance Position tolerance, bigger number means less precise * \return An unsigned int containing the index of the point containing the position or -1 if not found */ std::optional<PolygonPoint*> getPointAroundPosition(const Transform::UnitVector& position, const Transform::UnitVector& tolerance); /** * \brief Moves the Polygon (relative to the current position) * \param position UnitVector containing the offset to move the Polygon */ void move(const Transform::UnitVector& position) override; /** * \brief Adds an angle to the current angle of the PolygonalCollider (will rotate all points around the given origin) * \param angle Angle to add to the PolygonalCollider * \param origin Origin to rotate all the points around */ void rotate(float angle, Transform::UnitVector origin); /** * \brief Sets the new position of the Polygon (using the point at index 0) * \param position UnitVector containing the new Position of the Polygon */ void setPosition(const Transform::UnitVector& position) override; /** * \brief Sets the angle of the PolygonalCollider (will rotate all points around the given origin) * \param angle Angle to set to the PolygonalCollider * \param origin Origin to rotate all the points around */ void setRotation(float angle, Transform::UnitVector origin); void setPositionFromCentroid(const Transform::UnitVector& position); PolygonPoint& operator[](point_index_t i); PolygonPoint& get(point_index_t i); Rect getBoundingBox() const; }; }
45.595238
156
0.663316
mjopenglsdl
f5bd16a09b8163855c372db305ffda78fa3be8f2
4,259
cpp
C++
swg_generated/cpp/qt5cpp/client/SWGMarketInfo.cpp
Reclusive-Trader/upbit-client
ca1fb02c9d4e22f6d726baf30a455a235ce0324a
[ "MIT" ]
46
2021-01-07T14:53:26.000Z
2022-03-25T10:11:16.000Z
swg_generated/cpp/qt5cpp/client/SWGMarketInfo.cpp
Reclusive-Trader/upbit-client
ca1fb02c9d4e22f6d726baf30a455a235ce0324a
[ "MIT" ]
4
2021-02-20T05:21:29.000Z
2022-03-01T12:53:02.000Z
swg_generated/cpp/qt5cpp/client/SWGMarketInfo.cpp
Reclusive-Trader/upbit-client
ca1fb02c9d4e22f6d726baf30a455a235ce0324a
[ "MIT" ]
59
2021-01-07T11:58:10.000Z
2022-02-15T06:11:33.000Z
/** * Upbit Open API * ## REST API for Upbit Exchange - Base URL: [https://api.upbit.com] - Official Upbit API Documents: [https://docs.upbit.com] - Official Support email: [open-api@upbit.com] * * OpenAPI spec version: 1.0.0 * Contact: ujhin942@gmail.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ #include "SWGMarketInfo.h" #include "SWGHelpers.h" #include <QJsonDocument> #include <QJsonArray> #include <QObject> #include <QDebug> namespace Swagger { SWGMarketInfo::SWGMarketInfo(QString json) { init(); this->fromJson(json); } SWGMarketInfo::SWGMarketInfo() { init(); } SWGMarketInfo::~SWGMarketInfo() { this->cleanup(); } void SWGMarketInfo::init() { market = new QString(""); m_market_isSet = false; korean_name = new QString(""); m_korean_name_isSet = false; english_name = new QString(""); m_english_name_isSet = false; market_warning = new QString(""); m_market_warning_isSet = false; } void SWGMarketInfo::cleanup() { if(market != nullptr) { delete market; } if(korean_name != nullptr) { delete korean_name; } if(english_name != nullptr) { delete english_name; } if(market_warning != nullptr) { delete market_warning; } } SWGMarketInfo* SWGMarketInfo::fromJson(QString json) { QByteArray array (json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); return this; } void SWGMarketInfo::fromJsonObject(QJsonObject pJson) { ::Swagger::setValue(&market, pJson["market"], "QString", "QString"); ::Swagger::setValue(&korean_name, pJson["korean_name"], "QString", "QString"); ::Swagger::setValue(&english_name, pJson["english_name"], "QString", "QString"); ::Swagger::setValue(&market_warning, pJson["market_warning"], "QString", "QString"); } QString SWGMarketInfo::asJson () { QJsonObject obj = this->asJsonObject(); QJsonDocument doc(obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject SWGMarketInfo::asJsonObject() { QJsonObject obj; if(market != nullptr && *market != QString("")){ toJsonValue(QString("market"), market, obj, QString("QString")); } if(korean_name != nullptr && *korean_name != QString("")){ toJsonValue(QString("korean_name"), korean_name, obj, QString("QString")); } if(english_name != nullptr && *english_name != QString("")){ toJsonValue(QString("english_name"), english_name, obj, QString("QString")); } if(market_warning != nullptr && *market_warning != QString("")){ toJsonValue(QString("market_warning"), market_warning, obj, QString("QString")); } return obj; } QString* SWGMarketInfo::getMarket() { return market; } void SWGMarketInfo::setMarket(QString* market) { this->market = market; this->m_market_isSet = true; } QString* SWGMarketInfo::getKoreanName() { return korean_name; } void SWGMarketInfo::setKoreanName(QString* korean_name) { this->korean_name = korean_name; this->m_korean_name_isSet = true; } QString* SWGMarketInfo::getEnglishName() { return english_name; } void SWGMarketInfo::setEnglishName(QString* english_name) { this->english_name = english_name; this->m_english_name_isSet = true; } QString* SWGMarketInfo::getMarketWarning() { return market_warning; } void SWGMarketInfo::setMarketWarning(QString* market_warning) { this->market_warning = market_warning; this->m_market_warning_isSet = true; } bool SWGMarketInfo::isSet(){ bool isObjectUpdated = false; do{ if(market != nullptr && *market != QString("")){ isObjectUpdated = true; break;} if(korean_name != nullptr && *korean_name != QString("")){ isObjectUpdated = true; break;} if(english_name != nullptr && *english_name != QString("")){ isObjectUpdated = true; break;} if(market_warning != nullptr && *market_warning != QString("")){ isObjectUpdated = true; break;} }while(false); return isObjectUpdated; } }
25.201183
174
0.669641
Reclusive-Trader
f5bf0ad176c860aed0ec40730959b6320c256315
35,812
cpp
C++
DT3LevelEditor/Animation/EdLevelAnimationWindow.cpp
nemerle/DT3
801615d507eda9764662f3a34339aa676170e93a
[ "MIT" ]
3
2016-01-27T13:17:18.000Z
2019-03-19T09:18:25.000Z
DT3LevelEditor/Animation/EdLevelAnimationWindow.cpp
nemerle/DT3
801615d507eda9764662f3a34339aa676170e93a
[ "MIT" ]
1
2016-01-28T14:39:49.000Z
2016-01-28T22:12:07.000Z
DT3LevelEditor/Animation/EdLevelAnimationWindow.cpp
adderly/DT3
e2605be091ec903d3582e182313837cbaf790857
[ "MIT" ]
3
2016-01-25T16:44:51.000Z
2021-01-29T19:59:45.000Z
//============================================================================== /// /// File: EdLevelAnimationWindow.cpp /// /// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved. /// /// This file is subject to the terms and conditions defined in /// file 'LICENSE.txt', which is part of this source code package. /// //============================================================================== // Editor include #include "EdLevelAnimationWindow.hpp" #include "EdLevelDocument.hpp" // Qt include #include <QtWidgets/qdrawutil.h> #include <QtWidgets/QStyle> #include <QtCore/QFile> #include <QtGui/QMouseEvent> #include <QtGui/QWheelEvent> // Engine includes #include "DT3Core/Types/Utility/MoreStrings.hpp" #include "DT3Core/Objects/ObjectBase.hpp" #include "DT3Core/Scripting/ScriptingKeyframesRoot.hpp" //============================================================================== //============================================================================== using namespace DT3; //============================================================================== //============================================================================== EdLevelAnimationWindow::EdLevelAnimationWindow(QWidget *parent, QToolBar *toolbar, EdLevelDocument *document) : QWidget (parent), _font("Arial", 9), _font_bold("Arial", 9, QFont::Bold), _fm(_font), _pixels_per_second(100), _time (0.0F), _scroll (0), _root (NULL), _thumb_image (":/images/thumb.png"), _keyframe_image (":/images/keyframe.png"), _keyframe_image_selected (":/images/keyframe_selected.png") { _document = document; _toolbar = toolbar; // // Actions and toolbar // _anim_play = new QAction(tr("&Play"), this); _anim_play->setIcon(QIcon(":/images/play.png")); _anim_play->setStatusTip(tr("Play")); connect(_anim_play, SIGNAL(triggered()), this, SLOT(onScriptPlay())); _anim_stop = new QAction(tr("&Play"), this); _anim_stop->setIcon(QIcon(":/images/stop.png")); _anim_stop->setStatusTip(tr("Play")); connect(_anim_stop, SIGNAL(triggered()), this, SLOT(onScriptStop())); toolbar->addAction(_anim_play); toolbar->addAction(_anim_stop); // // Set up window // _horz_scrollbar = new QScrollBar(Qt::Horizontal, this); _horz_scrollbar->setSingleStep(20); _vert_scrollbar = new QScrollBar(Qt::Vertical, this); _vert_scrollbar->setSingleStep(10); connect( _horz_scrollbar, SIGNAL(valueChanged(int)), this, SLOT(onScrollTime(int)) ); connect( _vert_scrollbar, SIGNAL(valueChanged(int)), this, SLOT(onScroll(int)) ); _time_min = new EdLevelLineEdit(this); _time_min->setText("-1"); _time_max = new EdLevelLineEdit(this); _time_max->setText("30"); connect( _time_min, SIGNAL(editingFinished()), this, SLOT(onChangeTimeRange()) ); connect( _time_max, SIGNAL(editingFinished()), this, SLOT(onChangeTimeRange()) ); _scroll_width = _vert_scrollbar->sizeHint().width(); _scroll_height = _horz_scrollbar->sizeHint().height(); setFocusPolicy(Qt::ClickFocus); } EdLevelAnimationWindow::~EdLevelAnimationWindow (void) { } //============================================================================== //============================================================================== void EdLevelAnimationWindow::onAnimPlay (void) { //_anim_timer.start(200, this); } void EdLevelAnimationWindow::onAnimStop (void) { //_anim_timer.stop(); } //============================================================================== //============================================================================== void EdLevelAnimationWindow::scanRoot (const std::shared_ptr<ScriptingKeyframesRoot> &root, std::vector<PlugEventCache> &plug_event_cache) { _root = root; // Get all of the plugs for the current node std::list<PlugBase*> plugs; root->all_plugs(plugs); FOR_EACH (j,plugs) { // We only care about outputs if ( !(**j).is_output() ) continue; // Make sure it's hooked up if ( !(**j).has_outgoing_connection() ) continue; // Check each outgoing connection const std::vector<PlugBase*> connections = (**j).outgoing_connections(); for (int k = 0; k < connections.size(); ++k) { // Get connected keyframes std::shared_ptr<ScriptingKeyframes> keyframes = checked_cast<ScriptingKeyframes>( checked_cast<ScriptingKeyframes>(connections[k]->owner()->shared_from_this()) ); if (!keyframes) continue; // Get Keyframes output PlugBase *keyframes_out_plug = keyframes->plug_by_name("Out"); if (keyframes_out_plug) { // Make sure output is connected if (!keyframes_out_plug->has_outgoing_connection()) continue; // Get the FIRST output connection PlugBase* next_input_plug = keyframes_out_plug->outgoing_connections()[0]; // Record the nodes PlugEventCache animated_node; animated_node._node = checked_static_cast<PlugNode>(next_input_plug->owner()->shared_from_this()); animated_node._plug = next_input_plug; animated_node._keyframes = keyframes; plug_event_cache.push_back(animated_node); } // Get Keyframes output Event *keyframes_out_event = keyframes->event_by_name("Out"); if (keyframes_out_event) { // Make sure output is connected if (!keyframes_out_event->has_outgoing_connection()) continue; // Get the FIRST output connection Event* next_input_event = keyframes_out_event->outgoing_connections()[0]; // Record the nodes PlugEventCache animated_node; animated_node._node = checked_static_cast<PlugNode>(next_input_event->owner()->shared_from_this()); animated_node._event = next_input_event; animated_node._keyframes = keyframes; plug_event_cache.push_back(animated_node); } } } } //============================================================================== //============================================================================== void EdLevelAnimationWindow::layoutItems (std::vector<PlugEventCache> &plug_event_cache) { std::shared_ptr<PlugNode> last_node; int ypos = 0; for (int i = 0; i < plug_event_cache.size(); ++i) { if (plug_event_cache[i]._node != last_node) { last_node = plug_event_cache[i]._node; PlugEventCache c; //c._node = last_node; c._title = last_node->full_name(); c._ypos = ypos; plug_event_cache.insert (plug_event_cache.begin() + i, c); ypos += NODE_ITEM_HEIGHT; ++i; } if (plug_event_cache[i]._plug) plug_event_cache[i]._title = MoreStrings::captialize_and_format(plug_event_cache[i]._plug->name()); else plug_event_cache[i]._title = MoreStrings::captialize_and_format(plug_event_cache[i]._event->name()); plug_event_cache[i]._ypos = ypos; ypos += NODE_ITEM_HEIGHT; } _nodes_height = ypos; } //============================================================================== //============================================================================== void EdLevelAnimationWindow::scanRelevantNodes (const std::list<std::shared_ptr<PlugNode>> &selection_list) { _root.reset(); // // Build a giant list of all of the relevant nodes breadth-first // std::list<std::shared_ptr<PlugNode>> visited_nodes = selection_list; std::vector<PlugEventCache> plug_event_cache; FOR_EACH (i,visited_nodes) { // Check if node is a root if ((*i)->isa(ScriptingKeyframesRoot::kind())) { std::shared_ptr<ScriptingKeyframesRoot> root = checked_static_cast<ScriptingKeyframesRoot>(*i); scanRoot (root, plug_event_cache); layoutItems (plug_event_cache); if (_plug_event_cache != plug_event_cache) { _plug_event_cache = plug_event_cache; } return; } // Special case components too if ((*i)->isa(ObjectBase::kind())) { std::shared_ptr<ObjectBase> node_base = checked_static_cast<ObjectBase>(*i); for (int i = 0; i < ComponentBase::NUM_COMPONENT_TYPES; ++i) { std::shared_ptr<ComponentBase> component_base = node_base->component_by_type ( (ComponentBase::ComponentType) i); if (component_base) { // Check if we already visited the node auto j = std::find(visited_nodes.begin(), visited_nodes.end(), component_base); if (j != visited_nodes.end()) continue; visited_nodes.push_back(component_base); } } } // Get all of the plugs for the current node std::list<PlugBase*> plugs; (**i).all_plugs(plugs); FOR_EACH (j, plugs) { // We only care about inputs if ( !(**j).is_input() ) continue; // Make sure it's hooked up if ( !(**j).has_incoming_connection() ) continue; // Get the node std::shared_ptr<PlugNode> node = checked_static_cast<PlugNode>((**j).incoming_connection()->owner()->shared_from_this()); if (!node) continue; // Check if we already visited the node auto k = std::find(visited_nodes.begin(), visited_nodes.end(), node); if (k == visited_nodes.end()) visited_nodes.push_back(node); } // Get all of the events for the current node std::list<Event*> events; (**i).all_events(events); FOR_EACH (k, events) { // We only care about inputs if ( !(**k).is_input() ) continue; // Make sure it's hooked up if ( !(**k).has_incoming_connection() ) continue; // Get the nodes const std::vector<Event*> events = (*k)->incoming_connections(); FOR_EACH (i, events) { std::shared_ptr<PlugNode> node = checked_static_cast<PlugNode>((*i)->owner()->shared_from_this()); auto k = std::find(visited_nodes.begin(), visited_nodes.end(), node); if (k == visited_nodes.end()) visited_nodes.push_back(node); } } } } //============================================================================== //============================================================================== void EdLevelAnimationWindow::itemRect(PlugEventCache &n, QRect &tr, QRect &r) const { if (n._node) { const int INDENT = 15; tr = QRect(INDENT, n._ypos, NODE_ITEM_WIDTH-INDENT, NODE_ITEM_HEIGHT); r = QRect(0, n._ypos, NODE_ITEM_WIDTH, NODE_ITEM_HEIGHT); } else { const int INDENT = 5; tr = QRect(INDENT, n._ypos, NODE_ITEM_WIDTH-INDENT, NODE_ITEM_HEIGHT); r = QRect(0, n._ypos, NODE_ITEM_WIDTH, NODE_ITEM_HEIGHT); } } //============================================================================== //============================================================================== void EdLevelAnimationWindow::thumbRect (QRect &r) const { if (_root) { DTfloat t = _root->time(); int xpos = timeToPosition(t); r = QRect(xpos - _thumb_image.width()/2,0, _thumb_image.width(),_thumb_image.height()); } else { r = QRect(_thumb_image.width()/2,0, _thumb_image.width(),_thumb_image.height()); } } //============================================================================== //============================================================================== void EdLevelAnimationWindow::selectionRect (QRect &r) const { QPoint selection_start = _start_point + QPoint(timeToPosition(_time) - NODE_ITEM_WIDTH, -TITLE_HEIGHT + _scroll); QPoint selection_end = _end_point + QPoint(timeToPosition(_time) - NODE_ITEM_WIDTH, -TITLE_HEIGHT + _scroll); DTfloat xmin = selection_start.x(); DTfloat xmax = selection_end.x(); if (xmin > xmax) std::swap(xmin,xmax); DTfloat ymin = selection_start.y(); DTfloat ymax = selection_end.y(); if (ymin > ymax) std::swap(ymin,ymax); r = QRect( xmin, ymin, xmax - xmin, ymax - ymin); } void EdLevelAnimationWindow::keyRect (PlugEventCache &p, int k, QRect &rk) const { QRect tr, r; itemRect(p, tr, r); DTfloat kf_time = p._keyframes->key_time(k); int xpos = timeToPosition(kf_time); rk = QRect( xpos - _keyframe_image.width()/2, r.center().y() - _keyframe_image.height()/2, _keyframe_image.width(), _keyframe_image.height() ); } //============================================================================== //============================================================================== int EdLevelAnimationWindow::timeToPosition (DTfloat seconds) const { return _pixels_per_second * seconds; } DTfloat EdLevelAnimationWindow::positionToTime (int position) const { return static_cast<DTfloat>(position) / static_cast<DTfloat>(_pixels_per_second); } //============================================================================== //============================================================================== void EdLevelAnimationWindow::onSelectionChanged (const std::list<std::shared_ptr<PlugNode>> &selection_list) { blockSignals(true); scanRelevantNodes(selection_list); blockSignals(false); update(); } //============================================================================== //============================================================================== void EdLevelAnimationWindow::resizeEvent (QResizeEvent *event) { _title = QRect(0,0,NODE_ITEM_WIDTH, TITLE_HEIGHT); _timeline = QRect(NODE_ITEM_WIDTH,0,rect().width() - NODE_ITEM_WIDTH - _scroll_width, TITLE_HEIGHT); _nodes = QRect(0,TITLE_HEIGHT, NODE_ITEM_WIDTH, rect().height() - TITLE_HEIGHT); _controls = QRect(NODE_ITEM_WIDTH, TITLE_HEIGHT, rect().width() - NODE_ITEM_WIDTH - _scroll_width, rect().height() - TITLE_HEIGHT - _scroll_height); // Place scrollbars _horz_scrollbar->setGeometry(NODE_ITEM_WIDTH, rect().height() - _scroll_height, rect().width() - NODE_ITEM_WIDTH - _scroll_width, _scroll_height); _vert_scrollbar->setGeometry(rect().width() - _scroll_width, TITLE_HEIGHT, _scroll_width, rect().height() - TITLE_HEIGHT - _scroll_height); // Scale scrollbars int page_step = rect().height() - TITLE_HEIGHT - _scroll_height; _vert_scrollbar->setPageStep(page_step); _vert_scrollbar->setRange(0,_nodes_height - page_step); // Scale fields _time_min->setGeometry(NODE_ITEM_WIDTH, rect().height() - _scroll_height - TIME_FIELD_HEIGHT, TIME_FIELD_WIDTH, TIME_FIELD_HEIGHT); _time_max->setGeometry(rect().width() - _scroll_width - TIME_FIELD_WIDTH, rect().height() - _scroll_height - TIME_FIELD_HEIGHT, TIME_FIELD_WIDTH, TIME_FIELD_HEIGHT); onChangeTimeRange(); } //============================================================================== //============================================================================== void EdLevelAnimationWindow::onScrollTime(int time) { _time = positionToTime(time); update(); } void EdLevelAnimationWindow::onScroll(int scroll) { _scroll = scroll; update(); } void EdLevelAnimationWindow::onChangeTimeRange() { _time_min_sec = _time_min->text().toFloat(); _time_max_sec = _time_max->text().toFloat(); if (_time < _time_min_sec) _time = _time_min_sec; if (_time > _time_max_sec) _time = _time_max_sec; int page_step = _controls.width(); _horz_scrollbar->setPageStep(page_step); _horz_scrollbar->setRange( timeToPosition(_time_min_sec), timeToPosition(_time_max_sec) - page_step); update(); } //============================================================================== //============================================================================== void EdLevelAnimationWindow::mouseDoubleClickEvent (QMouseEvent *event) { event->accept(); } void EdLevelAnimationWindow::mousePressEvent(QMouseEvent *event) { emit doUndoBlock(); _start_point = _last_point = _end_point = event->pos(); // Translate into timeline space QPoint local_pos = _end_point + QPoint(timeToPosition(_time) - NODE_ITEM_WIDTH, -TITLE_HEIGHT + _scroll); // Check click in thumb if (_timeline.contains(event->pos())) { setMode(MODE_DRAGGING_THUMB); if (_root) { DTfloat t = positionToTime(local_pos.x()); emit doCommand(QString("SetProp \"") + _root->full_name().c_str() + ".Time_Out\" " + MoreStrings::cast_to_string(t).c_str()); } update(); } else if (_controls.contains(_end_point)) { if ( (event->buttons() & Qt::LeftButton) && ( (event->buttons() & Qt::MidButton) || (event->modifiers() & Qt::ALT)) ) { setMode(MODE_ZOOMING); } else { // Check all keyframes to see if one is clicked for (int i = 0; i < _plug_event_cache.size(); ++i) { if (!_plug_event_cache[i]._node || !_plug_event_cache[i]._keyframes) continue; for (int k = 0; k < getNumKeys(_plug_event_cache[i]); ++k) { QRect rk; keyRect (_plug_event_cache[i], k, rk); if (rk.contains(local_pos)) { int id = _plug_event_cache[i]._keyframes->key_id(k); // Check select new keyframe if (!isSelected(_plug_event_cache[i], id)) { clearSelected(); setSelected(_plug_event_cache[i], id, true); } setMode(MODE_DRAGGING); update(); return; } } } setMode(MODE_DRAG_SELECTING); } } else { setMode(MODE_NONE); } } void EdLevelAnimationWindow::mouseMoveEvent(QMouseEvent *event) { _end_point = event->pos(); //QPoint dist = _end_point - _start_point; QPoint delta = _end_point - _last_point; // Translate into timeline space QPoint local_pos = _end_point + QPoint(timeToPosition(_time) - NODE_ITEM_WIDTH, -TITLE_HEIGHT); switch (getMode()) { case MODE_DRAGGING_THUMB: if (_root) { DTfloat t = positionToTime(local_pos.x()); emit doCommand(QString("SetProp \"") + _root->full_name().c_str() + ".Time_Out\" " + MoreStrings::cast_to_string(t).c_str()); } update(); break; case MODE_DRAG_SELECTING: update(); // Just displaying selection rect break; case MODE_DRAGGING: // Check all keyframes to see if one is clicked for (int i = 0; i < _plug_event_cache.size(); ++i) { if (!_plug_event_cache[i]._node || !_plug_event_cache[i]._keyframes) continue; DTfloat dt = positionToTime(delta.x()); int num_keys = getNumKeys(_plug_event_cache[i]); // Since order can flip when keys are set, we start with the farther ahead points first // depending on direction of dt if (dt < 0.0F) { for (int k = 0; k < num_keys; ++k) { int id = _plug_event_cache[i]._keyframes->key_id(k); if (isSelected(_plug_event_cache[i], id)) { DTfloat current_time = _plug_event_cache[i]._keyframes->key_time(k); std::string cmd = "SetKeyframeTimeByID " + _plug_event_cache[i]._keyframes->full_name() + " " + MoreStrings::cast_to_string(id) + " " + MoreStrings::cast_to_string(current_time + dt); emit doCommand(cmd.c_str()); } } } else { for (int k = num_keys-1; k >= 0; --k) { int id = _plug_event_cache[i]._keyframes->key_id(k); if (isSelected(_plug_event_cache[i], id)) { DTfloat current_time = _plug_event_cache[i]._keyframes->key_time(k); std::string cmd = "SetKeyframeTimeByID " + _plug_event_cache[i]._keyframes->full_name() + " " + MoreStrings::cast_to_string(id) + " " + MoreStrings::cast_to_string(current_time + dt); emit doCommand(cmd.c_str()); } } } } update(); break; case MODE_ZOOMING: { DTfloat center_time_before = (_horz_scrollbar->value() + _controls.width() / 2) / static_cast<DTfloat>(_pixels_per_second); DTfloat zoom = -delta.y(); _pixels_per_second += zoom; if (_pixels_per_second < 5) _pixels_per_second = 5; else if (_pixels_per_second > 500) _pixels_per_second = 500; DTfloat center_time_after= (_horz_scrollbar->value() + _controls.width() / 2) / static_cast<DTfloat>(_pixels_per_second); _horz_scrollbar->setValue(_horz_scrollbar->value() - (center_time_after - center_time_before) * _pixels_per_second); onChangeTimeRange(); } break; default: break; }; _last_point = _end_point; } void EdLevelAnimationWindow::mouseReleaseEvent(QMouseEvent *event) { _end_point = event->pos(); // Translate into timeline space QPoint local_pos = _end_point + QPoint(timeToPosition(_time) - NODE_ITEM_WIDTH, -TITLE_HEIGHT); switch (getMode()) { case MODE_DRAGGING_THUMB: if (_root) { DTfloat t = positionToTime(local_pos.x()); emit doCommand(QString("SetProp \"") + _root->full_name().c_str() + ".Time_Out\" " + MoreStrings::cast_to_string(t).c_str()); } update(); break; case MODE_DRAG_SELECTING: { QRect rs; selectionRect(rs); for (int i = 0; i < _plug_event_cache.size(); ++i) { if (!_plug_event_cache[i]._node || !_plug_event_cache[i]._keyframes) continue; // Append selection if (event->modifiers() & Qt::SHIFT) { for (int k = 0; k < getNumKeys(_plug_event_cache[i]); ++k) { QRect rk; keyRect (_plug_event_cache[i], k, rk); if (rs.intersects(rk)) { int id = _plug_event_cache[i]._keyframes->key_id(k); // Invert keyframes if (isSelected(_plug_event_cache[i], id)) setSelected(_plug_event_cache[i], id, false); else setSelected(_plug_event_cache[i], id, true); } } // New selection } else { clearSelected (_plug_event_cache[i]); for (int k = 0; k < getNumKeys(_plug_event_cache[i]); ++k) { QRect rk; keyRect (_plug_event_cache[i], k, rk); if (rs.contains(rk)) { int id = _plug_event_cache[i]._keyframes->key_id(k); setSelected(_plug_event_cache[i], id, true); } } } } update(); } break; case MODE_DRAGGING: update(); break; default: break; } setMode(MODE_NONE); } //============================================================================== //============================================================================== void EdLevelAnimationWindow::wheelEvent (QWheelEvent *event) { int move = -event->delta(); if (event->orientation() == Qt::Horizontal) { _horz_scrollbar->setValue(_horz_scrollbar->value() + move); } else { _vert_scrollbar->setValue(_vert_scrollbar->value() + move); } update(); event->accept(); } //============================================================================== //============================================================================== void EdLevelAnimationWindow::keyPressEvent (QKeyEvent *event) { emit doUndoBlock(); int key = event->key(); if (event->matches(QKeySequence::Delete) || key == 0x1000003) { for (int i = 0; i < _plug_event_cache.size(); ++i) { if (!_plug_event_cache[i]._node || !_plug_event_cache[i]._keyframes) continue; std::list<int> &selected = _plug_event_cache[i]._selected_ids; FOR_EACH (j ,selected) { std::string cmd = "ClearKeyframeByID " + _plug_event_cache[i]._keyframes->full_name() + " " + MoreStrings::cast_to_string(*j); emit doCommand(cmd.c_str()); } } clearSelected(); update(); } } //============================================================================== //============================================================================== void EdLevelAnimationWindow::setSelected (PlugEventCache &p, int id, bool selected) { if (selected) { auto i = std::find(p._selected_ids.begin(), p._selected_ids.end(), id); if (i == p._selected_ids.end()) p._selected_ids.push_back(id); } else { auto i = std::find(p._selected_ids.begin(), p._selected_ids.end(), id); if (i != p._selected_ids.end()) p._selected_ids.erase(i); } } void EdLevelAnimationWindow::clearSelected (PlugEventCache &p) { p._selected_ids.clear(); } void EdLevelAnimationWindow::clearSelected (void) { for (int i = 0; i < _plug_event_cache.size(); ++i) clearSelected(_plug_event_cache[i]); } bool EdLevelAnimationWindow::isSelected (PlugEventCache &p, int id) { auto i = std::find(p._selected_ids.begin(), p._selected_ids.end(), id); if (i == p._selected_ids.end()) return false; return true; } //============================================================================== //============================================================================== void EdLevelAnimationWindow::onRefreshAnimation(void) { scanRelevantNodes( _document->selection() ); update(); } //============================================================================== //============================================================================== void EdLevelAnimationWindow::paintEvent(QPaintEvent * /* event */) { QPainter painter(this); draw(&painter); } void EdLevelAnimationWindow::draw(QPainter *painter) { painter->setRenderHint(QPainter::Antialiasing, false); painter->setClipRect(rect()); painter->setPen(Qt::NoPen); painter->setBrush(QBrush(QColor(100,100,100,255))); painter->drawRect(rect()); painter->setBrush(QBrush(QColor(95,95,95,255))); painter->drawRect(_nodes); painter->drawRect(_title); painter->drawRect(_timeline); // // Draw Node Names // painter->resetTransform (); painter->setClipRect ( _nodes ); painter->translate (0, TITLE_HEIGHT - _scroll); for (int i = 0; i < _plug_event_cache.size(); ++i) { QRect tr, r; itemRect(_plug_event_cache[i], tr, r); if (_plug_event_cache[i]._node) { painter->setPen(QPen(QColor(100,100,100,255),0)); painter->setBrush(QBrush(QColor(130,130,130,255))); painter->drawRect(r); painter->setPen(QPen(QColor(40,40,40,255),1)); painter->setFont(_font); painter->drawText(tr, Qt::AlignLeft | Qt::AlignVCenter, _plug_event_cache[i]._title.c_str() ); } else { painter->setPen(QPen(QColor(40,40,40,255),1)); painter->setFont(_font_bold); painter->drawText(tr, Qt::AlignLeft | Qt::AlignVCenter, _plug_event_cache[i]._title.c_str() ); } } // // Draw Node Keyframes // painter->resetTransform (); painter->setClipRect ( _controls ); painter->translate (NODE_ITEM_WIDTH - timeToPosition(_time), TITLE_HEIGHT - _scroll); for (int i = 0; i < _plug_event_cache.size(); ++i) { if (!_plug_event_cache[i]._node || !_plug_event_cache[i]._keyframes) continue; QRect tr, r; itemRect(_plug_event_cache[i], tr, r); // Build a new Rect based on this one r.setLeft( timeToPosition(_time_min_sec) ); r.setWidth( timeToPosition(_time_max_sec - _time_min_sec) ); painter->setPen(QPen(QColor(100,100,100,255),0)); painter->setBrush(QBrush(QColor(130,130,130,255))); painter->drawRect(r); // Draw guide line painter->setPen(QPen(QColor(100,100,100,255),1)); painter->drawLine( timeToPosition(_time_min_sec), r.center().y(), timeToPosition(_time_max_sec - _time_min_sec), r.center().y()); if (getNumKeys(_plug_event_cache[i]) > 0) { // Draw regions between keyframes for (int k = 0; k < getNumKeys(_plug_event_cache[i])-1; ++k) { QRect r1,r2; keyRect (_plug_event_cache[i], k, r1); keyRect (_plug_event_cache[i], k+1, r2); QRect r = r1.united(r2); r.adjust(_keyframe_image.width()/2, 0, -_keyframe_image.width()/2, 0); painter->setPen(Qt::NoPen); painter->setBrush(QBrush(QColor(0,0,0,30))); painter->drawRect(r); } // Draw keyframes for (int k = 0; k < getNumKeys(_plug_event_cache[i]); ++k) { QRect r; keyRect (_plug_event_cache[i], k, r); int id = _plug_event_cache[i]._keyframes->key_id(k); if (isSelected (_plug_event_cache[i], id)) painter->drawImage(r, _keyframe_image_selected); else painter->drawImage(r, _keyframe_image); } } } // Selection if (getMode() == MODE_DRAG_SELECTING) { QRect rs; selectionRect(rs); painter->setPen(QPen(QColor(53,120,255,255),2)); painter->setBrush(QBrush(QColor(0,0,0,50))); painter->drawRoundedRect(rs, 5, 5); } // // Draw Seconds // painter->resetTransform (); painter->setClipRect ( _timeline.united(_controls) ); painter->translate (NODE_ITEM_WIDTH - timeToPosition(_time), 0); painter->setFont(_font); // Milliseconds for (int t = _time_min_sec*1000; t <= _time_max_sec*1000; t += 100) { int xpos = timeToPosition(t/1000.0F); // Full second if (t % 1000 == 0) { if (t == 0) painter->setPen(QPen(QColor(75,75,75,255),3,Qt::SolidLine)); else painter->setPen(QPen(QColor(75,75,75,255),1,Qt::SolidLine)); painter->drawLine( QPoint(xpos, TITLE_HEIGHT) , QPoint(xpos, rect().height() - _scroll_height) ); QRect tr(xpos - _pixels_per_second/2,0,_pixels_per_second,TITLE_HEIGHT); painter->setPen(QPen(QColor(25,25,25,255),1,Qt::SolidLine)); std::stringstream ss; ss << (t/1000) << " s"; painter->drawText(tr, Qt::AlignHCenter | Qt::AlignBottom, ss.str().c_str()); } else { painter->setPen(QPen(QColor(90,90,90,255),1,Qt::DotLine)); painter->drawLine( QPoint(xpos, TITLE_HEIGHT) , QPoint(xpos, rect().height() - _scroll_height) ); } } // // Draw Current Time // if (_root) { painter->resetTransform (); painter->setClipRect ( _timeline.united(_controls) ); painter->translate (NODE_ITEM_WIDTH - timeToPosition(_time), 0); DTfloat t = _root->time(); int xpos = timeToPosition(t); QRect thr; thumbRect(thr); painter->drawImage(thr, _thumb_image); painter->setPen(QPen(QColor(0,255,0,255),1,Qt::SolidLine)); painter->drawLine( QPoint(xpos, TITLE_HEIGHT) , QPoint(xpos, rect().height() - _scroll_height) ); QRect tr(xpos - _pixels_per_second/2,0,_pixels_per_second,TITLE_HEIGHT); std::stringstream ss; ss << t << " s"; painter->drawText(tr, Qt::AlignHCenter | Qt::AlignTop, ss.str().c_str()); } // // Draw Separators // painter->resetTransform (); painter->setClipRect (rect()); painter->setPen(QPen(QColor(75,75,75,255),2)); painter->setBrush(QBrush(QColor(100,100,100,255))); painter->drawLine( QPoint(0, TITLE_HEIGHT), QPoint(rect().width(), TITLE_HEIGHT) ); painter->drawLine( QPoint(NODE_ITEM_WIDTH, 0), QPoint(NODE_ITEM_WIDTH, rect().height()) ); } //============================================================================== //============================================================================== #include "moc_EdLevelAnimationWindow.cpp"
34.500963
211
0.501703
nemerle
f5c0688dd156ba862e9571e1a778a5dded3474dd
19,353
cpp
C++
src/mongo/db/storage/wiredtiger/wiredtiger_recovery_unit_test.cpp
evergage/mongo
887ce0b9730bc9f43b5fe7627a71659b84b68026
[ "Apache-2.0" ]
null
null
null
src/mongo/db/storage/wiredtiger/wiredtiger_recovery_unit_test.cpp
evergage/mongo
887ce0b9730bc9f43b5fe7627a71659b84b68026
[ "Apache-2.0" ]
null
null
null
src/mongo/db/storage/wiredtiger/wiredtiger_recovery_unit_test.cpp
evergage/mongo
887ce0b9730bc9f43b5fe7627a71659b84b68026
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2018 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/db/storage/wiredtiger/wiredtiger_recovery_unit.h" #include "mongo/base/checked_cast.h" #include "mongo/db/repl/repl_settings.h" #include "mongo/db/repl/replication_coordinator_mock.h" #include "mongo/db/service_context.h" #include "mongo/db/storage/recovery_unit_test_harness.h" #include "mongo/db/storage/wiredtiger/wiredtiger_kv_engine.h" #include "mongo/db/storage/wiredtiger/wiredtiger_record_store.h" #include "mongo/db/storage/wiredtiger/wiredtiger_session_cache.h" #include "mongo/db/storage/wiredtiger/wiredtiger_util.h" #include "mongo/unittest/temp_dir.h" #include "mongo/unittest/unittest.h" #include "mongo/util/clock_source_mock.h" namespace mongo { namespace { class WiredTigerRecoveryUnitHarnessHelper final : public RecoveryUnitHarnessHelper { public: WiredTigerRecoveryUnitHarnessHelper() : _dbpath("wt_test"), _engine(kWiredTigerEngineName, // .canonicalName _dbpath.path(), // .path &_cs, // .cs "", // .extraOpenOptions 1, // .cacheSizeGB false, // .durable false, // .ephemeral false, // .repair false // .readOnly ) { repl::ReplicationCoordinator::set( getGlobalServiceContext(), std::unique_ptr<repl::ReplicationCoordinator>(new repl::ReplicationCoordinatorMock( getGlobalServiceContext(), repl::ReplSettings()))); } ~WiredTigerRecoveryUnitHarnessHelper() {} virtual std::unique_ptr<RecoveryUnit> newRecoveryUnit() final { return std::unique_ptr<RecoveryUnit>(_engine.newRecoveryUnit()); } virtual std::unique_ptr<RecordStore> createRecordStore(OperationContext* opCtx, const std::string& ns) final { std::string uri = "table:" + ns; const bool prefixed = false; StatusWith<std::string> result = WiredTigerRecordStore::generateCreateString( kWiredTigerEngineName, ns, CollectionOptions(), "", prefixed); ASSERT_TRUE(result.isOK()); std::string config = result.getValue(); { WriteUnitOfWork uow(opCtx); WiredTigerRecoveryUnit* ru = checked_cast<WiredTigerRecoveryUnit*>(opCtx->recoveryUnit()); WT_SESSION* s = ru->getSession()->getSession(); invariantWTOK(s->create(s, uri.c_str(), config.c_str())); uow.commit(); } WiredTigerRecordStore::Params params; params.ns = ns; params.uri = uri; params.engineName = kWiredTigerEngineName; params.isCapped = false; params.isEphemeral = false; params.cappedMaxSize = -1; params.cappedMaxDocs = -1; params.cappedCallback = nullptr; params.sizeStorer = nullptr; params.isReadOnly = false; auto ret = stdx::make_unique<StandardWiredTigerRecordStore>(&_engine, opCtx, params); ret->postConstructorInit(opCtx); return std::move(ret); } WiredTigerKVEngine* getEngine() { return &_engine; } private: unittest::TempDir _dbpath; ClockSourceMock _cs; WiredTigerKVEngine _engine; }; std::unique_ptr<HarnessHelper> makeHarnessHelper() { return std::make_unique<WiredTigerRecoveryUnitHarnessHelper>(); } MONGO_INITIALIZER(RegisterHarnessFactory)(InitializerContext* const) { mongo::registerHarnessHelperFactory(makeHarnessHelper); return Status::OK(); } class WiredTigerRecoveryUnitTestFixture : public unittest::Test { public: typedef std::pair<ServiceContext::UniqueClient, ServiceContext::UniqueOperationContext> ClientAndCtx; ClientAndCtx makeClientAndOpCtx(RecoveryUnitHarnessHelper* harnessHelper, const std::string& clientName) { auto sc = harnessHelper->serviceContext(); auto client = sc->makeClient(clientName); auto opCtx = client->makeOperationContext(); opCtx->setRecoveryUnit(harnessHelper->newRecoveryUnit(), WriteUnitOfWork::RecoveryUnitState::kNotInUnitOfWork); return std::make_pair(std::move(client), std::move(opCtx)); } void getCursor(WiredTigerRecoveryUnit* ru, WT_CURSOR** cursor) { WT_SESSION* wt_session = ru->getSession()->getSession(); invariantWTOK(wt_session->create(wt_session, wt_uri, wt_config)); invariantWTOK(wt_session->open_cursor(wt_session, wt_uri, NULL, NULL, cursor)); } void setUp() override { harnessHelper = std::make_unique<WiredTigerRecoveryUnitHarnessHelper>(); clientAndCtx1 = makeClientAndOpCtx(harnessHelper.get(), "writer"); clientAndCtx2 = makeClientAndOpCtx(harnessHelper.get(), "reader"); ru1 = checked_cast<WiredTigerRecoveryUnit*>(clientAndCtx1.second->recoveryUnit()); ru2 = checked_cast<WiredTigerRecoveryUnit*>(clientAndCtx2.second->recoveryUnit()); } std::unique_ptr<WiredTigerRecoveryUnitHarnessHelper> harnessHelper; ClientAndCtx clientAndCtx1, clientAndCtx2; WiredTigerRecoveryUnit *ru1, *ru2; private: const char* wt_uri = "table:prepare_transaction"; const char* wt_config = "key_format=S,value_format=S"; }; TEST_F(WiredTigerRecoveryUnitTestFixture, SetReadSource) { ru1->setTimestampReadSource(RecoveryUnit::ReadSource::kProvided, Timestamp(1, 1)); ASSERT_EQ(RecoveryUnit::ReadSource::kProvided, ru1->getTimestampReadSource()); ASSERT_EQ(Timestamp(1, 1), ru1->getPointInTimeReadTimestamp()); } TEST_F(WiredTigerRecoveryUnitTestFixture, CreateAndCheckForCachePressure) { int time = 1; // Reconfigure the size of the cache to be very small so that building cache pressure is fast. WiredTigerKVEngine* engine = harnessHelper->getEngine(); std::string cacheSizeReconfig = "cache_size=1MB"; ASSERT_EQ(engine->reconfigure(cacheSizeReconfig.c_str()), 0); OperationContext* opCtx = clientAndCtx1.second.get(); std::unique_ptr<RecordStore> rs(harnessHelper->createRecordStore(opCtx, "a.b")); // Insert one document so that we can then update it in a loop to create cache pressure. // Note: inserts will not create cache pressure. WriteUnitOfWork wu(opCtx); ASSERT_OK(ru1->setTimestamp(Timestamp(time++))); std::string str = str::stream() << "foobarbaz"; StatusWith<RecordId> ress = rs->insertRecord(opCtx, str.c_str(), str.size() + 1, Timestamp()); ASSERT_OK(ress.getStatus()); auto recordId = ress.getValue(); wu.commit(); for (int j = 0; j < 1000; ++j) { // Once we hit the cache pressure threshold, i.e. have successfully created cache pressure // that is detectable, we are done. if (engine->isCacheUnderPressure(opCtx)) { invariant(j != 0); break; } try { WriteUnitOfWork wuow(opCtx); ASSERT_OK(ru1->setTimestamp(Timestamp(time++))); std::string s = str::stream() << "abcbcdcdedefefgfghghihijijkjklklmlmnmnomopopqpqrqrsrststutuv" << j; ASSERT_OK(rs->updateRecord(opCtx, recordId, s.c_str(), s.size() + 1, nullptr)); wuow.commit(); } catch (const DBException& ex) { invariant(ex.toStatus().code() == ErrorCodes::WriteConflict); } } } TEST_F(WiredTigerRecoveryUnitTestFixture, LocalReadOnADocumentBeingPreparedTriggersPrepareConflict) { // Prepare but don't commit a transaction ru1->beginUnitOfWork(clientAndCtx1.second.get()); WT_CURSOR* cursor; getCursor(ru1, &cursor); cursor->set_key(cursor, "key"); cursor->set_value(cursor, "value"); invariantWTOK(cursor->insert(cursor)); ru1->setPrepareTimestamp({1, 1}); ru1->prepareUnitOfWork(); // Transaction read default triggers WT_PREPARE_CONFLICT ru2->beginUnitOfWork(clientAndCtx2.second.get()); getCursor(ru2, &cursor); cursor->set_key(cursor, "key"); int ret = cursor->search(cursor); ASSERT_EQ(WT_PREPARE_CONFLICT, ret); ru1->abortUnitOfWork(); ru2->abortUnitOfWork(); } TEST_F(WiredTigerRecoveryUnitTestFixture, AvailableReadOnADocumentBeingPreparedDoesNotTriggerPrepareConflict) { // Prepare but don't commit a transaction ru1->beginUnitOfWork(clientAndCtx1.second.get()); WT_CURSOR* cursor; getCursor(ru1, &cursor); cursor->set_key(cursor, "key"); cursor->set_value(cursor, "value"); invariantWTOK(cursor->insert(cursor)); ru1->setPrepareTimestamp({1, 1}); ru1->prepareUnitOfWork(); // Transaction that should ignore prepared transactions won't trigger // WT_PREPARE_CONFLICT ru2->beginUnitOfWork(clientAndCtx2.second.get()); ru2->setIgnorePrepared(true); getCursor(ru2, &cursor); cursor->set_key(cursor, "key"); int ret = cursor->search(cursor); ASSERT_EQ(WT_NOTFOUND, ret); ru1->abortUnitOfWork(); ru2->abortUnitOfWork(); } TEST_F(WiredTigerRecoveryUnitTestFixture, WriteOnADocumentBeingPreparedTriggersWTRollback) { // Prepare but don't commit a transaction ru1->beginUnitOfWork(clientAndCtx1.second.get()); WT_CURSOR* cursor; getCursor(ru1, &cursor); cursor->set_key(cursor, "key"); cursor->set_value(cursor, "value"); invariantWTOK(cursor->insert(cursor)); ru1->setPrepareTimestamp({1, 1}); ru1->prepareUnitOfWork(); // Another transaction with write triggers WT_ROLLBACK ru2->beginUnitOfWork(clientAndCtx2.second.get()); getCursor(ru2, &cursor); cursor->set_key(cursor, "key"); cursor->set_value(cursor, "value2"); int ret = cursor->insert(cursor); ASSERT_EQ(WT_ROLLBACK, ret); ru1->abortUnitOfWork(); ru2->abortUnitOfWork(); } TEST_F(WiredTigerRecoveryUnitTestFixture, ChangeIsPassedEmptyLastTimestampSetOnCommitWithNoTimestamp) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); wuow.commit(); } ASSERT(!commitTs); } TEST_F(WiredTigerRecoveryUnitTestFixture, ChangeIsPassedLastTimestampSetOnCommit) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); Timestamp ts2(6, 6); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT_OK(opCtx->recoveryUnit()->setTimestamp(ts1)); ASSERT(!commitTs); ASSERT_OK(opCtx->recoveryUnit()->setTimestamp(ts2)); ASSERT(!commitTs); ASSERT_OK(opCtx->recoveryUnit()->setTimestamp(ts1)); ASSERT(!commitTs); wuow.commit(); ASSERT_EQ(*commitTs, ts1); } ASSERT_EQ(*commitTs, ts1); } TEST_F(WiredTigerRecoveryUnitTestFixture, ChangeIsNotPassedLastTimestampSetOnAbort) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT_OK(opCtx->recoveryUnit()->setTimestamp(ts1)); ASSERT(!commitTs); } ASSERT(!commitTs); } TEST_F(WiredTigerRecoveryUnitTestFixture, ChangeIsPassedCommitTimestamp) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); opCtx->recoveryUnit()->setCommitTimestamp(ts1); ASSERT(!commitTs); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); wuow.commit(); ASSERT_EQ(*commitTs, ts1); } ASSERT_EQ(*commitTs, ts1); } TEST_F(WiredTigerRecoveryUnitTestFixture, ChangeIsNotPassedCommitTimestampIfCleared) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); opCtx->recoveryUnit()->setCommitTimestamp(ts1); ASSERT(!commitTs); opCtx->recoveryUnit()->clearCommitTimestamp(); ASSERT(!commitTs); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); wuow.commit(); } ASSERT(!commitTs); } TEST_F(WiredTigerRecoveryUnitTestFixture, ChangeIsPassedNewestCommitTimestamp) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); Timestamp ts2(6, 6); opCtx->recoveryUnit()->setCommitTimestamp(ts2); ASSERT(!commitTs); opCtx->recoveryUnit()->clearCommitTimestamp(); ASSERT(!commitTs); opCtx->recoveryUnit()->setCommitTimestamp(ts1); ASSERT(!commitTs); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); wuow.commit(); ASSERT_EQ(*commitTs, ts1); } ASSERT_EQ(*commitTs, ts1); } TEST_F(WiredTigerRecoveryUnitTestFixture, ChangeIsNotPassedCommitTimestampOnAbort) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); opCtx->recoveryUnit()->setCommitTimestamp(ts1); ASSERT(!commitTs); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); } ASSERT(!commitTs); } TEST_F(WiredTigerRecoveryUnitTestFixture, CommitTimestampBeforeSetTimestampOnCommit) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); Timestamp ts2(6, 6); opCtx->recoveryUnit()->setCommitTimestamp(ts2); ASSERT(!commitTs); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); wuow.commit(); ASSERT_EQ(*commitTs, ts2); } ASSERT_EQ(*commitTs, ts2); opCtx->recoveryUnit()->clearCommitTimestamp(); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT_OK(opCtx->recoveryUnit()->setTimestamp(ts1)); ASSERT_EQ(*commitTs, ts2); wuow.commit(); ASSERT_EQ(*commitTs, ts1); } ASSERT_EQ(*commitTs, ts1); } TEST_F(WiredTigerRecoveryUnitTestFixture, CommitTimestampAfterSetTimestampOnCommit) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); Timestamp ts2(6, 6); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); ASSERT_OK(opCtx->recoveryUnit()->setTimestamp(ts2)); ASSERT(!commitTs); wuow.commit(); ASSERT_EQ(*commitTs, ts2); } ASSERT_EQ(*commitTs, ts2); opCtx->recoveryUnit()->setCommitTimestamp(ts1); ASSERT_EQ(*commitTs, ts2); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT_EQ(*commitTs, ts2); wuow.commit(); ASSERT_EQ(*commitTs, ts1); } ASSERT_EQ(*commitTs, ts1); } TEST_F(WiredTigerRecoveryUnitTestFixture, CommitTimestampBeforeSetTimestampOnAbort) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); Timestamp ts2(6, 6); opCtx->recoveryUnit()->setCommitTimestamp(ts2); ASSERT(!commitTs); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); } ASSERT(!commitTs); opCtx->recoveryUnit()->clearCommitTimestamp(); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT_OK(opCtx->recoveryUnit()->setTimestamp(ts1)); ASSERT(!commitTs); } ASSERT(!commitTs); } TEST_F(WiredTigerRecoveryUnitTestFixture, CommitTimestampAfterSetTimestampOnAbort) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); Timestamp ts2(6, 6); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); ASSERT_OK(opCtx->recoveryUnit()->setTimestamp(ts2)); ASSERT(!commitTs); } ASSERT(!commitTs); opCtx->recoveryUnit()->setCommitTimestamp(ts1); ASSERT(!commitTs); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); } ASSERT(!commitTs); } } // namespace } // namespace mongo
36.241573
98
0.660931
evergage
f5c1054a308d3b17d7a75fc95ddf2f5624dd9ea8
12,266
cpp
C++
folly/experimental/coro/test/AsyncGeneratorTest.cpp
muralivemulapati/folly
d7808b52813448e4535455e87fbea838a2307ce7
[ "Apache-2.0" ]
null
null
null
folly/experimental/coro/test/AsyncGeneratorTest.cpp
muralivemulapati/folly
d7808b52813448e4535455e87fbea838a2307ce7
[ "Apache-2.0" ]
null
null
null
folly/experimental/coro/test/AsyncGeneratorTest.cpp
muralivemulapati/folly
d7808b52813448e4535455e87fbea838a2307ce7
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/Portability.h> #if FOLLY_HAS_COROUTINES #include <folly/ScopeGuard.h> #include <folly/Traits.h> #include <folly/experimental/coro/AsyncGenerator.h> #include <folly/experimental/coro/Baton.h> #include <folly/experimental/coro/BlockingWait.h> #include <folly/experimental/coro/Collect.h> #include <folly/experimental/coro/Sleep.h> #include <folly/experimental/coro/Task.h> #include <folly/experimental/coro/WithCancellation.h> #include <folly/futures/Future.h> #include <folly/portability/GTest.h> #include <chrono> #include <map> #include <string> #include <tuple> TEST(AsyncGenerator, DefaultConstructedGeneratorIsEmpty) { folly::coro::blockingWait([]() -> folly::coro::Task<void> { folly::coro::AsyncGenerator<int> g; auto result = co_await g.next(); CHECK(!result); }()); } TEST(AsyncGenerator, GeneratorDestroyedBeforeCallingBegin) { bool started = false; auto makeGenerator = [&]() -> folly::coro::AsyncGenerator<int> { started = true; co_return; }; { auto gen = makeGenerator(); (void)gen; } CHECK(!started); } TEST(AsyncGenerator, PartiallyConsumingSequenceDestroysObjectsInScope) { bool started = false; bool destroyed = false; auto makeGenerator = [&]() -> folly::coro::AsyncGenerator<int> { SCOPE_EXIT { destroyed = true; }; started = true; co_yield 1; co_yield 2; co_return; }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { { auto gen = makeGenerator(); CHECK(!started); CHECK(!destroyed); auto result = co_await gen.next(); CHECK(started); CHECK(!destroyed); CHECK(result); CHECK_EQ(1, *result); } CHECK(destroyed); }()); } TEST(AsyncGenerator, FullyConsumeSequence) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<int> { for (int i = 0; i < 4; ++i) { co_yield i; } }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); auto result = co_await gen.next(); CHECK(result); CHECK_EQ(0, *result); result = co_await gen.next(); CHECK(result); CHECK_EQ(1, *result); result = co_await gen.next(); CHECK(result); CHECK_EQ(2, *result); result = co_await gen.next(); CHECK(result); CHECK_EQ(3, *result); result = co_await gen.next(); CHECK(!result); }()); } namespace { struct SomeError : std::exception {}; } // namespace TEST(AsyncGenerator, ThrowExceptionBeforeFirstYield) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<int> { if (true) { throw SomeError{}; } co_return; }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); bool caughtException = false; try { (void)co_await gen.next(); CHECK(false); } catch (const SomeError&) { caughtException = true; } CHECK(caughtException); }()); } TEST(AsyncGenerator, ThrowExceptionAfterFirstYield) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<int> { co_yield 42; throw SomeError{}; }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); auto result = co_await gen.next(); CHECK(result); CHECK_EQ(42, *result); bool caughtException = false; try { (void)co_await gen.next(); CHECK(false); } catch (const SomeError&) { caughtException = true; } CHECK(caughtException); }()); } TEST(AsyncGenerator, ConsumingManySynchronousElementsDoesNotOverflowStack) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<std::uint64_t> { for (std::uint64_t i = 0; i < 1'000'000; ++i) { co_yield i; } }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); std::uint64_t sum = 0; while (auto result = co_await gen.next()) { sum += *result; } CHECK_EQ(499999500000u, sum); }()); } TEST(AsyncGenerator, ProduceResultsAsynchronously) { folly::coro::blockingWait([&]() -> folly::coro::Task<void> { folly::Executor* executor = co_await folly::coro::co_current_executor; auto makeGenerator = [&]() -> folly::coro::AsyncGenerator<int> { using namespace std::literals::chrono_literals; CHECK_EQ(executor, co_await folly::coro::co_current_executor); co_await folly::coro::sleep(1ms); CHECK_EQ(executor, co_await folly::coro::co_current_executor); co_yield 1; CHECK_EQ(executor, co_await folly::coro::co_current_executor); co_await folly::coro::sleep(1ms); CHECK_EQ(executor, co_await folly::coro::co_current_executor); co_yield 2; CHECK_EQ(executor, co_await folly::coro::co_current_executor); co_await folly::coro::sleep(1ms); CHECK_EQ(executor, co_await folly::coro::co_current_executor); }; auto gen = makeGenerator(); auto result = co_await gen.next(); CHECK_EQ(1, *result); result = co_await gen.next(); CHECK_EQ(2, *result); result = co_await gen.next(); CHECK(!result); }()); } struct ConvertibleToIntReference { int value; operator int&() { return value; } }; TEST(AsyncGenerator, GeneratorOfLValueReference) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<int&> { int value = 10; co_yield value; // Consumer gets a mutable reference to the value and can modify it. CHECK_EQ(20, value); // NOTE: Not allowed to yield an rvalue from an AsyncGenerator<T&>? // co_yield 30; // Compile-error co_yield ConvertibleToIntReference{30}; }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); auto result = co_await gen.next(); CHECK_EQ(10, result.value()); *result = 20; result = co_await gen.next(); CHECK_EQ(30, result.value()); result = co_await gen.next(); CHECK(!result.has_value()); }()); } struct ConvertibleToInt { operator int() const { return 99; } }; TEST(AsyncGenerator, GeneratorOfConstLValueReference) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<const int&> { int value = 10; co_yield value; // Consumer gets a const reference to the value. // Allowed to yield an rvalue from an AsyncGenerator<const T&>. co_yield 30; co_yield ConvertibleToInt{}; }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); auto result = co_await gen.next(); CHECK_EQ(10, *result); result = co_await gen.next(); CHECK_EQ(30, *result); result = co_await gen.next(); CHECK_EQ(99, *result); result = co_await gen.next(); CHECK(!result); }()); } TEST(AsyncGenerator, GeneratorOfRValueReference) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<std::unique_ptr<int>&&> { co_yield std::make_unique<int>(10); auto ptr = std::make_unique<int>(20); co_yield std::move(ptr); CHECK(ptr == nullptr); }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); auto result = co_await gen.next(); CHECK_EQ(10, **result); // Don't move it to a local var. result = co_await gen.next(); CHECK_EQ(20, **result); auto ptr = *result; // Move it to a local var. result = co_await gen.next(); CHECK(!result); }()); } struct MoveOnly { explicit MoveOnly(int value) : value_(value) {} MoveOnly(MoveOnly&& other) noexcept : value_(std::exchange(other.value_, -1)) {} ~MoveOnly() {} MoveOnly& operator=(MoveOnly&&) = delete; int value() const { return value_; } private: int value_; }; TEST(AsyncGenerator, GeneratorOfMoveOnlyType) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<MoveOnly> { MoveOnly rvalue(1); co_yield std::move(rvalue); CHECK_EQ(-1, rvalue.value()); co_yield MoveOnly(2); }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); auto result = co_await gen.next(); // NOTE: It's an error to dereference using '*it' as this returns a copy // of the iterator's reference type, which in this case is 'MoveOnly'. CHECK_EQ(1, result->value()); result = co_await gen.next(); CHECK_EQ(2, result->value()); result = co_await gen.next(); CHECK(!result); }()); } TEST(AsyncGenerator, GeneratorOfConstValue) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<const int> { // OK to yield prvalue co_yield 42; // OK to yield lvalue int x = 123; co_yield x; co_yield ConvertibleToInt{}; }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); auto result = co_await gen.next(); CHECK_EQ(42, *result); static_assert(std::is_same_v<decltype(*result), const int&>); result = co_await gen.next(); CHECK_EQ(123, *result); result = co_await gen.next(); CHECK_EQ(99, *result); result = co_await gen.next(); CHECK(!result); }()); } TEST(AsyncGenerator, ExplicitValueType) { std::map<std::string, std::string> items; items["foo"] = "hello"; items["bar"] = "goodbye"; auto makeGenerator = [&]() -> folly::coro::AsyncGenerator< std::tuple<const std::string&, std::string&>, std::tuple<std::string, std::string>> { for (auto& [k, v] : items) { co_yield{k, v}; } }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); auto result = co_await gen.next(); { auto [kRef, vRef] = *result; CHECK_EQ("bar", kRef); CHECK_EQ("goodbye", vRef); decltype(gen)::value_type copy = *result; vRef = "au revoir"; CHECK_EQ("goodbye", std::get<1>(copy)); CHECK_EQ("au revoir", std::get<1>(*result)); } }()); CHECK_EQ("au revoir", items["bar"]); } TEST(AsyncGenerator, InvokeLambda) { folly::coro::blockingWait([]() -> folly::coro::Task<void> { auto ptr = std::make_unique<int>(123); auto gen = folly::coro::co_invoke( [p = std::move(ptr)]() mutable -> folly::coro::AsyncGenerator<std::unique_ptr<int>&&> { co_yield std::move(p); }); auto result = co_await gen.next(); CHECK(result); ptr = *result; CHECK(ptr); CHECK(*ptr == 123); }()); } template <typename Ref, typename Value = folly::remove_cvref_t<Ref>> folly::coro::AsyncGenerator<Ref, Value> neverStream() { folly::coro::Baton baton; folly::CancellationCallback cb{ co_await folly::coro::co_current_cancellation_token, [&] { baton.post(); }}; co_await baton; } TEST(AsyncGenerator, CancellationTokenPropagatesFromConsumer) { folly::coro::blockingWait([]() -> folly::coro::Task<void> { folly::CancellationSource cancelSource; bool suspended = false; bool done = false; co_await folly::coro::collectAll( folly::coro::co_withCancellation( cancelSource.getToken(), [&]() -> folly::coro::Task<void> { auto stream = neverStream<int>(); suspended = true; auto result = co_await stream.next(); CHECK(!result.has_value()); done = true; }()), [&]() -> folly::coro::Task<void> { co_await folly::coro::co_reschedule_on_current_executor; co_await folly::coro::co_reschedule_on_current_executor; co_await folly::coro::co_reschedule_on_current_executor; CHECK(suspended); CHECK(!done); cancelSource.requestCancellation(); }()); CHECK(done); }()); } #endif
27.502242
78
0.628974
muralivemulapati
f5c335aa22be901327562676c585b56e34c7da99
9,922
cxx
C++
com/oleutest/stgbvt/comtools/cmdlinew/culong.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/oleutest/stgbvt/comtools/cmdlinew/culong.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/oleutest/stgbvt/comtools/cmdlinew/culong.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------ // // File: culong.cxx // // Contents: implementation for CUlongCmdlineObj // // Synoposis: Encapsulates a command line switch which takes an // unsigned long value, eg: /maxusers:10 // // Classes: CUlongCmdlineObj // // Functions: // // History: 06/15/92 DeanE Stolen from CIntCmdlineObj code // 07/29/92 davey Added nlsType and nlsLineArgType // 09/09/92 Lizch Changed SUCCESS to NO_ERROR // 09/18/92 Lizch Precompile headers // 11/14/92 DwightKr Updates for new version of NLS_STR // 10/14/93 DeanE Converted to NCHAR // //------------------------------------------------------------------- #include <comtpch.hxx> #pragma hdrstop #include <cmdlinew.hxx> // public cmdlinew stuff #include "_clw.hxx" // private cmdlinew stuff #include <ctype.h> // is functions INT StringToUlong(LPCNSTR pnszInt, ULONG *pUlong); LPCNSTR nszCmdlineUlong = _TEXTN("Takes an unsigned long "); LPCNSTR nszLineArgUlong = _TEXTN("<ulong> "); //+------------------------------------------------------------------ // // Member: CUlongCmdlineObj destructor // // Synoposis: Frees any memory associated with the object // // History: Added to allow casting of pValue 05/12/92 Lizch // Integrated into CUlongCmdlineObj 6/15/92 DeanE // //------------------------------------------------------------------- CUlongCmdlineObj::~CUlongCmdlineObj() { delete (ULONG *)_pValue; _pValue = NULL; } //+------------------------------------------------------------------ // // Member: CUlongCmdlineObj::SetValue, public // // Synposis: Stores the ulong value specified after the switch // string, eg. 10 for /maxusers:10 // // Effects: This implementation for the virtual method SetValue // converts the characters following the switch to an unsigned // long. It allocates memory for the ulong. // If there is no equator character, or if there // is no character following the equator character, _pValue // remains NULL. // // Arguments: [nszArg] - the string following the switch on the // command line. Includes the equator (eg. // ':' or '=' ), if any. // // Returns: CMDLINE_NO_ERROR, CMDLINE_ERROR_OUT_OF_MEMORY, // CMDLINE_ERROR_TOO_BIG, CMDLINE_ERROR_INVALID_VALUE // // History: Created 12/27/91 Lizch // Converted to NLS_STR 4/17/92 Lizch // Integrated into CUlongCmdlineObj 6/15/92 DeanE // //------------------------------------------------------------------- INT CUlongCmdlineObj::SetValue(LPCNSTR nszArg) { INT iRC; // delete any existing _pValue delete (ULONG *)_pValue; _pValue = NULL; _pValue = new ULONG; if (_pValue == NULL) { return (CMDLINE_ERROR_OUT_OF_MEMORY); } // I'm using this rather than c runtime atol so that I // can detect error conditions like overflow and non-digits. iRC = StringToUlong(nszArg, (ULONG *)_pValue); if (iRC != CMDLINE_NO_ERROR) { delete (ULONG *)_pValue; _pValue = NULL; } return(iRC); } //+------------------------------------------------------------------ // // Member: CUlongCmdlineObj::GetValue, public // // Synposis: Returns a pointer to ULONG that holds the value. // // Arguments: void // // Returns: ULONG value at *_pValue. // // History: Created 12/27/91 Lizch // Converted to NLS_STR 4/17/92 Lizch // Integrated into CUlongCmdlineObj 6/15/92 DeanE // //------------------------------------------------------------------- const ULONG *CUlongCmdlineObj::GetValue() { return((ULONG *)_pValue); } //+------------------------------------------------------------------ // // Member: CUlongCmdlineObj::DisplayValue, public // // Synoposis: Prints the stored command line value accordint to // current display method. Generally this will be to stdout. // // History: Created 12/27/91 Lizch // Converted to NLS_STR 4/17/92 Lizch // Integrated into CUlongCmdlineObj 6/15/92 DeanE // //------------------------------------------------------------------- void CUlongCmdlineObj::DisplayValue() { if (_pValue != NULL) { _sNprintf(_nszErrorBuf, _TEXTN("Command line switch %s has value %lu\n"), _pnszSwitch, *(ULONG *)_pValue); (*_pfnDisplay)(_nszErrorBuf); } else { DisplayNoValue(); } } //+------------------------------------------------------------------ // // Function: StringToUlong // // Synoposis: Converts given string to unsigned long, checking for // overflow and illegal characters. Only +, - and digits // are accepted. // // Arguments: [nszUlong] - string to convert // [pUlong] - pointer to converted unsigned long // // Returns: CMDLINE_NO_ERROR, CMDLINE_ERROR_INVALID_VALUE, // CMDLINE_ERROR_TOO_BIG // // History: Created 12/17/91 Lizch // Converted to AsciiToUlong 6/15/92 DeanE // Added in conversion of Hex 12/27/94 DaveY // // Notes: I'm using this rather than c runtime atoi so that I // can detect error conditions like overflow and non-digits. // The sign is checked for and stored, although it is not // used - so a negative value will still be converted to // an unsigned equivalent. // //------------------------------------------------------------------- INT StringToUlong(LPCNSTR nszUlong, ULONG *pUlong) { short sNegator = 1; ULONG ulResult = 0; INT iRC = CMDLINE_NO_ERROR; // Skip any leading spaces - these can occur if the command line // switch incorporates spaces, eg "/a: 123" // while (_isnspace(*nszUlong)) { nszUlong++; } // Get sign - ignore for now switch (*nszUlong) { case '-': sNegator = -1; nszUlong++; break; case '+': sNegator = 1; nszUlong++; break; default: break; } // see if using hex values if ((*nszUlong == _TEXTN('0')) && ((*(nszUlong+1) == _TEXTN('x')) || (*(nszUlong+1) == _TEXTN('X')))) { nszUlong += 2; // pass the "0x" int max = sizeof(ULONG) << 1; // number of hex digits possible for(int i=0; *nszUlong != NULL && i < max; i++, nszUlong++) { if ((_TEXTN('0') <= *nszUlong ) && (*nszUlong <= _TEXTN('9'))) { ulResult = ulResult * 16 + (*nszUlong - _TEXTN('0')); } else if ((_TEXTN('A') <= *nszUlong ) && (*nszUlong <= _TEXTN('F'))) { ulResult = ulResult * 16 + 10 + (*nszUlong - _TEXTN('A')); } else if ((_TEXTN('a') <= *nszUlong) && (*nszUlong <= _TEXTN('f'))) { ulResult = ulResult * 16 + 10 + (*nszUlong - _TEXTN('a')); } else { iRC = CMDLINE_ERROR_INVALID_VALUE; ulResult = 0; break; } } if ((i >= max) && (*nszUlong != NULL)) { iRC = CMDLINE_ERROR_INVALID_VALUE; ulResult = 0; } *pUlong = ulResult; return iRC; } // must be decimal for (;*nszUlong != L'\0'; nszUlong++) { if (!_isndigit(*nszUlong)) { ulResult = 0; iRC = CMDLINE_ERROR_INVALID_VALUE; break; } ULONG ulPrevious = ulResult; ulResult = (ulResult * 10) + (*nszUlong - '0'); // Check for overflow by checking that the previous result is less // than the current result - if the previous one was bigger, we've // overflowed! // if (ulResult < ulPrevious) { ulResult = 0; iRC = CMDLINE_ERROR_TOO_BIG; break; } } *pUlong = ulResult; return(iRC); } //+------------------------------------------------------------------- // // Method: CUlongCmdlineObj::QueryCmdlineType, protected, const // // Synoposis: returns a character pointer to the cmdline type. // // Arguments: None. // // Returns: const NCHAR pointer to string. // // History: 28-Jul-92 davey Created. // //-------------------------------------------------------------------- LPCNSTR CUlongCmdlineObj::QueryCmdlineType() const { return(nszCmdlineUlong); } //+------------------------------------------------------------------- // // Method: CUlongCmdlineObj::QueryLineArgType, protected, const // // Synoposis: returns a character pointer to the line arg type. // // Arguments: None. // // Returns: const NLS_STR reference to string. // // History: 28-Jul-92 davey Created. // //-------------------------------------------------------------------- LPCNSTR CUlongCmdlineObj::QueryLineArgType() const { // if user has not defined one then give default one if (_pnszLineArgType == NULL) { return(nszLineArgUlong); } else { return(_pnszLineArgType); } }
30.435583
80
0.476618
npocmaka
f5c439f14ae46e7826367041aa2f7d45ce4728e8
600
cpp
C++
frameworks/compile/mclinker/lib/LD/BinaryReader.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2022-01-07T01:53:19.000Z
2022-01-07T01:53:19.000Z
frameworks/compile/mclinker/lib/LD/BinaryReader.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
null
null
null
frameworks/compile/mclinker/lib/LD/BinaryReader.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2020-02-28T02:48:42.000Z
2020-02-28T02:48:42.000Z
//===- BinaryReader.cpp ---------------------------------------------------===// // // The MCLinker Project // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <mcld/LD/BinaryReader.h> using namespace mcld; //===----------------------------------------------------------------------===// // BinaryReader //===----------------------------------------------------------------------===// BinaryReader::~BinaryReader() { }
30
80
0.336667
touxiong88
f5c52e1ac31fdcdac60c7b27e3ee47cb3433f7b9
4,698
hpp
C++
test/sgraph/sgraph_check_degree_count.hpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1
2018-12-15T20:03:51.000Z
2018-12-15T20:03:51.000Z
test/sgraph/sgraph_check_degree_count.hpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
3
2021-09-08T02:18:00.000Z
2022-03-12T00:39:44.000Z
test/sgraph/sgraph_check_degree_count.hpp
ZeroInfinite/turicreate
dd210c2563930881abd51fd69cb73007955b33fd
[ "BSD-3-Clause" ]
1
2019-06-01T18:49:28.000Z
2019-06-01T18:49:28.000Z
/* Copyright © 2017 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #ifndef TURI_SGRAPH_TEST_DEGREE_COUNT_HPP #define TURI_SGRAPH_TEST_DEGREE_COUNT_HPP #include <sgraph/sgraph.hpp> #include "sgraph_test_util.hpp" using namespace turi; typedef std::function< std::vector<std::pair<flexible_type, flexible_type>>(sgraph&, sgraph::edge_direction)> degree_count_fn_type; // Takes a degree count function (graph, DIR) -> [(id, degree), (id_degree)] // Check it computes the right degree on various of graphs void check_degree_count(degree_count_fn_type degree_count_fn) { size_t n_vertex = 1000; size_t n_partition = 4; typedef sgraph::edge_direction edge_direction; { // for single directional ring graph sgraph g = create_ring_graph(n_vertex, n_partition, false /* one direction */); std::vector<std::pair<flexible_type, flexible_type>> in_degree = degree_count_fn(g, edge_direction::IN_EDGE); std::vector<std::pair<flexible_type, flexible_type>> out_degree = degree_count_fn(g, edge_direction::OUT_EDGE); std::vector<std::pair<flexible_type, flexible_type>> total_degree = degree_count_fn(g, edge_direction::ANY_EDGE); TS_ASSERT_EQUALS(in_degree.size(), g.num_vertices()); TS_ASSERT_EQUALS(out_degree.size(), g.num_vertices()); TS_ASSERT_EQUALS(total_degree.size(), g.num_vertices()); for (size_t i = 0; i < g.num_vertices(); ++i) { TS_ASSERT_EQUALS((int)out_degree[i].second, 1); TS_ASSERT_EQUALS((int)in_degree[i].second, 1); TS_ASSERT_EQUALS((int)total_degree[i].second, 2); TS_ASSERT_EQUALS((int)out_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); TS_ASSERT_EQUALS((int)in_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); TS_ASSERT_EQUALS((int)total_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); } } { // for bi-directional ring graph sgraph g = create_ring_graph(n_vertex, n_partition, true /* bi direction */); std::vector<std::pair<flexible_type, flexible_type>> in_degree = degree_count_fn(g, edge_direction::IN_EDGE); std::vector<std::pair<flexible_type, flexible_type>> out_degree = degree_count_fn(g, edge_direction::OUT_EDGE); std::vector<std::pair<flexible_type, flexible_type>> total_degree = degree_count_fn(g, edge_direction::ANY_EDGE); TS_ASSERT_EQUALS(in_degree.size(), g.num_vertices()); TS_ASSERT_EQUALS(out_degree.size(), g.num_vertices()); TS_ASSERT_EQUALS(total_degree.size(), g.num_vertices()); for (size_t i = 0; i < g.num_vertices(); ++i) { TS_ASSERT_EQUALS((int)out_degree[i].second, 2); TS_ASSERT_EQUALS((int)in_degree[i].second, 2); TS_ASSERT_EQUALS((int)total_degree[i].second, 4); TS_ASSERT_EQUALS((int)out_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); TS_ASSERT_EQUALS((int)in_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); TS_ASSERT_EQUALS((int)total_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); } } { // for star graph sgraph g = create_star_graph(n_vertex, n_partition); std::vector<std::pair<flexible_type, flexible_type>> in_degree = degree_count_fn(g, edge_direction::IN_EDGE); std::vector<std::pair<flexible_type, flexible_type>> out_degree = degree_count_fn(g, edge_direction::OUT_EDGE); std::vector<std::pair<flexible_type, flexible_type>> total_degree = degree_count_fn(g, edge_direction::ANY_EDGE); TS_ASSERT_EQUALS(in_degree.size(), g.num_vertices()); TS_ASSERT_EQUALS(out_degree.size(), g.num_vertices()); TS_ASSERT_EQUALS(total_degree.size(), g.num_vertices()); for (size_t i = 0; i < g.num_vertices(); ++i) { TS_ASSERT_EQUALS((int)in_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); TS_ASSERT_EQUALS((int)out_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); TS_ASSERT_EQUALS((int)total_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); if (in_degree[i].first == 0) { TS_ASSERT_EQUALS((int)in_degree[i].second, n_vertex -1); } else { TS_ASSERT_EQUALS((int)in_degree[i].second, 0); } if (out_degree[i].first == 0) { TS_ASSERT_EQUALS((int)out_degree[i].second, 0); } else { TS_ASSERT_EQUALS((int)out_degree[i].second, 1); } if (total_degree[i].first == 0) { TS_ASSERT_EQUALS((int)total_degree[i].second, n_vertex -1); } else { TS_ASSERT_EQUALS((int)total_degree[i].second, 1); } } } } #endif
48.43299
117
0.702214
shreyasvj25
f5c5d8e508da0c221d706f97a668b23b2a37a3bd
320
cpp
C++
src/IceRay/material/pattern/noise/cells.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
2
2020-09-04T12:27:15.000Z
2022-01-17T14:49:40.000Z
src/IceRay/material/pattern/noise/cells.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
null
null
null
src/IceRay/material/pattern/noise/cells.cpp
dmilos/IceRay
4e01f141363c0d126d3c700c1f5f892967e3d520
[ "MIT-0" ]
1
2020-09-04T12:27:52.000Z
2020-09-04T12:27:52.000Z
#include "./cells.hpp" namespace GS_DDMRM { namespace S_IceRay { namespace S_material { namespace S_pattern { namespace S_noise { GS_DDMRM::S_IceRay::S_utility::S_table::GC_value<3,1> GC_cells::M2s_table; } } } } }
14.545455
85
0.503125
dmilos
f5c7bbf52297d1b8792ae291df46b9db6ff3e567
2,260
cc
C++
src/cartographer_ros-release-1.0/cartographer_ros/cartographer_ros/ros_log_sink.cc
Louis-AD-git/racecar_ws
3c5cb561d1aee11d80a7f3847e0334e93f345513
[ "MIT" ]
1,019
2016-08-04T14:52:11.000Z
2020-04-02T09:08:03.000Z
cartographer_ros/cartographer_ros/ros_log_sink.cc
magiccjae/cartographer_ros
e2b20a052de03f188e3d65e88932d7ccec14a14a
[ "Apache-2.0" ]
1,194
2016-08-03T12:52:12.000Z
2020-04-03T04:53:11.000Z
cartographer_ros/cartographer_ros/ros_log_sink.cc
magiccjae/cartographer_ros
e2b20a052de03f188e3d65e88932d7ccec14a14a
[ "Apache-2.0" ]
795
2016-08-03T11:01:22.000Z
2020-04-03T13:05:21.000Z
/* * Copyright 2016 The Cartographer Authors * * 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 "cartographer_ros/ros_log_sink.h" #include <chrono> #include <cstring> #include <string> #include <thread> #include "glog/log_severity.h" #include "ros/console.h" namespace cartographer_ros { namespace { const char* GetBasename(const char* filepath) { const char* base = std::strrchr(filepath, '/'); return base ? (base + 1) : filepath; } } // namespace ScopedRosLogSink::ScopedRosLogSink() : will_die_(false) { AddLogSink(this); } ScopedRosLogSink::~ScopedRosLogSink() { RemoveLogSink(this); } void ScopedRosLogSink::send(const ::google::LogSeverity severity, const char* const filename, const char* const base_filename, const int line, const struct std::tm* const tm_time, const char* const message, const size_t message_len) { const std::string message_string = ::google::LogSink::ToString( severity, GetBasename(filename), line, tm_time, message, message_len); switch (severity) { case ::google::GLOG_INFO: ROS_INFO_STREAM(message_string); break; case ::google::GLOG_WARNING: ROS_WARN_STREAM(message_string); break; case ::google::GLOG_ERROR: ROS_ERROR_STREAM(message_string); break; case ::google::GLOG_FATAL: ROS_FATAL_STREAM(message_string); will_die_ = true; break; } } void ScopedRosLogSink::WaitTillSent() { if (will_die_) { // Give ROS some time to actually publish our message. std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } } } // namespace cartographer_ros
29.350649
77
0.672566
Louis-AD-git
f5caf7fa5c74e321e9096368497c76f477d0633c
21,479
cpp
C++
scopeprotocols/FIRFilter.cpp
adamgreig/scopehal
a96ed51a6122ce5595dc5ccf676e82fb3ab2ac47
[ "BSD-3-Clause" ]
1
2020-12-27T14:58:48.000Z
2020-12-27T14:58:48.000Z
scopeprotocols/FIRFilter.cpp
pd0wm/scopehal
da5dd5a79cd24726ba9da4a9c6356e0b0b4c2dcc
[ "BSD-3-Clause" ]
null
null
null
scopeprotocols/FIRFilter.cpp
pd0wm/scopehal
da5dd5a79cd24726ba9da4a9c6356e0b0b4c2dcc
[ "BSD-3-Clause" ]
null
null
null
/*********************************************************************************************************************** * * * ANTIKERNEL v0.1 * * * * Copyright (c) 2012-2020 Andrew D. Zonenberg * * 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 author nor the names of any contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD 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 "scopeprotocols.h" #include "FIRFilter.h" #include <immintrin.h> using namespace std; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Construction / destruction FIRFilter::FIRFilter(const string& color) : Filter( OscilloscopeChannel::CHANNEL_TYPE_ANALOG, color, CAT_MATH, "kernels/FIRFilter.cl", "FIRFilter") , m_filterTypeName("Filter Type") , m_filterLengthName("Length") , m_stopbandAttenName("Stopband Attenuation") , m_freqLowName("Frequency Low") , m_freqHighName("Frequency High") { CreateInput("in"); m_range = 1; m_offset = 0; m_min = FLT_MAX; m_max = -FLT_MAX; m_parameters[m_filterTypeName] = FilterParameter(FilterParameter::TYPE_ENUM, Unit(Unit::UNIT_COUNTS)); m_parameters[m_filterTypeName].AddEnumValue("Low pass", FILTER_TYPE_LOWPASS); m_parameters[m_filterTypeName].AddEnumValue("High pass", FILTER_TYPE_HIGHPASS); m_parameters[m_filterTypeName].AddEnumValue("Band pass", FILTER_TYPE_BANDPASS); m_parameters[m_filterTypeName].AddEnumValue("Notch", FILTER_TYPE_NOTCH); m_parameters[m_filterTypeName].SetIntVal(FILTER_TYPE_LOWPASS); m_parameters[m_filterLengthName] = FilterParameter(FilterParameter::TYPE_INT, Unit(Unit::UNIT_SAMPLEDEPTH)); m_parameters[m_filterLengthName].SetIntVal(0); m_parameters[m_stopbandAttenName] = FilterParameter(FilterParameter::TYPE_FLOAT, Unit(Unit::UNIT_DB)); m_parameters[m_stopbandAttenName].SetFloatVal(60); m_parameters[m_freqLowName] = FilterParameter(FilterParameter::TYPE_FLOAT, Unit(Unit::UNIT_HZ)); m_parameters[m_freqLowName].SetFloatVal(0); m_parameters[m_freqHighName] = FilterParameter(FilterParameter::TYPE_FLOAT, Unit(Unit::UNIT_HZ)); m_parameters[m_freqHighName].SetFloatVal(100e6); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Factory methods bool FIRFilter::ValidateChannel(size_t i, StreamDescriptor stream) { if(stream.m_channel == NULL) return false; if( (i == 0) && (stream.m_channel->GetType() == OscilloscopeChannel::CHANNEL_TYPE_ANALOG) ) return true; return false; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Accessors void FIRFilter::ClearSweeps() { m_range = 1; m_offset = 0; m_min = FLT_MAX; m_max = -FLT_MAX; } void FIRFilter::SetDefaultName() { char hwname[256]; auto type = static_cast<FilterType>(m_parameters[m_filterTypeName].GetIntVal()); switch(type) { case FILTER_TYPE_LOWPASS: snprintf(hwname, sizeof(hwname), "LPF(%s, %s)", GetInputDisplayName(0).c_str(), m_parameters[m_freqHighName].ToString().c_str()); break; case FILTER_TYPE_HIGHPASS: snprintf(hwname, sizeof(hwname), "HPF(%s, %s)", GetInputDisplayName(0).c_str(), m_parameters[m_freqLowName].ToString().c_str()); break; case FILTER_TYPE_BANDPASS: snprintf(hwname, sizeof(hwname), "BPF(%s, %s, %s)", GetInputDisplayName(0).c_str(), m_parameters[m_freqLowName].ToString().c_str(), m_parameters[m_freqHighName].ToString().c_str()); break; case FILTER_TYPE_NOTCH: snprintf(hwname, sizeof(hwname), "Notch(%s, %s, %s)", GetInputDisplayName(0).c_str(), m_parameters[m_freqLowName].ToString().c_str(), m_parameters[m_freqHighName].ToString().c_str()); break; } m_hwname = hwname; m_displayname = m_hwname; } string FIRFilter::GetProtocolName() { return "FIR Filter"; } bool FIRFilter::IsOverlay() { //we create a new analog channel return false; } bool FIRFilter::NeedsConfig() { return true; } double FIRFilter::GetVoltageRange() { return m_range; } double FIRFilter::GetOffset() { return m_offset; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Actual decoder logic void FIRFilter::Refresh() { //Sanity check if(!VerifyAllInputsOKAndAnalog()) { SetData(NULL, 0); return; } //Get input data auto din = GetAnalogInputWaveform(0); //Assume the input is dense packed, get the sample frequency int64_t fs_per_sample = din->m_timescale; float sample_hz = FS_PER_SECOND / fs_per_sample; //Calculate limits for our filter float nyquist = sample_hz / 2; float flo = m_parameters[m_freqLowName].GetFloatVal(); float fhi = m_parameters[m_freqHighName].GetFloatVal(); auto type = static_cast<FilterType>(m_parameters[m_filterTypeName].GetIntVal()); if(type == FILTER_TYPE_LOWPASS) flo = 0; else if(type == FILTER_TYPE_HIGHPASS) fhi = nyquist; else { //Swap high/low if they get swapped if(fhi < flo) { float ftmp = flo; flo = fhi; fhi = ftmp; } } flo = max(flo, 0.0f); fhi = min(fhi, nyquist); //Calculate filter order size_t filterlen = m_parameters[m_filterLengthName].GetIntVal(); float atten = m_parameters[m_stopbandAttenName].GetFloatVal(); if(filterlen == 0) filterlen = (atten / 22) * (sample_hz / (fhi - flo) ); filterlen |= 1; //force length to be odd //Create the filter coefficients (TODO: cache this) vector<float> coeffs; coeffs.resize(filterlen); CalculateFilterCoefficients( coeffs, flo / nyquist, fhi / nyquist, atten, type ); //Set up output m_xAxisUnit = m_inputs[0].m_channel->GetXAxisUnits(); m_yAxisUnit = m_inputs[0].m_channel->GetYAxisUnits(); size_t radius = (filterlen - 1) / 2; auto cap = SetupOutputWaveform(din, 0, 0, filterlen); //Run the actual filter float vmin; float vmax; DoFilterKernel(coeffs, din, cap, vmin, vmax); //Shift output to compensate for filter group delay cap->m_triggerPhase = (radius * fs_per_sample) + din->m_triggerPhase; //Calculate bounds m_max = max(m_max, vmax); m_min = min(m_min, vmin); m_range = (m_max - m_min) * 1.05; m_offset = -( (m_max - m_min)/2 + m_min ); } void FIRFilter::DoFilterKernel( vector<float>& coefficients, AnalogWaveform* din, AnalogWaveform* cap, float& vmin, float& vmax) { #ifdef HAVE_OPENCL if(g_clContext && m_kernel) DoFilterKernelOpenCL(coefficients, din, cap, vmin, vmax); else #endif if(g_hasAvx512F) DoFilterKernelAVX512F(coefficients, din, cap, vmin, vmax); else if(g_hasAvx2) DoFilterKernelAVX2(coefficients, din, cap, vmin, vmax); else DoFilterKernelGeneric(coefficients, din, cap, vmin, vmax); } #ifdef HAVE_OPENCL void FIRFilter::DoFilterKernelOpenCL( std::vector<float>& coefficients, AnalogWaveform* din, AnalogWaveform* cap, float& vmin, float& vmax) { //Setup size_t len = din->m_samples.size(); size_t filterlen = coefficients.size(); size_t end = len - filterlen; //Round size up to next multiple of block size //(must equal BLOCK_SIZE in kernel) const size_t blocksize = 1024; size_t globalsize = (end + blocksize); globalsize -= (globalsize % blocksize); //Allocate min/max buffer (first stage reduction on GPU, rest on CPU) size_t nblocks = globalsize / blocksize; vector<float> minmax; minmax.resize(2 * nblocks); try { //Allocate memory and copy to the GPU cl::Buffer inbuf(*g_clContext, din->m_samples.begin(), din->m_samples.end(), true, true, NULL); cl::Buffer coeffbuf(*g_clContext, coefficients.begin(), coefficients.end(), true, true, NULL); cl::Buffer outbuf(*g_clContext, cap->m_samples.begin(), cap->m_samples.end(), false, true, NULL); cl::Buffer minmaxbuf(*g_clContext, minmax.begin(), minmax.end(), false, true, NULL); //Run the filter cl::CommandQueue queue(*g_clContext, g_contextDevices[0], 0); m_kernel->setArg(0, inbuf); m_kernel->setArg(1, coeffbuf); m_kernel->setArg(2, outbuf); m_kernel->setArg(3, filterlen); m_kernel->setArg(4, end); m_kernel->setArg(5, minmaxbuf); queue.enqueueNDRangeKernel( *m_kernel, cl::NullRange, cl::NDRange(globalsize, 1), cl::NDRange(blocksize, 1), NULL); //Map/unmap the buffer to synchronize output with the CPU void* ptr = queue.enqueueMapBuffer(outbuf, true, CL_MAP_READ, 0, end * sizeof(float)); void* ptr2 = queue.enqueueMapBuffer(minmaxbuf, true, CL_MAP_READ, 0, 2 * nblocks * sizeof(float)); queue.enqueueUnmapMemObject(outbuf, ptr); queue.enqueueUnmapMemObject(minmaxbuf, ptr2); } catch(const cl::Error& e) { LogFatal("OpenCL error: %s (%d)\n", e.what(), e.err() ); } //Final reduction stage CPU-side vmin = FLT_MAX; vmax = -FLT_MAX; for(size_t i=0; i<nblocks; i++) { vmin = min(vmin, minmax[i*2]); vmax = max(vmax, minmax[i*2 + 1]); } } #endif /** @brief Performs a FIR filter (does not assume symmetric) */ void FIRFilter::DoFilterKernelGeneric( vector<float>& coefficients, AnalogWaveform* din, AnalogWaveform* cap, float& vmin, float& vmax) { //Setup vmin = FLT_MAX; vmax = -FLT_MAX; size_t len = din->m_samples.size(); size_t filterlen = coefficients.size(); size_t end = len - filterlen; //Do the filter for(size_t i=0; i<end; i++) { float v = 0; for(size_t j=0; j<filterlen; j++) v += din->m_samples[i + j] * coefficients[j]; vmin = min(vmin, v); vmax = max(vmax, v); cap->m_samples[i] = v; } } /** @brief Optimized FIR implementation Uses AVX2, but not AVX512 or FMA. */ __attribute__((target("avx2"))) void FIRFilter::DoFilterKernelAVX2( vector<float>& coefficients, AnalogWaveform* din, AnalogWaveform* cap, float& vmin, float& vmax) { __m256 vmin_x8 = { FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX }; __m256 vmax_x8 = { -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX }; //Save some pointers and sizes size_t len = din->m_samples.size(); size_t filterlen = coefficients.size(); size_t end = len - filterlen; size_t end_rounded = end - (end % 64); float* pin = (float*)&din->m_samples[0]; float* pout = (float*)&cap->m_samples[0]; //Vectorized and unrolled outer loop size_t i=0; for(; i<end_rounded; i += 64) { float* base = pin + i; //First tap __m256 coeff = _mm256_set1_ps(coefficients[0]); __m256 vin_a = _mm256_loadu_ps(base + 0); __m256 vin_b = _mm256_loadu_ps(base + 8); __m256 vin_c = _mm256_loadu_ps(base + 16); __m256 vin_d = _mm256_loadu_ps(base + 24); __m256 vin_e = _mm256_loadu_ps(base + 32); __m256 vin_f = _mm256_loadu_ps(base + 40); __m256 vin_g = _mm256_loadu_ps(base + 48); __m256 vin_h = _mm256_loadu_ps(base + 56); __m256 v_a = _mm256_mul_ps(coeff, vin_a); __m256 v_b = _mm256_mul_ps(coeff, vin_b); __m256 v_c = _mm256_mul_ps(coeff, vin_c); __m256 v_d = _mm256_mul_ps(coeff, vin_d); __m256 v_e = _mm256_mul_ps(coeff, vin_e); __m256 v_f = _mm256_mul_ps(coeff, vin_f); __m256 v_g = _mm256_mul_ps(coeff, vin_g); __m256 v_h = _mm256_mul_ps(coeff, vin_h); //Subsequent taps for(size_t j=1; j<filterlen; j++) { coeff = _mm256_set1_ps(coefficients[j]); vin_a = _mm256_loadu_ps(base + j + 0); vin_b = _mm256_loadu_ps(base + j + 8); vin_c = _mm256_loadu_ps(base + j + 16); vin_d = _mm256_loadu_ps(base + j + 24); vin_e = _mm256_loadu_ps(base + j + 32); vin_f = _mm256_loadu_ps(base + j + 40); vin_g = _mm256_loadu_ps(base + j + 48); vin_h = _mm256_loadu_ps(base + j + 56); __m256 prod_a = _mm256_mul_ps(coeff, vin_a); __m256 prod_b = _mm256_mul_ps(coeff, vin_b); __m256 prod_c = _mm256_mul_ps(coeff, vin_c); __m256 prod_d = _mm256_mul_ps(coeff, vin_d); __m256 prod_e = _mm256_mul_ps(coeff, vin_e); __m256 prod_f = _mm256_mul_ps(coeff, vin_f); __m256 prod_g = _mm256_mul_ps(coeff, vin_g); __m256 prod_h = _mm256_mul_ps(coeff, vin_h); v_a = _mm256_add_ps(prod_a, v_a); v_b = _mm256_add_ps(prod_b, v_b); v_c = _mm256_add_ps(prod_c, v_c); v_d = _mm256_add_ps(prod_d, v_d); v_e = _mm256_add_ps(prod_e, v_e); v_f = _mm256_add_ps(prod_f, v_f); v_g = _mm256_add_ps(prod_g, v_g); v_h = _mm256_add_ps(prod_h, v_h); } //Store the output _mm256_store_ps(pout + i + 0, v_a); _mm256_store_ps(pout + i + 8, v_b); _mm256_store_ps(pout + i + 16, v_c); _mm256_store_ps(pout + i + 24, v_d); _mm256_store_ps(pout + i + 32, v_e); _mm256_store_ps(pout + i + 40, v_f); _mm256_store_ps(pout + i + 48, v_g); _mm256_store_ps(pout + i + 56, v_h); //Calculate min/max: First level __m256 min_ab = _mm256_min_ps(v_a, v_b); __m256 min_cd = _mm256_min_ps(v_c, v_d); __m256 min_ef = _mm256_min_ps(v_e, v_f); __m256 min_gh = _mm256_min_ps(v_g, v_h); __m256 max_ab = _mm256_max_ps(v_a, v_b); __m256 max_cd = _mm256_max_ps(v_c, v_d); __m256 max_ef = _mm256_max_ps(v_e, v_f); __m256 max_gh = _mm256_max_ps(v_g, v_h); //Min/max: second level __m256 min_abcd = _mm256_min_ps(min_ab, min_cd); __m256 min_efgh = _mm256_min_ps(min_ef, min_gh); __m256 max_abcd = _mm256_max_ps(max_ab, max_cd); __m256 max_efgh = _mm256_max_ps(max_ef, max_gh); //Min/max: third level __m256 min_l3 = _mm256_min_ps(min_abcd, min_efgh); __m256 max_l3 = _mm256_max_ps(max_abcd, max_efgh); //Min/max: final reduction vmin_x8 = _mm256_min_ps(vmin_x8, min_l3); vmax_x8 = _mm256_max_ps(vmax_x8, max_l3); } //Horizontal reduction of vector min/max float tmp_min[8] __attribute__((aligned(32))); float tmp_max[8] __attribute__((aligned(32))); _mm256_store_ps(tmp_min, vmin_x8); _mm256_store_ps(tmp_max, vmax_x8); for(int j=0; j<8; j++) { vmin = min(vmin, tmp_min[j]); vmax = max(vmax, tmp_max[j]); } //Catch any stragglers for(; i<end_rounded; i++) { float v = 0; for(size_t j=0; j<filterlen; j++) v += din->m_samples[i + j] * coefficients[j]; vmin = min(vmin, v); vmax = max(vmax, v); cap->m_samples[i] = v; } } /** @brief Optimized AVX512F implementation */ __attribute__((target("avx512f"))) void FIRFilter::DoFilterKernelAVX512F( vector<float>& coefficients, AnalogWaveform* din, AnalogWaveform* cap, float& vmin, float& vmax) { __m512 vmin_x16 = _mm512_set1_ps(FLT_MAX); __m512 vmax_x16 = _mm512_set1_ps(-FLT_MAX); //Save some pointers and sizes size_t len = din->m_samples.size(); size_t filterlen = coefficients.size(); size_t end = len - filterlen; size_t end_rounded = end - (end % 64); float* pin = (float*)&din->m_samples[0]; float* pout = (float*)&cap->m_samples[0]; //Vectorized and unrolled outer loop size_t i=0; for(; i<end_rounded; i += 64) { float* base = pin + i; //First tap __m512 coeff = _mm512_set1_ps(coefficients[0]); __m512 vin_a = _mm512_loadu_ps(base + 0); __m512 vin_b = _mm512_loadu_ps(base + 16); __m512 vin_c = _mm512_loadu_ps(base + 32); __m512 vin_d = _mm512_loadu_ps(base + 48); __m512 v_a = _mm512_mul_ps(coeff, vin_a); __m512 v_b = _mm512_mul_ps(coeff, vin_b); __m512 v_c = _mm512_mul_ps(coeff, vin_c); __m512 v_d = _mm512_mul_ps(coeff, vin_d); //Subsequent taps for(size_t j=1; j<filterlen; j++) { coeff = _mm512_set1_ps(coefficients[j]); vin_a = _mm512_loadu_ps(base + j + 0); vin_b = _mm512_loadu_ps(base + j + 16); vin_c = _mm512_loadu_ps(base + j + 32); vin_d = _mm512_loadu_ps(base + j + 48); v_a = _mm512_fmadd_ps(coeff, vin_a, v_a); v_b = _mm512_fmadd_ps(coeff, vin_b, v_b); v_c = _mm512_fmadd_ps(coeff, vin_c, v_c); v_d = _mm512_fmadd_ps(coeff, vin_d, v_d); } //Store the output _mm512_store_ps(pout + i + 0, v_a); _mm512_store_ps(pout + i + 16, v_b); _mm512_store_ps(pout + i + 32, v_c); _mm512_store_ps(pout + i + 48, v_d); //Calculate min/max: First level __m512 min_ab = _mm512_min_ps(v_a, v_b); __m512 min_cd = _mm512_min_ps(v_c, v_d); __m512 max_ab = _mm512_max_ps(v_a, v_b); __m512 max_cd = _mm512_max_ps(v_c, v_d); //Min/max: second level __m512 min_abcd = _mm512_min_ps(min_ab, min_cd); __m512 max_abcd = _mm512_max_ps(max_ab, max_cd); //Min/max: final reduction vmin_x16 = _mm512_min_ps(vmin_x16, min_abcd); vmax_x16 = _mm512_max_ps(vmax_x16, max_abcd); } //Horizontal reduction of vector min/max float tmp_min[16] __attribute__((aligned(64))); float tmp_max[16] __attribute__((aligned(64))); _mm512_store_ps(tmp_min, vmin_x16); _mm512_store_ps(tmp_max, vmax_x16); for(int j=0; j<16; j++) { vmin = min(vmin, tmp_min[j]); vmax = max(vmax, tmp_max[j]); } //Catch any stragglers for(; i<end_rounded; i++) { float v = 0; for(size_t j=0; j<filterlen; j++) v += din->m_samples[i + j] * coefficients[j]; vmin = min(vmin, v); vmax = max(vmax, v); cap->m_samples[i] = v; } } /** @brief Calculates FIR coefficients Based on public domain code at https://www.arc.id.au/FilterDesign.html Cutoff frequencies are specified in fractions of the Nyquist limit (Fsample/2). @param coefficients Output buffer @param fa Left side passband (0 for LPF) @param fb Right side passband (1 for HPF) @param stopbandAtten Stop-band attenuation, in dB @param type Type of filter */ void FIRFilter::CalculateFilterCoefficients( vector<float>& coefficients, float fa, float fb, float stopbandAtten, FilterType type) { //Calculate the impulse response of the filter size_t len = coefficients.size(); size_t np = (len - 1) / 2; vector<float> impulse; impulse.push_back(fb-fa); for(size_t j=1; j<=np; j++) impulse.push_back( (sin(j*M_PI*fb) - sin(j*M_PI*fa)) /(j*M_PI) ); //Calculate window scaling factor for stopband attenuation float alpha = 0; if(stopbandAtten < 21) alpha = 0; else if(stopbandAtten > 50) alpha = 0.1102 * (stopbandAtten - 8.7); else alpha = 0.5842 * pow(stopbandAtten-21, 0.4) + 0.07886*(stopbandAtten-21); //Final windowing (Kaiser-Bessel) float ia = Bessel(alpha); if(type == FILTER_TYPE_NOTCH) { for(size_t j=0; j<=np; j++) coefficients[np+j] = -impulse[j] * Bessel(alpha * sqrt(1 - ((j*j*1.0)/(np*np)))) / ia; coefficients[np] += 1; } else { for(size_t j=0; j<=np; j++) coefficients[np+j] = impulse[j] * Bessel(alpha * sqrt(1 - ((j*j*1.0)/(np*np)))) / ia; } for(size_t j=0; j<=np; j++) coefficients[j] = coefficients[len-1-j]; } /** @brief 0th order Bessel function */ float FIRFilter::Bessel(float x) { float d = 0; float ds = 1; float s = 1; while(ds > s*1e-6) { d += 2; ds *= (x*x)/(d*d); s += ds; } return s; }
31.402047
120
0.622701
adamgreig
f5ccb13a069bd4e6510be3c0edd2a7ea4508684d
3,295
cpp
C++
test/performance/alphabet/alphabet_assign_char_benchmark.cpp
mr-c/seqan3
f1975b614937c497e578a079180a1322442dde3a
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
test/performance/alphabet/alphabet_assign_char_benchmark.cpp
mr-c/seqan3
f1975b614937c497e578a079180a1322442dde3a
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
test/performance/alphabet/alphabet_assign_char_benchmark.cpp
mr-c/seqan3
f1975b614937c497e578a079180a1322442dde3a
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- #include <algorithm> #include <cstring> #include <numeric> #include <benchmark/benchmark.h> #include <seqan3/alphabet/all.hpp> #include <seqan3/test/seqan2.hpp> #if SEQAN3_HAS_SEQAN2 #include <seqan/align.h> #include <seqan/basic.h> #include <seqan/modifier.h> #endif template <seqan3::alphabet alphabet_t> void assign_char(benchmark::State & state) { using char_t = seqan3::alphabet_char_t<alphabet_t>; std::array<char_t, 256> chars{}; std::iota(chars.begin(), chars.end(), 0); alphabet_t a{}; for (auto _ : state) for (char_t c : chars) benchmark::DoNotOptimize(seqan3::assign_char_to(c, a)); } /* regular alphabets, sorted by size */ BENCHMARK_TEMPLATE(assign_char, seqan3::gap); BENCHMARK_TEMPLATE(assign_char, seqan3::dna4); BENCHMARK_TEMPLATE(assign_char, seqan3::rna4); BENCHMARK_TEMPLATE(assign_char, seqan3::dna5); BENCHMARK_TEMPLATE(assign_char, seqan3::rna5); BENCHMARK_TEMPLATE(assign_char, seqan3::dna15); BENCHMARK_TEMPLATE(assign_char, seqan3::rna15); BENCHMARK_TEMPLATE(assign_char, seqan3::aa20); BENCHMARK_TEMPLATE(assign_char, seqan3::aa27); BENCHMARK_TEMPLATE(assign_char, seqan3::phred42); BENCHMARK_TEMPLATE(assign_char, seqan3::phred63); /* adaptations */ BENCHMARK_TEMPLATE(assign_char, char); BENCHMARK_TEMPLATE(assign_char, char32_t); /* alphabet variant */ BENCHMARK_TEMPLATE(assign_char, seqan3::gapped<seqan3::dna4>); BENCHMARK_TEMPLATE(assign_char, seqan3::alphabet_variant<seqan3::gap, seqan3::dna4, seqan3::dna5, seqan3::dna15, seqan3::rna15, seqan3::rna4, seqan3::rna5>); BENCHMARK_TEMPLATE(assign_char, seqan3::alphabet_variant<seqan3::dna4, char>); /* alphabet tuple */ BENCHMARK_TEMPLATE(assign_char, seqan3::masked<seqan3::dna4>); BENCHMARK_TEMPLATE(assign_char, seqan3::qualified<seqan3::dna4, seqan3::phred42>); BENCHMARK_TEMPLATE(assign_char, seqan3::qualified<seqan3::dna5, seqan3::phred63>); #if SEQAN3_HAS_SEQAN2 template <typename alphabet_t> void assign_char_seqan2(benchmark::State & state) { std::array<char, 256> chars{}; std::iota(chars.begin(), chars.end(), 0); alphabet_t a{}; for (auto _ : state) for (char c : chars) benchmark::DoNotOptimize(a = c); } BENCHMARK_TEMPLATE(assign_char_seqan2, seqan::Dna); BENCHMARK_TEMPLATE(assign_char_seqan2, seqan::Rna); BENCHMARK_TEMPLATE(assign_char_seqan2, seqan::Dna5); BENCHMARK_TEMPLATE(assign_char_seqan2, seqan::Rna5); BENCHMARK_TEMPLATE(assign_char_seqan2, seqan::Iupac); BENCHMARK_TEMPLATE(assign_char_seqan2, seqan::AminoAcid); BENCHMARK_TEMPLATE(assign_char_seqan2, seqan::Dna5Q); BENCHMARK_TEMPLATE(assign_char_seqan2, typename seqan::GappedValueType<seqan::Dna>::Type); #endif BENCHMARK_MAIN();
37.873563
112
0.700759
mr-c
f5cd8edcce6b2ab80301b10999ca540023b06dc7
28,923
cxx
C++
Interaction/Widgets/vtkPointHandleRepresentation3D.cxx
DmitrySemikin/vtk-mirror
7e70ac8c84797c7603686bd9bf8030c2ad8f101f
[ "BSD-3-Clause" ]
1
2021-07-21T07:15:44.000Z
2021-07-21T07:15:44.000Z
Interaction/Widgets/vtkPointHandleRepresentation3D.cxx
DmitrySemikin/vtk-mirror
7e70ac8c84797c7603686bd9bf8030c2ad8f101f
[ "BSD-3-Clause" ]
null
null
null
Interaction/Widgets/vtkPointHandleRepresentation3D.cxx
DmitrySemikin/vtk-mirror
7e70ac8c84797c7603686bd9bf8030c2ad8f101f
[ "BSD-3-Clause" ]
2
2020-03-24T14:09:05.000Z
2021-09-17T09:30:26.000Z
/*========================================================================= Program: Visualization Toolkit Module: vtkPointHandleRepresentation3D.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPointHandleRepresentation3D.h" #include "vtkActor.h" #include "vtkAssemblyPath.h" #include "vtkCamera.h" #include "vtkCellPicker.h" #include "vtkCoordinate.h" #include "vtkCursor3D.h" #include "vtkEventData.h" #include "vtkFocalPlanePointPlacer.h" #include "vtkInteractorObserver.h" #include "vtkLine.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPickingManager.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include <assert.h> vtkStandardNewMacro(vtkPointHandleRepresentation3D); vtkCxxSetObjectMacro(vtkPointHandleRepresentation3D, Property, vtkProperty); vtkCxxSetObjectMacro(vtkPointHandleRepresentation3D, SelectedProperty, vtkProperty); //---------------------------------------------------------------------- vtkPointHandleRepresentation3D::vtkPointHandleRepresentation3D() { // Initialize state this->InteractionState = vtkHandleRepresentation::Outside; // Represent the line this->Cursor3D = vtkCursor3D::New(); this->Cursor3D->AllOff(); this->Cursor3D->AxesOn(); this->Cursor3D->TranslationModeOn(); this->Mapper = vtkPolyDataMapper::New(); this->Mapper->SetInputConnection(this->Cursor3D->GetOutputPort()); // Set up the initial properties this->CreateDefaultProperties(); this->Actor = vtkActor::New(); this->Actor->SetMapper(this->Mapper); this->Actor->SetProperty(this->Property); // Manage the picking stuff this->CursorPicker = vtkCellPicker::New(); this->CursorPicker->PickFromListOn(); this->CursorPicker->AddPickList(this->Actor); this->CursorPicker->SetTolerance(0.01); // need some fluff // Override superclass' this->PlaceFactor = 1.0; // The size of the hot spot this->HotSpotSize = 0.05; this->WaitingForMotion = 0; this->ConstraintAxis = -1; // Current handle size this->HandleSize = 15.0; // in pixels this->CurrentHandleSize = this->HandleSize; // Translation control this->TranslationMode = 1; vtkFocalPlanePointPlacer* pointPlacer = vtkFocalPlanePointPlacer::New(); this->SetPointPlacer(pointPlacer); pointPlacer->Delete(); // Continuous moves this->SmoothMotion = 1; } //---------------------------------------------------------------------- vtkPointHandleRepresentation3D::~vtkPointHandleRepresentation3D() { this->Cursor3D->Delete(); this->CursorPicker->Delete(); this->Mapper->Delete(); this->Actor->Delete(); this->Property->Delete(); this->SelectedProperty->Delete(); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::RegisterPickers() { vtkPickingManager* pm = this->GetPickingManager(); if (!pm) { return; } pm->AddPicker(this->CursorPicker, this); } //------------------------------------------------------------------------- void vtkPointHandleRepresentation3D::PlaceWidget(double bds[6]) { int i; double bounds[6], center[3]; this->AdjustBounds(bds, bounds, center); this->Cursor3D->SetModelBounds(bounds); this->SetWorldPosition(center); for (i = 0; i < 6; i++) { this->InitialBounds[i] = bounds[i]; } this->InitialLength = sqrt((bounds[1] - bounds[0]) * (bounds[1] - bounds[0]) + (bounds[3] - bounds[2]) * (bounds[3] - bounds[2]) + (bounds[5] - bounds[4]) * (bounds[5] - bounds[4])); } //------------------------------------------------------------------------- double* vtkPointHandleRepresentation3D::GetBounds() { return this->Cursor3D->GetModelBounds(); } //------------------------------------------------------------------------- void vtkPointHandleRepresentation3D::SetWorldPosition(double p[3]) { if (this->Renderer && this->PointPlacer) { if (this->PointPlacer->ValidateWorldPosition(p)) { this->Cursor3D->SetFocalPoint(p); // this may clamp the point this->WorldPosition->SetValue(this->Cursor3D->GetFocalPoint()); this->WorldPositionTime.Modified(); } } else { this->Cursor3D->SetFocalPoint(p); // this may clamp the point this->WorldPosition->SetValue(this->Cursor3D->GetFocalPoint()); this->WorldPositionTime.Modified(); } } //------------------------------------------------------------------------- void vtkPointHandleRepresentation3D::SetDisplayPosition(double p[3]) { if (this->Renderer && this->PointPlacer) { if (this->PointPlacer->ValidateDisplayPosition(this->Renderer, p)) { double worldPos[3], worldOrient[9]; if (this->PointPlacer->ComputeWorldPosition(this->Renderer, p, worldPos, worldOrient)) { this->DisplayPosition->SetValue(p); this->WorldPosition->SetValue(worldPos); this->DisplayPositionTime.Modified(); this->SetWorldPosition(this->WorldPosition->GetValue()); } } } else { this->DisplayPosition->SetValue(p); this->DisplayPositionTime.Modified(); } } //------------------------------------------------------------------------- void vtkPointHandleRepresentation3D::SetHandleSize(double size) { this->Superclass::SetHandleSize(size); this->CurrentHandleSize = this->HandleSize; } //------------------------------------------------------------------------- int vtkPointHandleRepresentation3D ::ComputeInteractionState(int X, int Y, int vtkNotUsed(modify)) { this->VisibilityOn(); // actor must be on to be picked // First make sure that the cursor is within the bounding sphere of the // representation in display space. double d[3], bounds[6]; this->Cursor3D->GetModelBounds(bounds); this->GetDisplayPosition(d); if (!this->NearbyEvent(X, Y, bounds)) { this->InteractionState = vtkHandleRepresentation::Outside; return this->InteractionState; } // Now see if anything is picked vtkAssemblyPath* path = this->GetAssemblyPath(X, Y, 0., this->CursorPicker); if (path != nullptr) { this->InteractionState = vtkHandleRepresentation::Nearby; } else { this->InteractionState = vtkHandleRepresentation::Outside; if (this->ActiveRepresentation) { this->VisibilityOff(); } } return this->InteractionState; } //------------------------------------------------------------------------- int vtkPointHandleRepresentation3D::ComputeComplexInteractionState( vtkRenderWindowInteractor*, vtkAbstractWidget*, unsigned long, void* calldata, int) { this->VisibilityOn(); // actor must be on to be picked vtkEventData* edata = static_cast<vtkEventData*>(calldata); vtkEventDataDevice3D* edd = edata->GetAsEventDataDevice3D(); if (edd) { double pos[3]; edd->GetWorldPosition(pos); vtkAssemblyPath* path = this->GetAssemblyPath3DPoint(pos, this->CursorPicker); double focus[3]; this->Cursor3D->GetFocalPoint(focus); double d[3]; this->GetDisplayPosition(d); if (path != nullptr) { this->InteractionState = vtkHandleRepresentation::Nearby; } else { this->InteractionState = vtkHandleRepresentation::Outside; if (this->ActiveRepresentation) { this->VisibilityOff(); } } } return this->InteractionState; } //------------------------------------------------------------------------- int vtkPointHandleRepresentation3D::DetermineConstraintAxis( int constraint, double* x, double* startPickPoint) { // Look for trivial cases if (!this->Constrained) { return -1; } else if (constraint >= 0 && constraint < 3) { return constraint; } // Okay, figure out constraint. First see if the choice is // outside the hot spot if (!x) { double p[3], d2, tol; this->CursorPicker->GetPickPosition(p); d2 = vtkMath::Distance2BetweenPoints(p, this->LastPickPosition); tol = this->HotSpotSize * this->InitialLength; if (d2 > (tol * tol)) { this->WaitingForMotion = 0; return this->CursorPicker->GetCellId(); } else { this->WaitingForMotion = 1; this->WaitCount = 0; return -1; } } else if (x) { this->WaitingForMotion = 0; double v[3]; v[0] = fabs(x[0] - startPickPoint[0]); v[1] = fabs(x[1] - startPickPoint[1]); v[2] = fabs(x[2] - startPickPoint[2]); return (v[0] > v[1] ? (v[0] > v[2] ? 0 : 2) : (v[1] > v[2] ? 1 : 2)); } else { return -1; } } //---------------------------------------------------------------------- // Record the current event position, and the translation state void vtkPointHandleRepresentation3D::StartWidgetInteraction(double startEventPos[2]) { this->StartEventPosition[0] = startEventPos[0]; this->StartEventPosition[1] = startEventPos[1]; this->StartEventPosition[2] = 0.0; this->LastEventPosition[0] = startEventPos[0]; this->LastEventPosition[1] = startEventPos[1]; // Make sure events are close to widget and something is picked double bounds[6]; this->Cursor3D->GetModelBounds(bounds); bool nearby = this->NearbyEvent(startEventPos[0], startEventPos[1], bounds); vtkAssemblyPath* path = this->GetAssemblyPath(startEventPos[0], startEventPos[1], 0., this->CursorPicker); if (nearby && path != nullptr) { this->InteractionState = vtkHandleRepresentation::Nearby; this->ConstraintAxis = -1; this->CursorPicker->GetPickPosition(this->LastPickPosition); } else { this->InteractionState = vtkHandleRepresentation::Outside; this->ConstraintAxis = -1; } this->Cursor3D->SetTranslationMode(this->TranslationMode); this->WaitCount = 0; } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::StartComplexInteraction( vtkRenderWindowInteractor*, vtkAbstractWidget*, unsigned long, void* calldata) { vtkEventData* edata = static_cast<vtkEventData*>(calldata); vtkEventDataDevice3D* edd = edata->GetAsEventDataDevice3D(); if (edd) { edd->GetWorldPosition(this->StartEventPosition); this->LastEventPosition[0] = this->StartEventPosition[0]; this->LastEventPosition[1] = this->StartEventPosition[1]; this->LastEventPosition[2] = this->StartEventPosition[2]; double bounds[6]; this->Cursor3D->GetModelBounds(bounds); bool nearby = this->NearbyEvent(this->StartEventPosition[0], this->StartEventPosition[1], bounds); vtkAssemblyPath* path = this->GetAssemblyPath3DPoint(this->StartEventPosition, this->CursorPicker); if (nearby && path != nullptr) { this->InteractionState = vtkHandleRepresentation::Nearby; this->ConstraintAxis = -1; this->CursorPicker->GetPickPosition(this->LastPickPosition); } else { this->InteractionState = vtkHandleRepresentation::Outside; this->ConstraintAxis = -1; } this->Cursor3D->SetTranslationMode(this->TranslationMode); this->WaitCount = 0; } } //---------------------------------------------------------------------- // Based on the displacement vector (computed in display coordinates) and // the cursor state (which corresponds to which part of the widget has been // selected), the widget points are modified. // First construct a local coordinate system based on the display coordinates // of the widget. void vtkPointHandleRepresentation3D::WidgetInteraction(double eventPos[2]) { // Do different things depending on state // Calculations everybody does double focalPoint[4], pickPoint[4], prevPickPoint[4], startPickPoint[4], z; // Compute the two points defining the motion vector vtkInteractorObserver::ComputeWorldToDisplay(this->Renderer, this->LastPickPosition[0], this->LastPickPosition[1], this->LastPickPosition[2], focalPoint); z = focalPoint[2]; vtkInteractorObserver::ComputeDisplayToWorld( this->Renderer, this->LastEventPosition[0], this->LastEventPosition[1], z, prevPickPoint); vtkInteractorObserver::ComputeDisplayToWorld( this->Renderer, eventPos[0], eventPos[1], z, pickPoint); // Process the motion if (this->InteractionState == vtkHandleRepresentation::Selecting || this->InteractionState == vtkHandleRepresentation::Translating) { this->WaitCount++; if (this->WaitCount > 3 || !this->Constrained) { vtkInteractorObserver::ComputeDisplayToWorld(this->Renderer, this->StartEventPosition[0], this->StartEventPosition[1], z, startPickPoint); this->ConstraintAxis = this->DetermineConstraintAxis(this->ConstraintAxis, pickPoint, startPickPoint); if (this->InteractionState == vtkHandleRepresentation::Selecting && !this->TranslationMode) { vtkDebugMacro(<< "Processing widget interaction for Select mode"); // If we are doing axis constrained motion, ignore the placer. // Can't have both the placer and an axis constraint dictating // handle placement. if (this->ConstraintAxis >= 0 || this->Constrained || !this->PointPlacer) { this->MoveFocus(prevPickPoint, pickPoint); } else { double newCenterPointRequested[3]; // displayPosition double newCenterPoint[3], worldOrient[9]; // Make a request for the new position. this->MoveFocusRequest(prevPickPoint, pickPoint, eventPos, newCenterPointRequested); vtkFocalPlanePointPlacer* fPlacer = vtkFocalPlanePointPlacer::SafeDownCast(this->PointPlacer); if (fPlacer) { // Offset the placer plane to one that passes through the current // world position and is parallel to the focal plane. Offset = // the distance currentWorldPos is from the focal plane // double currentWorldPos[3], projDir[3], fp[3]; this->GetWorldPosition(currentWorldPos); this->Renderer->GetActiveCamera()->GetFocalPoint(fp); double vec[3] = { currentWorldPos[0] - fp[0], currentWorldPos[1] - fp[1], currentWorldPos[2] - fp[2] }; this->Renderer->GetActiveCamera()->GetDirectionOfProjection(projDir); fPlacer->SetOffset(vtkMath::Dot(vec, projDir)); } vtkDebugMacro(<< "Request for computing world position at " << "display position of " << newCenterPointRequested[0] << "," << newCenterPointRequested[1]); // See what the placer says. if (this->PointPlacer->ComputeWorldPosition( this->Renderer, newCenterPointRequested, newCenterPoint, worldOrient)) { // Once the placer has validated us, update the handle position this->SetWorldPosition(newCenterPoint); } } } else { vtkDebugMacro(<< "Processing widget interaction for translate"); // If we are doing axis constrained motion, ignore the placer. // Can't have both the placer and the axis constraint dictating // handle placement. if (this->ConstraintAxis >= 0 || this->Constrained || !this->PointPlacer) { this->Translate(prevPickPoint, pickPoint); } else { double newCenterPointRequested[3]; // displayPosition double newCenterPoint[3], worldOrient[9]; // Make a request for the new position. this->MoveFocusRequest(prevPickPoint, pickPoint, eventPos, newCenterPointRequested); vtkFocalPlanePointPlacer* fPlacer = vtkFocalPlanePointPlacer::SafeDownCast(this->PointPlacer); if (fPlacer) { // Offset the placer plane to one that passes through the current // world position and is parallel to the focal plane. Offset = // the distance currentWorldPos is from the focal plane // double currentWorldPos[3], projDir[3], fp[3]; this->GetWorldPosition(currentWorldPos); this->Renderer->GetActiveCamera()->GetFocalPoint(fp); double vec[3] = { currentWorldPos[0] - fp[0], currentWorldPos[1] - fp[1], currentWorldPos[2] - fp[2] }; this->Renderer->GetActiveCamera()->GetDirectionOfProjection(projDir); fPlacer->SetOffset(vtkMath::Dot(vec, projDir)); } vtkDebugMacro(<< "Request for computing world position at " << "display position of " << newCenterPointRequested[0] << "," << newCenterPointRequested[1]); // See what the placer says. if (this->PointPlacer->ComputeWorldPosition( this->Renderer, newCenterPointRequested, newCenterPoint, worldOrient)) { // Once the placer has validated us, update the handle // position and its bounds. double* p = this->GetWorldPosition(); // Get the motion vector double v[3] = { newCenterPoint[0] - p[0], newCenterPoint[1] - p[1], newCenterPoint[2] - p[2] }; double *bounds = this->Cursor3D->GetModelBounds(), newBounds[6]; for (int i = 0; i < 3; i++) { newBounds[2 * i] = bounds[2 * i] + v[i]; newBounds[2 * i + 1] = bounds[2 * i + 1] + v[i]; } this->Cursor3D->SetModelBounds(newBounds); this->SetWorldPosition(newCenterPoint); } } } } } else if (this->InteractionState == vtkHandleRepresentation::Scaling) { // Scaling does not change the position of the handle, we needn't // ask the placer.. this->Scale(prevPickPoint, pickPoint, eventPos); } // Book keeping this->LastEventPosition[0] = eventPos[0]; this->LastEventPosition[1] = eventPos[1]; this->Modified(); } void vtkPointHandleRepresentation3D::ComplexInteraction( vtkRenderWindowInteractor*, vtkAbstractWidget*, unsigned long, void* calldata) { vtkEventData* edata = static_cast<vtkEventData*>(calldata); vtkEventDataDevice3D* edd = edata->GetAsEventDataDevice3D(); if (edd) { double eventPos[3]; edd->GetWorldPosition(eventPos); // Process the motion if (this->InteractionState == vtkHandleRepresentation::Selecting || this->InteractionState == vtkHandleRepresentation::Translating) { this->WaitCount++; if (this->WaitCount > 3 || !this->Constrained) { this->ConstraintAxis = this->DetermineConstraintAxis(this->ConstraintAxis, eventPos, this->StartEventPosition); if (this->InteractionState == vtkHandleRepresentation::Selecting && !this->TranslationMode) { vtkDebugMacro(<< "Processing widget interaction for Select mode"); this->MoveFocus(this->LastEventPosition, eventPos); } else { vtkDebugMacro(<< "Processing widget interaction for translate"); this->Translate(this->LastEventPosition, eventPos); } } } // Book keeping this->LastEventPosition[0] = eventPos[0]; this->LastEventPosition[1] = eventPos[1]; this->LastEventPosition[2] = eventPos[2]; this->Modified(); } } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D ::MoveFocusRequest( const double* p1, const double* p2, const double eventPos[2], double center[3]) { if (this->SmoothMotion) { double focus[4], v[3]; this->Cursor3D->GetFocalPoint(focus); this->GetTranslationVector(p1, p2, v); // Move the center of the handle along the motion vector focus[0] += v[0]; focus[1] += v[1]; focus[2] += v[2]; focus[3] = 1.0; // Get the display position that this center would fall on. this->Renderer->SetWorldPoint(focus); this->Renderer->WorldToDisplay(); this->Renderer->GetDisplayPoint(center); } else { center[0] = eventPos[0]; center[1] = eventPos[1]; center[2] = 1.0; } } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::MoveFocus(const double* p1, const double* p2) { this->Translate(p1, p2); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::SetTranslationMode(vtkTypeBool mode) { if (this->TranslationMode != mode) { this->TranslationMode = mode; // Pass new setting to Cursor3D, otherwise PlaceWidget will not work // as it should when TranslationMode is off. this->Cursor3D->SetTranslationMode(mode); this->Modified(); } } //---------------------------------------------------------------------- // Translate everything void vtkPointHandleRepresentation3D::Translate(const double* p1, const double* p2) { double v[3] = { 0, 0, 0 }; vtkHandleRepresentation::Translate(p1, p2); this->GetTranslationVector(p1, p2, v); double* bounds = this->Cursor3D->GetModelBounds(); double* pos = this->Cursor3D->GetFocalPoint(); double newBounds[6], newFocus[3]; int i; if (this->ConstraintAxis >= 0) { // move along axis for (i = 0; i < 3; i++) { if (i != this->ConstraintAxis) { v[i] = 0.0; } } } for (i = 0; i < 3; i++) { newBounds[2 * i] = bounds[2 * i] + v[i]; newBounds[2 * i + 1] = bounds[2 * i + 1] + v[i]; newFocus[i] = pos[i] + v[i]; } this->Cursor3D->SetModelBounds(newBounds); this->Cursor3D->SetFocalPoint(newFocus); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::SizeBounds() { // Only change the size of the bounding box if translation mode is on. if (this->TranslationMode) { double center[3], bounds[6]; this->Cursor3D->GetFocalPoint(center); double radius = this->SizeHandlesInPixels(1.0, center); radius *= this->CurrentHandleSize / this->HandleSize; for (int i = 0; i < 3; i++) { bounds[2 * i] = center[i] - radius; bounds[2 * i + 1] = center[i] + radius; } this->Cursor3D->SetModelBounds(bounds); } } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::Scale( const double* p1, const double* p2, const double eventPos[2]) { // Get the motion vector double v[3]; v[0] = p2[0] - p1[0]; v[1] = p2[1] - p1[1]; v[2] = p2[2] - p1[2]; double* bounds = this->Cursor3D->GetModelBounds(); // Compute the scale factor double sf = vtkMath::Norm(v) / sqrt((bounds[1] - bounds[0]) * (bounds[1] - bounds[0]) + (bounds[3] - bounds[2]) * (bounds[3] - bounds[2]) + (bounds[5] - bounds[4]) * (bounds[5] - bounds[4])); if (eventPos[1] > this->LastEventPosition[1]) { sf = 1.0 + sf; } else { sf = 1.0 - sf; } this->CurrentHandleSize *= sf; this->CurrentHandleSize = (this->CurrentHandleSize < 0.001 ? 0.001 : this->CurrentHandleSize); this->SizeBounds(); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::Highlight(int highlight) { if (highlight) { this->Actor->SetProperty(this->SelectedProperty); } else { this->Actor->SetProperty(this->Property); } } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::CreateDefaultProperties() { this->Property = vtkProperty::New(); this->Property->SetAmbient(1.0); this->Property->SetAmbientColor(1.0, 1.0, 1.0); this->Property->SetLineWidth(0.5); this->SelectedProperty = vtkProperty::New(); this->SelectedProperty->SetAmbient(1.0); this->SelectedProperty->SetAmbientColor(0.0, 1.0, 0.0); this->SelectedProperty->SetLineWidth(2.0); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::SetVisibility(vtkTypeBool visible) { this->Actor->SetVisibility(visible); // Forward to superclass this->Superclass::SetVisibility(visible); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::BuildRepresentation() { // The net effect is to resize the handle if (this->GetMTime() > this->BuildTime || (this->Renderer && this->Renderer->GetVTKWindow() && this->Renderer->GetVTKWindow()->GetMTime() > this->BuildTime)) { if (!this->Placed) { this->ValidPick = 1; this->Placed = 1; } this->SizeBounds(); this->Cursor3D->Update(); this->BuildTime.Modified(); } } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::ShallowCopy(vtkProp* prop) { vtkPointHandleRepresentation3D* rep = vtkPointHandleRepresentation3D::SafeDownCast(prop); if (rep) { this->SetOutline(rep->GetOutline()); this->SetXShadows(rep->GetXShadows()); this->SetYShadows(rep->GetYShadows()); this->SetZShadows(rep->GetZShadows()); this->SetTranslationMode(rep->GetTranslationMode()); this->SetProperty(rep->GetProperty()); this->Actor->SetProperty(rep->GetProperty()); this->SetSelectedProperty(rep->GetSelectedProperty()); this->SetHotSpotSize(rep->GetHotSpotSize()); } this->Superclass::ShallowCopy(prop); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::DeepCopy(vtkProp* prop) { vtkPointHandleRepresentation3D* rep = vtkPointHandleRepresentation3D::SafeDownCast(prop); if (rep) { this->SetOutline(rep->GetOutline()); this->SetXShadows(rep->GetXShadows()); this->SetYShadows(rep->GetYShadows()); this->SetZShadows(rep->GetZShadows()); this->SetTranslationMode(rep->GetTranslationMode()); this->SetProperty(rep->GetProperty()); this->Actor->SetProperty(rep->GetProperty()); this->SetSelectedProperty(rep->GetSelectedProperty()); this->SetHotSpotSize(rep->GetHotSpotSize()); } this->Superclass::DeepCopy(prop); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::GetActors(vtkPropCollection* pc) { this->Actor->GetActors(pc); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::ReleaseGraphicsResources(vtkWindow* win) { this->Actor->ReleaseGraphicsResources(win); } //---------------------------------------------------------------------- int vtkPointHandleRepresentation3D::RenderOpaqueGeometry(vtkViewport* viewport) { this->BuildRepresentation(); // Sanity check double worldPos[3]; this->GetWorldPosition(worldPos); if (worldPos[0] == VTK_DOUBLE_MAX) { return 0; } return this->Actor->RenderOpaqueGeometry(viewport); } //----------------------------------------------------------------------------- int vtkPointHandleRepresentation3D::RenderTranslucentPolygonalGeometry(vtkViewport* viewport) { this->BuildRepresentation(); // Sanity check double worldPos[3]; this->GetWorldPosition(worldPos); if (worldPos[0] == VTK_DOUBLE_MAX) { return 0; } return this->Actor->RenderTranslucentPolygonalGeometry(viewport); } //----------------------------------------------------------------------------- vtkTypeBool vtkPointHandleRepresentation3D::HasTranslucentPolygonalGeometry() { this->BuildRepresentation(); return this->Actor->HasTranslucentPolygonalGeometry(); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::PrintSelf(ostream& os, vtkIndent indent) { // Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os, indent); os << indent << "Hot Spot Size: " << this->HotSpotSize << "\n"; if (this->Property) { os << indent << "Property: " << this->Property << "\n"; } else { os << indent << "Property: (none)\n"; } if (this->SelectedProperty) { os << indent << "Selected Property: " << this->SelectedProperty << "\n"; } else { os << indent << "Selected Property: (none)\n"; } os << indent << "Outline: " << (this->GetOutline() ? "On\n" : "Off\n"); os << indent << "XShadows: " << (this->GetXShadows() ? "On\n" : "Off\n"); os << indent << "YShadows: " << (this->GetYShadows() ? "On\n" : "Off\n"); os << indent << "ZShadows: " << (this->GetZShadows() ? "On\n" : "Off\n"); os << indent << "Translation Mode: " << (this->TranslationMode ? "On\n" : "Off\n"); os << indent << "SmoothMotion: " << this->SmoothMotion << endl; }
32.136667
99
0.608097
DmitrySemikin
f5cedba503219973d90e24eda157451a4a95d3c5
83,256
cpp
C++
runtime/variable.cpp
redm-pro/mLang
67f12ecb9f8d451d2eeab1ed00e6e709ff52945d
[ "BSD-3-Clause" ]
null
null
null
runtime/variable.cpp
redm-pro/mLang
67f12ecb9f8d451d2eeab1ed00e6e709ff52945d
[ "BSD-3-Clause" ]
null
null
null
runtime/variable.cpp
redm-pro/mLang
67f12ecb9f8d451d2eeab1ed00e6e709ff52945d
[ "BSD-3-Clause" ]
null
null
null
/* $Author = Sargis Ananyan; $Corp = RedM Inc; $Web = https://redm.pro/; $Lincese = BSD 3; $Name = mLang; $Description = A programming language for web programming.; */ #pragma once bool empty_bool __attribute__ ((weak)); int empty_int __attribute__ ((weak)); double empty_float __attribute__ ((weak)); string empty_string __attribute__ ((weak)); char empty_array_var_storage[sizeof (array <var>)] __attribute__ ((weak)); array <var> *empty_array_var __attribute__ ((weak)) = reinterpret_cast <array <var> *> (empty_array_var_storage); var empty_var __attribute__ ((weak)); void var::copy_from (const var &other) { switch (other.type) { case NULL_TYPE: break; case BOOLEAN_TYPE: b = other.b; break; case INTEGER_TYPE: i = other.i; break; case FLOAT_TYPE: f = other.f; break; case STRING_TYPE: new (&s) string (*STRING(other.s)); break; case ARRAY_TYPE: new (&a) array <var> (*ARRAY(other.a)); break; case OBJECT_TYPE: new (&o) object (*OBJECT(other.o)); break; } type = other.type; } var::var (void): type (NULL_TYPE) { } var::var (const Unknown &u): type (NULL_TYPE) { php_assert ("Unknown used!!!" && 0); } var::var (bool b): type (BOOLEAN_TYPE), b (b) { } var::var (int i): type (INTEGER_TYPE), i (i) { } var::var (double f): type (FLOAT_TYPE), f (f) { } var::var (const string &s_): type (STRING_TYPE) { new (&s) string (s_); } var::var (const char *s_, int len): type (STRING_TYPE) { new (&s) string (s_, len); } template <class T> var::var (const array <T> &a_): type (ARRAY_TYPE) { new (&a) array <var> (a_); } template <class T> var::var (const object_ptr <T> &o_): type (OBJECT_TYPE) { new (&o) object (o_); } var::var (const OrFalse <int> &v) { if (likely (v.bool_value)) { type = INTEGER_TYPE; i = v.value; } else { type = BOOLEAN_TYPE; b = false; } } var::var (const OrFalse <double> &v) { if (likely (v.bool_value)) { type = FLOAT_TYPE; f = v.value; } else { type = BOOLEAN_TYPE; b = false; } } var::var (const OrFalse <string> &v) { if (likely (v.bool_value)) { type = STRING_TYPE; new (&s) string (v.value); } else { type = BOOLEAN_TYPE; b = false; } } template <class T> var::var (const OrFalse <array <T> > &v) { if (likely (v.bool_value)) { type = ARRAY_TYPE; new (&a) array <var> (v.value); } else { type = BOOLEAN_TYPE; b = false; } } template <class T> var::var (const OrFalse <object_ptr <T> > &v) { if (likely (v.bool_value)) { type = OBJECT_TYPE; new (&o) object (v.value); } else { type = BOOLEAN_TYPE; b = false; } } var::var (const var &v) { copy_from (v); } var& var::operator = (bool other) { switch (type) { case NULL_TYPE: type = BOOLEAN_TYPE; b = other; return *this; case BOOLEAN_TYPE: b = other; return *this; case INTEGER_TYPE: type = BOOLEAN_TYPE; b = other; return *this; case FLOAT_TYPE: type = BOOLEAN_TYPE; b = other; return *this; case STRING_TYPE: STRING(s)->~string(); type = BOOLEAN_TYPE; b = other; return *this; case ARRAY_TYPE: ARRAY(a)->~array <var>(); type = BOOLEAN_TYPE; b = other; return *this; case OBJECT_TYPE: OBJECT(o)->~object(); type = BOOLEAN_TYPE; b = other; return *this; default: php_assert (0); exit (1); } } var& var::operator = (int other) { switch (type) { case NULL_TYPE: type = INTEGER_TYPE; i = other; return *this; case BOOLEAN_TYPE: type = INTEGER_TYPE; i = other; return *this; case INTEGER_TYPE: i = other; return *this; case FLOAT_TYPE: type = INTEGER_TYPE; i = other; return *this; case STRING_TYPE: STRING(s)->~string(); type = INTEGER_TYPE; i = other; return *this; case ARRAY_TYPE: ARRAY(a)->~array <var>(); type = INTEGER_TYPE; i = other; return *this; case OBJECT_TYPE: OBJECT(o)->~object(); type = INTEGER_TYPE; i = other; return *this; default: php_assert (0); exit (1); } } var& var::operator = (double other) { switch (type) { case NULL_TYPE: type = FLOAT_TYPE; f = other; return *this; case BOOLEAN_TYPE: type = FLOAT_TYPE; f = other; return *this; case INTEGER_TYPE: type = FLOAT_TYPE; f = other; return *this; case FLOAT_TYPE: f = other; return *this; case STRING_TYPE: STRING(s)->~string(); type = FLOAT_TYPE; f = other; return *this; case ARRAY_TYPE: ARRAY(a)->~array <var>(); type = FLOAT_TYPE; f = other; return *this; case OBJECT_TYPE: OBJECT(o)->~object(); type = FLOAT_TYPE; f = other; return *this; default: php_assert (0); exit (1); } } var& var::operator = (const string &other) { switch (type) { case NULL_TYPE: type = STRING_TYPE; new (&s) string (other); return *this; case BOOLEAN_TYPE: type = STRING_TYPE; new (&s) string (other); return *this; case INTEGER_TYPE: type = STRING_TYPE; new (&s) string (other); return *this; case FLOAT_TYPE: type = STRING_TYPE; new (&s) string (other); return *this; case STRING_TYPE: *STRING(s) = other; return *this; case ARRAY_TYPE: ARRAY(a)->~array <var>(); type = STRING_TYPE; new (&s) string (other); return *this; case OBJECT_TYPE: OBJECT(o)->~object(); type = STRING_TYPE; new (&s) string (other); return *this; default: php_assert (0); exit (1); } } var& var::assign (const char *other, int len) { switch (type) { case NULL_TYPE: type = STRING_TYPE; new (&s) string (other, len); return *this; case BOOLEAN_TYPE: type = STRING_TYPE; new (&s) string (other, len); return *this; case INTEGER_TYPE: type = STRING_TYPE; new (&s) string (other, len); return *this; case FLOAT_TYPE: type = STRING_TYPE; new (&s) string (other, len); return *this; case STRING_TYPE: STRING(s)->assign (other, len); return *this; case ARRAY_TYPE: ARRAY(a)->~array <var>(); type = STRING_TYPE; new (&s) string (other, len); return *this; case OBJECT_TYPE: OBJECT(o)->~object(); type = STRING_TYPE; new (&s) string (other, len); return *this; default: php_assert (0); exit (1); } } template <class T> var& var::operator = (const array <T> &other) { switch (type) { case NULL_TYPE: type = ARRAY_TYPE; new (&a) array <var> (other); return *this; case BOOLEAN_TYPE: type = ARRAY_TYPE; new (&a) array <var> (other); return *this; case INTEGER_TYPE: type = ARRAY_TYPE; new (&a) array <var> (other); return *this; case FLOAT_TYPE: type = ARRAY_TYPE; new (&a) array <var> (other); return *this; case STRING_TYPE: STRING(s)->~string(); type = ARRAY_TYPE; new (&a) array <var> (other); return *this; case ARRAY_TYPE: *ARRAY(a) = other; return *this; case OBJECT_TYPE: OBJECT(o)->~object(); type = ARRAY_TYPE; new (&a) array <var> (other); return *this; default: php_assert (0); exit (1); } } template <class T> var& var::operator = (const object_ptr <T> &other) { switch (type) { case NULL_TYPE: type = OBJECT_TYPE; new (&o) object (other); return *this; case BOOLEAN_TYPE: type = OBJECT_TYPE; new (&o) object (other); return *this; case INTEGER_TYPE: type = OBJECT_TYPE; new (&o) object (other); return *this; case FLOAT_TYPE: type = OBJECT_TYPE; new (&o) object (other); return *this; case STRING_TYPE: STRING(s)->~string(); type = OBJECT_TYPE; new (&o) object (other); return *this; case ARRAY_TYPE: ARRAY(a)->~array <var>(); type = OBJECT_TYPE; new (&o) object (other); return *this; case OBJECT_TYPE: *OBJECT(o) = other; return *this; default: php_assert (0); exit (1); } } var& var::operator = (const var &other) { if (this != &other) { destroy(); copy_from (other); } return *this; /* switch (other.type) { case NULL_TYPE: destroy(); type = NULL_TYPE; return *this; case BOOLEAN_TYPE: return *this = other.b; case INTEGER_TYPE: return *this = other.i; case FLOAT_TYPE: return *this = other.f; case STRING_TYPE: return *this = *STRING(other.s); case ARRAY_TYPE: return *this = *ARRAY(other.a); case OBJECT_TYPE: return *this = *OBJECT(other.o); default: php_assert (0); exit (1); }*/ } var& var::operator = (const OrFalse <int> &other) { destroy(); if (likely (other.bool_value)) { type = INTEGER_TYPE; i = other.value; } else { type = BOOLEAN_TYPE; b = false; } return *this; } var& var::operator = (const OrFalse <double> &other) { destroy(); if (likely (other.bool_value)) { type = FLOAT_TYPE; f = other.value; } else { type = BOOLEAN_TYPE; b = false; } return *this; } var& var::operator = (const OrFalse <string> &other) { if (likely (other.bool_value)) { *this = other.value; } else { destroy(); type = BOOLEAN_TYPE; b = false; } return *this; } template <class T> var& var::operator = (const OrFalse <array <T> > &other) { if (likely (other.bool_value)) { *this = other.value; } else { destroy(); type = BOOLEAN_TYPE; b = false; } return *this; } template <class T> var& var::operator = (const OrFalse <object_ptr <T> > &other) { if (likely (other.bool_value)) { *this = other.value; } else { destroy(); type = BOOLEAN_TYPE; b = false; } return *this; } const var var::operator - (void) const { var arg1 = to_numeric(); if (arg1.type == INTEGER_TYPE) { arg1.i = -arg1.i; } else { arg1.f = -arg1.f; } return arg1; } const var var::operator + (void) const { return to_numeric(); } int var::operator ~(void) const { return ~to_int(); } var& var::operator += (const var &other) { if (likely (type == INTEGER_TYPE && other.type == INTEGER_TYPE)) { i += other.i; return *this; } if (unlikely (type == ARRAY_TYPE || other.type == ARRAY_TYPE)) { if (type == ARRAY_TYPE && other.type == ARRAY_TYPE) { *ARRAY(a) += *ARRAY(other.a); } else { php_warning ("Unsupported operand types for operator += (%s and %s)", get_type_c_str(), other.get_type_c_str()); } return *this; } convert_to_numeric(); const var arg2 = other.to_numeric(); if (type == INTEGER_TYPE) { if (arg2.type == INTEGER_TYPE) { i += arg2.i; } else { type = FLOAT_TYPE; f = i + arg2.f; } } else { if (arg2.type == INTEGER_TYPE) { f += arg2.i; } else { f += arg2.f; } } return *this; } var& var::operator -= (const var &other) { if (likely (type == INTEGER_TYPE && other.type == INTEGER_TYPE)) { i -= other.i; return *this; } convert_to_numeric(); const var arg2 = other.to_numeric(); if (type == INTEGER_TYPE) { if (arg2.type == INTEGER_TYPE) { i -= arg2.i; } else { type = FLOAT_TYPE; f = i - arg2.f; } } else { if (arg2.type == INTEGER_TYPE) { f -= arg2.i; } else { f -= arg2.f; } } return *this; } var& var::operator *= (const var &other) { if (likely (type == INTEGER_TYPE && other.type == INTEGER_TYPE)) { i *= other.i; return *this; } convert_to_numeric(); const var arg2 = other.to_numeric(); if (type == INTEGER_TYPE) { if (arg2.type == INTEGER_TYPE) { i *= arg2.i; } else { type = FLOAT_TYPE; f = i * arg2.f; } } else { if (arg2.type == INTEGER_TYPE) { f *= arg2.i; } else { f *= arg2.f; } } return *this; } var& var::operator /= (const var &other) { if (likely (type == INTEGER_TYPE && other.type == INTEGER_TYPE)) { if (i % other.i == 0) { i /= other.i; } else { type = FLOAT_TYPE; f = (double)i / other.i; } return *this; } convert_to_numeric(); const var arg2 = other.to_numeric(); if (arg2.type == INTEGER_TYPE) { if (arg2.i == 0) { php_warning ("Integer division by zero"); type = BOOLEAN_TYPE; b = false; return *this; } if (type == INTEGER_TYPE) { if (i % arg2.i == 0) { i /= arg2.i; } else { type = FLOAT_TYPE; f = (double)i / other.i; } } else { f /= arg2.i; } } else { if (arg2.f == 0) { php_warning ("Float division by zero"); type = BOOLEAN_TYPE; b = false; return *this; } if (type == INTEGER_TYPE) { type = FLOAT_TYPE; f = i / arg2.f; } else { f /= arg2.f; } } return *this; } var& var::operator %= (const var &other) { int div = other.to_int(); if (div == 0) { php_warning ("Modulo by zero"); *this = false; return *this; } convert_to_int(); i %= div; return *this; } var& var::operator &= (const var &other) { convert_to_int(); i &= other.to_int(); return *this; } var& var::operator |= (const var &other) { convert_to_int(); i |= other.to_int(); return *this; } var& var::operator ^= (const var &other) { convert_to_int(); i ^= other.to_int(); return *this; } var& var::operator <<= (const var &other) { convert_to_int(); i <<= other.to_int(); return *this; } var& var::operator >>= (const var &other) { convert_to_int(); i >>= other.to_int(); return *this; } var& var::safe_set_add (const var &other) { if (likely (type == INTEGER_TYPE && other.type == INTEGER_TYPE)) { ::safe_set_add (i, other.i); return *this; } if (unlikely (type == ARRAY_TYPE || other.type == ARRAY_TYPE)) { if (type == ARRAY_TYPE && other.type == ARRAY_TYPE) { *ARRAY(a) += *ARRAY(other.a); } else { php_warning ("Unsupported operand types for operator += (%s and %s)", get_type_c_str(), other.get_type_c_str()); } return *this; } convert_to_numeric(); const var arg2 = other.to_numeric(); if (type == INTEGER_TYPE) { if (arg2.type == INTEGER_TYPE) { ::safe_set_add (i, arg2.i); } else { type = FLOAT_TYPE; f = i + arg2.f; } } else { if (arg2.type == INTEGER_TYPE) { f += arg2.i; } else { f += arg2.f; } } return *this; } var& var::safe_set_sub (const var &other) { if (likely (type == INTEGER_TYPE && other.type == INTEGER_TYPE)) { ::safe_set_sub (i, other.i); return *this; } convert_to_numeric(); const var arg2 = other.to_numeric(); if (type == INTEGER_TYPE) { if (arg2.type == INTEGER_TYPE) { ::safe_set_sub (i, arg2.i); } else { type = FLOAT_TYPE; f = i - arg2.f; } } else { if (arg2.type == INTEGER_TYPE) { f -= arg2.i; } else { f -= arg2.f; } } return *this; } var& var::safe_set_mul (const var &other) { if (likely (type == INTEGER_TYPE && other.type == INTEGER_TYPE)) { ::safe_set_mul (i, other.i); return *this; } convert_to_numeric(); const var arg2 = other.to_numeric(); if (type == INTEGER_TYPE) { if (arg2.type == INTEGER_TYPE) { ::safe_set_mul (i, arg2.i); } else { type = FLOAT_TYPE; f = i * arg2.f; } } else { if (arg2.type == INTEGER_TYPE) { f *= arg2.i; } else { f *= arg2.f; } } return *this; } var& var::safe_set_shl (const var &other) { safe_convert_to_int(); ::safe_set_shl (i, other.safe_to_int()); return *this; } var& var::operator ++ (void) { switch (type) { case NULL_TYPE: type = INTEGER_TYPE; i = 1; return *this; case BOOLEAN_TYPE: php_warning ("Can't apply operator ++ to boolean"); return *this; case INTEGER_TYPE: ++i; return *this; case FLOAT_TYPE: f += 1; return *this; case STRING_TYPE: *this = STRING(s)->to_numeric(); return ++(*this); case ARRAY_TYPE: php_warning ("Can't apply operator ++ to array"); return *this; case OBJECT_TYPE: php_warning ("Can't apply operator ++ to object"); return *this; default: php_assert (0); exit (1); } } const var var::operator ++ (int) { switch (type) { case NULL_TYPE: type = INTEGER_TYPE; i = 1; return var(); case BOOLEAN_TYPE: php_warning ("Can't apply operator ++ to boolean"); return b; case INTEGER_TYPE: { var res (i); ++i; return res; } case FLOAT_TYPE: { var res (f); f += 1; return res; } case STRING_TYPE: { var res (*STRING(s)); *this = STRING(s)->to_numeric(); (*this)++; return res; } case ARRAY_TYPE: php_warning ("Can't apply operator ++ to array"); return *ARRAY(a); case OBJECT_TYPE: php_warning ("Can't apply operator ++ to object"); return *this; default: php_assert (0); exit (1); } } var& var::operator -- (void) { if (likely (type == INTEGER_TYPE)) { --i; return *this; } switch (type) { case NULL_TYPE: php_warning ("Can't apply operator -- to null"); return *this; case BOOLEAN_TYPE: php_warning ("Can't apply operator -- to boolean"); return *this; case INTEGER_TYPE: --i; return *this; case FLOAT_TYPE: f -= 1; return *this; case STRING_TYPE: *this = STRING(s)->to_numeric(); return --(*this); case ARRAY_TYPE: php_warning ("Can't apply operator -- to array"); return *this; case OBJECT_TYPE: php_warning ("Can't apply operator -- to object"); return *this; default: php_assert (0); exit (1); } } const var var::operator -- (int) { if (likely (type == INTEGER_TYPE)) { var res (i); --i; return res; } switch (type) { case NULL_TYPE: php_warning ("Can't apply operator -- to null"); return var(); case BOOLEAN_TYPE: php_warning ("Can't apply operator -- to boolean"); return b; case INTEGER_TYPE: { var res (i); --i; return res; } case FLOAT_TYPE: { var res (f); f -= 1; return res; } case STRING_TYPE: { var res (*STRING(s)); *this = STRING(s)->to_numeric(); (*this)--; return res; } case ARRAY_TYPE: php_warning ("Can't apply operator -- to array"); return *ARRAY(a); case OBJECT_TYPE: php_warning ("Can't apply operator -- to object"); return *this; default: php_assert (0); exit (1); } } var& var::safe_incr_pre (void) { switch (type) { case NULL_TYPE: type = INTEGER_TYPE; i = 1; return *this; case BOOLEAN_TYPE: php_warning ("Can't apply operator ++ to boolean"); return *this; case INTEGER_TYPE: ::safe_incr_pre (i); return *this; case FLOAT_TYPE: f += 1; return *this; case STRING_TYPE: *this = STRING(s)->to_numeric(); return safe_incr_pre(); case ARRAY_TYPE: php_warning ("Can't apply operator ++ to array"); return *this; case OBJECT_TYPE: php_warning ("Can't apply operator ++ to object"); return *this; default: php_assert (0); exit (1); } } const var var::safe_incr_post (void) { switch (type) { case NULL_TYPE: type = INTEGER_TYPE; i = 1; return var(); case BOOLEAN_TYPE: php_warning ("Can't apply operator ++ to boolean"); return b; case INTEGER_TYPE: { var res (i); ::safe_incr_post (i); return res; } case FLOAT_TYPE: { var res (f); f += 1; return res; } case STRING_TYPE: { var res (*STRING(s)); *this = STRING(s)->to_numeric(); safe_incr_post(); return res; } case ARRAY_TYPE: php_warning ("Can't apply operator ++ to array"); return *ARRAY(a); case OBJECT_TYPE: php_warning ("Can't apply operator ++ to object"); return *this; default: php_assert (0); exit (1); } } var& var::safe_decr_pre (void) { switch (type) { case NULL_TYPE: php_warning ("Can't apply operator -- to null"); return *this; case BOOLEAN_TYPE: php_warning ("Can't apply operator -- to boolean"); return *this; case INTEGER_TYPE: ::safe_decr_pre (i); return *this; case FLOAT_TYPE: f -= 1; return *this; case STRING_TYPE: *this = STRING(s)->to_numeric(); return safe_decr_pre(); case ARRAY_TYPE: php_warning ("Can't apply operator -- to array"); return *this; case OBJECT_TYPE: php_warning ("Can't apply operator -- to object"); return *this; default: php_assert (0); exit (1); } } const var var::safe_decr_post (void) { switch (type) { case NULL_TYPE: php_warning ("Can't apply operator -- to null"); return var(); case BOOLEAN_TYPE: php_warning ("Can't apply operator -- to boolean"); return b; case INTEGER_TYPE: { var res (i); ::safe_decr_post (i); return res; } case FLOAT_TYPE: { var res (f); f -= 1; return res; } case STRING_TYPE: { var res (*STRING(s)); *this = STRING(s)->to_numeric(); safe_decr_post(); return res; } case ARRAY_TYPE: php_warning ("Can't apply operator -- to array"); return *ARRAY(a); case OBJECT_TYPE: php_warning ("Can't apply operator -- to object"); return *this; default: php_assert (0); exit (1); } } bool var::operator ! (void) const { return !to_bool(); } var& var::append (const string &v) { if (unlikely (type != STRING_TYPE)) { convert_to_string(); } STRING(s)->append (v); return *this; } void var::destroy (void) { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: break; case STRING_TYPE: STRING(s)->~string(); break; case ARRAY_TYPE: ARRAY(a)->~array <var>(); break; case OBJECT_TYPE: OBJECT(o)->~object(); break; default: php_assert (0); exit (1); } } var::~var (void) { destroy(); type = NULL_TYPE; } const var var::to_numeric (void) const { switch (type) { case NULL_TYPE: return 0; case BOOLEAN_TYPE: return (b ? 1 : 0); case INTEGER_TYPE: return i; case FLOAT_TYPE: return f; case STRING_TYPE: return STRING(s)->to_numeric(); case ARRAY_TYPE: php_warning ("Wrong convertion from array to number"); return ARRAY(a)->to_int(); case OBJECT_TYPE: php_warning ("Wrong convertion from object to number"); return 1; default: php_assert (0); exit (1); } } bool var::to_bool (void) const { switch (type) { case NULL_TYPE: return false; case BOOLEAN_TYPE: return b; case INTEGER_TYPE: return (bool)i; case FLOAT_TYPE: return (bool)f; case STRING_TYPE: return STRING(s)->to_bool(); case ARRAY_TYPE: return !ARRAY(a)->empty(); case OBJECT_TYPE: return true; default: php_assert (0); exit (1); } } int var::to_int (void) const { switch (type) { case NULL_TYPE: return 0; case BOOLEAN_TYPE: return (int)b; case INTEGER_TYPE: return i; case FLOAT_TYPE: return (int)f; case STRING_TYPE: return STRING(s)->to_int(); case ARRAY_TYPE: php_warning ("Wrong convertion from array to int"); return ARRAY(a)->to_int(); case OBJECT_TYPE: php_warning ("Wrong convertion from object to int"); return 1; default: php_assert (0); exit (1); } } double var::to_float (void) const { switch (type) { case NULL_TYPE: return 0.0; case BOOLEAN_TYPE: return (b ? 1.0 : 0.0); case INTEGER_TYPE: return (double)i; case FLOAT_TYPE: return f; case STRING_TYPE: return STRING(s)->to_float(); case ARRAY_TYPE: php_warning ("Wrong convertion from array to float"); return ARRAY(a)->to_float(); case OBJECT_TYPE: php_warning ("Wrong convertion from object to float"); return 1.0; default: php_assert (0); exit (1); } } const string var::to_string (void) const { switch (type) { case NULL_TYPE: return string(); case BOOLEAN_TYPE: return (b ? string ("1", 1) : string()); case INTEGER_TYPE: return string (i); case FLOAT_TYPE: return string (f); case STRING_TYPE: return *STRING(s); case ARRAY_TYPE: php_warning ("Convertion from array to string"); return string ("Array", 5); case OBJECT_TYPE: return OBJECT(o)->to_string(); default: php_assert (0); exit (1); } } const array <var> var::to_array (void) const { switch (type) { case NULL_TYPE: return array <var>(); case BOOLEAN_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: case STRING_TYPE: { array <var> res (array_size (1, 0, true)); res.push_back (*this); return res; } case ARRAY_TYPE: return *ARRAY(a); case OBJECT_TYPE: return OBJECT(o)->to_array(); default: php_assert (0); exit (1); } } const object var::to_object (void) const { switch (type) { case NULL_TYPE: return object(); case BOOLEAN_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: case STRING_TYPE: { object res; res.set (string ("scalar", 6), *this); return res; } case ARRAY_TYPE: return ARRAY(a)->to_object(); case OBJECT_TYPE: return *OBJECT(o); default: php_assert (0); exit (1); } } int var::safe_to_int (void) const { switch (type) { case NULL_TYPE: return 0; case BOOLEAN_TYPE: return (int)b; case INTEGER_TYPE: return i; case FLOAT_TYPE: if (fabs (f) > 2147483648) { php_warning ("Wrong convertion from double %.6lf to int", f); } return (int)f; case STRING_TYPE: return STRING(s)->safe_to_int(); case ARRAY_TYPE: php_warning ("Wrong convertion from array to int"); return ARRAY(a)->to_int(); case OBJECT_TYPE: php_warning ("Wrong convertion from object to int"); return 1; default: php_assert (0); exit (1); } } void var::convert_to_numeric (void) { switch (type) { case NULL_TYPE: type = INTEGER_TYPE; i = 0; return; case BOOLEAN_TYPE: type = INTEGER_TYPE; i = b; return; case INTEGER_TYPE: case FLOAT_TYPE: return; case STRING_TYPE: *this = STRING(s)->to_numeric(); return; case ARRAY_TYPE: { php_warning ("Wrong convertion from array to number"); int int_val = ARRAY(a)->to_int(); ARRAY(a)->~array <var>(); type = INTEGER_TYPE; i = int_val; return; } case OBJECT_TYPE: php_warning ("Wrong convertion from object to number"); OBJECT(o)->~object(); type = INTEGER_TYPE; i = 1; return; default: php_assert (0); exit (1); } } void var::convert_to_bool (void) { switch (type) { case NULL_TYPE: type = BOOLEAN_TYPE; b = 0; return; case BOOLEAN_TYPE: return; case INTEGER_TYPE: type = BOOLEAN_TYPE; b = (bool)i; return; case FLOAT_TYPE: type = BOOLEAN_TYPE; b = (bool)f; return; case STRING_TYPE: { bool bool_val = STRING(s)->to_bool(); STRING(s)->~string(); type = BOOLEAN_TYPE; b = bool_val; return; } case ARRAY_TYPE: { bool bool_val = ARRAY(a)->to_bool(); ARRAY(a)->~array <var>(); type = BOOLEAN_TYPE; b = bool_val; return; } case OBJECT_TYPE: OBJECT(o)->~object(); type = BOOLEAN_TYPE; b = true; return; default: php_assert (0); exit (1); } } void var::convert_to_int (void) { switch (type) { case NULL_TYPE: type = INTEGER_TYPE; i = 0; return; case BOOLEAN_TYPE: type = INTEGER_TYPE; i = b; return; case INTEGER_TYPE: return; case FLOAT_TYPE: type = INTEGER_TYPE; i = (int)f; return; case STRING_TYPE: { int int_val = STRING(s)->to_int(); STRING(s)->~string(); type = INTEGER_TYPE; i = int_val; return; } case ARRAY_TYPE: { php_warning ("Wrong convertion from array to int"); int int_val = ARRAY(a)->to_int(); ARRAY(a)->~array <var>(); type = INTEGER_TYPE; i = int_val; return; } case OBJECT_TYPE: php_warning ("Wrong convertion from object to int"); OBJECT(o)->~object(); type = INTEGER_TYPE; i = 1; return; default: php_assert (0); exit (1); } } void var::convert_to_float (void) { switch (type) { case NULL_TYPE: type = FLOAT_TYPE; f = 0.0; return; case BOOLEAN_TYPE: type = FLOAT_TYPE; f = b; return; case INTEGER_TYPE: type = FLOAT_TYPE; f = (double)i; return; case FLOAT_TYPE: return; case STRING_TYPE: { double float_val = STRING(s)->to_float(); STRING(s)->~string(); type = FLOAT_TYPE; f = float_val; return; } case ARRAY_TYPE: { php_warning ("Wrong convertion from array to float"); double float_val = ARRAY(a)->to_float(); ARRAY(a)->~array <var>(); type = FLOAT_TYPE; f = float_val; return; } case OBJECT_TYPE: php_warning ("Wrong convertion from object to float"); OBJECT(o)->~object(); type = FLOAT_TYPE; f = 1.0; return; default: php_assert (0); exit (1); } } void var::convert_to_string (void) { switch (type) { case NULL_TYPE: type = STRING_TYPE; new (&s) string(); return; case BOOLEAN_TYPE: type = STRING_TYPE; if (b) { new (&s) string ("1", 1); } else { new (&s) string(); } return; case INTEGER_TYPE: type = STRING_TYPE; new (&s) string (i); return; case FLOAT_TYPE: type = STRING_TYPE; new (&s) string (f); return; case STRING_TYPE: return; case ARRAY_TYPE: php_warning ("Converting from array to string"); ARRAY(a)->~array <var>(); type = STRING_TYPE; new (&s) string ("Array", 5); return; case OBJECT_TYPE: { string res = OBJECT(o)->to_string(); OBJECT(o)->~object(); type = STRING_TYPE; new (&s) string (res); return; } default: php_assert (0); exit (1); } } void var::safe_convert_to_int (void) { switch (type) { case NULL_TYPE: type = INTEGER_TYPE; i = 0; return; case BOOLEAN_TYPE: type = INTEGER_TYPE; i = (int)b; return; case INTEGER_TYPE: return; case FLOAT_TYPE: type = INTEGER_TYPE; if (fabs (f) > 2147483648) { php_warning ("Wrong convertion from double %.6lf to int", f); } i = (int)f; return; case STRING_TYPE: { int int_val = STRING(s)->safe_to_int(); STRING(s)->~string(); type = INTEGER_TYPE; i = int_val; return; } case ARRAY_TYPE: { php_warning ("Wrong convertion from array to int"); int int_val = ARRAY(a)->to_int(); ARRAY(a)->~array <var>(); type = INTEGER_TYPE; i = int_val; return; } case OBJECT_TYPE: php_warning ("Wrong convertion from object to int"); OBJECT(o)->~object(); type = INTEGER_TYPE; i = 1; return; default: php_assert (0); exit (1); } } const bool& var::as_bool (const char *function, int parameter_num) const { switch (type) { case NULL_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: case STRING_TYPE: case ARRAY_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be boolean, %s is given", function, parameter_num, get_type_c_str()); empty_bool = false; return empty_bool; case BOOLEAN_TYPE: return b; default: php_assert (0); exit (1); } } const int& var::as_int (const char *function, int parameter_num) const { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: case FLOAT_TYPE: case STRING_TYPE: case ARRAY_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be int, %s is given", function, parameter_num, get_type_c_str()); empty_int = 0; return empty_int; case INTEGER_TYPE: return i; default: php_assert (0); exit (1); } } const double& var::as_float (const char *function, int parameter_num) const { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: case INTEGER_TYPE: case STRING_TYPE: case ARRAY_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be float, %s is given", function, parameter_num, get_type_c_str()); empty_float = 0; return empty_float; case FLOAT_TYPE: return f; default: php_assert (0); exit (1); } } const string& var::as_string (const char *function, int parameter_num) const { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: case ARRAY_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be string, %s is given", function, parameter_num, get_type_c_str()); empty_string = string(); return empty_string; case STRING_TYPE: return *STRING(s); default: php_assert (0); exit (1); } } const array <var>& var::as_array (const char *function, int parameter_num) const { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: case STRING_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be array, %s is given", function, parameter_num, get_type_c_str()); *empty_array_var = array <var>(); return *empty_array_var; case ARRAY_TYPE: return *ARRAY(a); default: php_assert (0); exit (1); } } bool& var::as_bool (const char *function, int parameter_num) { switch (type) { case INTEGER_TYPE: case FLOAT_TYPE: case STRING_TYPE: case ARRAY_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be boolean, %s is given", function, parameter_num, get_type_c_str()); empty_bool = false; return empty_bool; case NULL_TYPE: convert_to_bool(); case BOOLEAN_TYPE: return b; default: php_assert (0); exit (1); } } int& var::as_int (const char *function, int parameter_num) { switch (type) { case ARRAY_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be int, %s is given", function, parameter_num, get_type_c_str()); empty_int = 0; return empty_int; case NULL_TYPE: case BOOLEAN_TYPE: case FLOAT_TYPE: case STRING_TYPE: convert_to_int(); case INTEGER_TYPE: return i; default: php_assert (0); exit (1); } } double& var::as_float (const char *function, int parameter_num) { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: case INTEGER_TYPE: case STRING_TYPE: convert_to_float(); case FLOAT_TYPE: return f; case ARRAY_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be float, %s is given", function, parameter_num, get_type_c_str()); empty_float = 0; return empty_float; default: php_assert (0); exit (1); } } string& var::as_string (const char *function, int parameter_num) { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: convert_to_string(); case STRING_TYPE: return *STRING(s); case ARRAY_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be string, %s is given", function, parameter_num, get_type_c_str()); empty_string = string(); return empty_string; default: php_assert (0); exit (1); } } array <var>& var::as_array (const char *function, int parameter_num) { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: case STRING_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be array, %s is given", function, parameter_num, get_type_c_str()); *empty_array_var = array <var>(); return *empty_array_var; case ARRAY_TYPE: return *ARRAY(a); default: php_assert (0); exit (1); } } bool var::is_numeric (void) const { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: return false; case INTEGER_TYPE: case FLOAT_TYPE: return true; case STRING_TYPE: return STRING(s)->is_numeric(); case ARRAY_TYPE: case OBJECT_TYPE: return false; default: php_assert (0); exit (1); } } bool var::is_scalar (void) const { return type != NULL_TYPE && type != ARRAY_TYPE && type != OBJECT_TYPE; } bool var::is_null (void) const { return type == NULL_TYPE; } bool var::is_bool (void) const { return type == BOOLEAN_TYPE; } bool var::is_int (void) const { return type == INTEGER_TYPE; } bool var::is_float (void) const { return type == FLOAT_TYPE; } bool var::is_string (void) const { return type == STRING_TYPE; } bool var::is_array (void) const { return type == ARRAY_TYPE; } bool var::is_object (void) const { return type == OBJECT_TYPE; } inline const char *var::get_type_c_str (void) const { switch (type) { case NULL_TYPE: return "NULL"; case BOOLEAN_TYPE: return "boolean"; case INTEGER_TYPE: return "integer"; case FLOAT_TYPE: return "double"; case STRING_TYPE: return "string"; case ARRAY_TYPE: return "array"; case OBJECT_TYPE: return "object"; default: php_assert (0); exit (1); } } inline const string var::get_type (void) const { const char *result = get_type_c_str(); return string (result, (dl::size_type)strlen (result)); } bool var::empty (void) const { return !to_bool(); } int var::count (void) const { switch (type) { case NULL_TYPE: return 0; case BOOLEAN_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: case STRING_TYPE: return 1; case ARRAY_TYPE: return ARRAY(a)->count(); case OBJECT_TYPE: return 1; default: php_assert (0); exit (1); } } void var::swap (var &other) { ::swap (type, other.type); ::swap (f, other.f); } var& var::operator[] (int int_key) { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { php_warning ("Lvalue string offset doesn't supported"); empty_var = var(); return empty_var; } if (type == NULL_TYPE || (type == BOOLEAN_TYPE && !b)) { type = ARRAY_TYPE; new (&a) array <var>(); } else { php_warning ("Cannot use a value \"%s\" of type %s as an array, index = %d", to_string().c_str(), get_type_c_str(), int_key); empty_var = var(); return empty_var; } } return (*ARRAY(a))[int_key]; } var& var::operator[] (const string &string_key) { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { php_warning ("Lvalue string offset doesn't supported"); empty_var = var(); return empty_var; } if (type == NULL_TYPE || (type == BOOLEAN_TYPE && !b)) { type = ARRAY_TYPE; new (&a) array <var>(); } else { php_warning ("Cannot use a value \"%s\" of type %s as an array, index = %s", to_string().c_str(), get_type_c_str(), string_key.c_str()); empty_var = var(); return empty_var; } } return (*ARRAY(a))[string_key]; } var& var::operator[] (const var &v) { switch (v.type) { case NULL_TYPE: return (*this)[string()]; case BOOLEAN_TYPE: return (*this)[v.b]; case INTEGER_TYPE: return (*this)[v.i]; case FLOAT_TYPE: return (*this)[(int)v.f]; case STRING_TYPE: return (*this)[*STRING(v.s)]; case ARRAY_TYPE: php_warning ("Illegal offset type %s", v.get_type_c_str()); return (*this)[ARRAY(v.a)->to_int()]; case OBJECT_TYPE: php_warning ("Illegal offset type %s", v.get_type_c_str()); return (*this)[1]; default: php_assert (0); exit (1); } } var& var::operator[] (const array <var>::const_iterator &it) { return (*ARRAY(a))[it]; } var& var::operator[] (const array <var>::iterator &it) { return (*ARRAY(a))[it]; } void var::set_value (int int_key, const var &v) { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { char c = (v.to_string())[0]; if (int_key >= 0) { int l = STRING(s)->size(); if (int_key >= l) { STRING(s)->append (int_key + 1 - l, ' '); } else { STRING(s)->make_not_shared(); } (*STRING(s))[int_key] = c; } else { php_warning ("Illegal string offset %d", int_key); } return; } if (type == NULL_TYPE || (type == BOOLEAN_TYPE && !b)) { type = ARRAY_TYPE; new (&a) array <var>(); } else { php_warning ("Cannot use a value \"%s\" of type %s as an array, index = %d", to_string().c_str(), get_type_c_str(), int_key); return; } } return ARRAY(a)->set_value (int_key, v); } void var::set_value (const string &string_key, const var &v) { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { int int_val; if (!string_key.try_to_int (&int_val)) { php_warning ("Illegal string offset \"%s\"", string_key.c_str()); int_val = string_key.to_int(); } if (int_val < 0) { return; } char c = (v.to_string())[0]; int l = STRING(s)->size(); if (int_val >= l) { STRING(s)->append (int_val + 1 - l, ' '); } else { STRING(s)->make_not_shared(); } (*STRING(s))[int_val] = c; return; } if (type == NULL_TYPE || (type == BOOLEAN_TYPE && !b)) { type = ARRAY_TYPE; new (&a) array <var>(); } else { php_warning ("Cannot use a value \"%s\" of type %s as an array, index = %s", to_string().c_str(), get_type_c_str(), string_key.c_str()); return; } } return ARRAY(a)->set_value (string_key, v); } void var::set_value (const var &v, const var &value) { switch (v.type) { case NULL_TYPE: return set_value (string(), value); case BOOLEAN_TYPE: return set_value (v.b, value); case INTEGER_TYPE: return set_value (v.i, value); case FLOAT_TYPE: return set_value ((int)v.f, value); case STRING_TYPE: return set_value (*STRING(v.s), value); case ARRAY_TYPE: php_warning ("Illegal offset type array"); return; case OBJECT_TYPE: php_warning ("Illegal offset type object"); return; default: php_assert (0); exit (1); } } void var::set_value (const array <var>::const_iterator &it) { return ARRAY(a)->set_value (it); } void var::set_value (const array <var>::iterator &it) { return ARRAY(a)->set_value (it); } const var var::get_value (int int_key) const { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { if ((dl::size_type)int_key >= STRING(s)->size()) { return string(); } return string (1, (*STRING(s))[int_key]); } if (type != NULL_TYPE && (type != BOOLEAN_TYPE || b)) { php_warning ("Cannot use a value \"%s\" of type %s as an array, index = %d", to_string().c_str(), get_type_c_str(), int_key); } return var(); } return ARRAY(a)->get_value (int_key); } const var var::get_value (const string &string_key) const { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { int int_val; if (!string_key.try_to_int (&int_val)) { php_warning ("Illegal string offset \"%s\"", string_key.c_str()); int_val = string_key.to_int(); } if ((dl::size_type)int_val >= STRING(s)->size()) { return string(); } return string (1, (*STRING(s))[int_val]); } if (type != NULL_TYPE && (type != BOOLEAN_TYPE || b)) { php_warning ("Cannot use a value \"%s\" of type %s as an array, index = %s", to_string().c_str(), get_type_c_str(), string_key.c_str()); } return var(); } return ARRAY(a)->get_value (string_key); } const var var::get_value (const var &v) const { switch (v.type) { case NULL_TYPE: return get_value (string()); case BOOLEAN_TYPE: return get_value (v.b); case INTEGER_TYPE: return get_value (v.i); case FLOAT_TYPE: return get_value ((int)v.f); case STRING_TYPE: return get_value (*STRING(v.s)); case ARRAY_TYPE: php_warning ("Illegal offset type %s", v.get_type_c_str()); return var(); case OBJECT_TYPE: php_warning ("Illegal offset type %s", v.get_type_c_str()); return var(); default: php_assert (0); exit (1); } } const var var::get_value (const array <var>::const_iterator &it) const { return ARRAY(a)->get_value (it); } const var var::get_value (const array <var>::iterator &it) const { return ARRAY(a)->get_value (it); } void var::push_back (const var &v) { if (unlikely (type != ARRAY_TYPE)) { if (type == NULL_TYPE || (type == BOOLEAN_TYPE && !b)) { type = ARRAY_TYPE; new (&a) array <var>(); } else { php_warning ("[] operator not supported for type %s", get_type_c_str()); return; } } return ARRAY(a)->push_back (v); } const var var::push_back_return (const var &v) { if (unlikely (type != ARRAY_TYPE)) { if (type == NULL_TYPE || (type == BOOLEAN_TYPE && !b)) { type = ARRAY_TYPE; new (&a) array <var>(); } else { php_warning ("[] operator not supported for type %s", get_type_c_str()); empty_var = var(); return empty_var; } } return ARRAY(a)->push_back_return (v); } bool var::isset (int int_key) const { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { return (dl::size_type)int_key < STRING(s)->size(); } if (type != NULL_TYPE && (type != BOOLEAN_TYPE || b)) { php_warning ("Cannot use variable of type %s as array in isset", get_type_c_str()); } return false; } return ARRAY(a)->isset (int_key); } bool var::isset (const string &string_key) const { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { int int_val; if (!string_key.try_to_int (&int_val)) { php_warning ("Illegal string offset \"%s\"", string_key.c_str()); int_val = string_key.to_int(); } return (dl::size_type)int_val < STRING(s)->size(); } if (type != NULL_TYPE && (type != BOOLEAN_TYPE || b)) { php_warning ("Cannot use variable of type %s as array in isset", get_type_c_str()); } return false; } return ARRAY(a)->isset (string_key); } bool var::isset (const var &v) const { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { return (dl::size_type)(v.to_int()) < STRING(s)->size(); } if (type != NULL_TYPE && (type != BOOLEAN_TYPE || b)) { php_warning ("Cannot use variable of type %s as array in isset", get_type_c_str()); } return false; } switch (v.type) { case NULL_TYPE: return ARRAY(a)->isset (string()); case BOOLEAN_TYPE: return ARRAY(a)->isset (v.b); case INTEGER_TYPE: return ARRAY(a)->isset (v.i); case FLOAT_TYPE: return ARRAY(a)->isset ((int)v.f); case STRING_TYPE: return ARRAY(a)->isset (*STRING(v.s)); case ARRAY_TYPE: php_warning ("Illegal offset type array"); return false; case OBJECT_TYPE: php_warning ("Illegal offset type object"); return false; default: php_assert (0); exit (1); } } bool var::isset (const array <var>::const_iterator &it) const { return ARRAY(a)->isset (it); } bool var::isset (const array <var>::iterator &it) const { return ARRAY(a)->isset (it); } void var::unset (int int_key) { if (unlikely (type != ARRAY_TYPE)) { if (type != NULL_TYPE && (type != BOOLEAN_TYPE || b)) { php_warning ("Cannot use variable of type %s as array in unset", get_type_c_str()); } return; } return ARRAY(a)->unset (int_key); } void var::unset (const string &string_key) { if (unlikely (type != ARRAY_TYPE)) { if (type != NULL_TYPE && (type != BOOLEAN_TYPE || b)) { php_warning ("Cannot use variable of type %s as array in unset", get_type_c_str()); } return; } return ARRAY(a)->unset (string_key); } void var::unset (const var &v) { if (unlikely (type != ARRAY_TYPE)) { if (type != NULL_TYPE && (type != BOOLEAN_TYPE || b)) { php_warning ("Cannot use variable of type %s as array in unset", get_type_c_str()); } return; } switch (v.type) { case NULL_TYPE: return ARRAY(a)->unset (string()); case BOOLEAN_TYPE: return ARRAY(a)->unset (v.b); case INTEGER_TYPE: return ARRAY(a)->unset (v.i); case FLOAT_TYPE: return ARRAY(a)->unset ((int)v.f); case STRING_TYPE: return ARRAY(a)->unset (*STRING(v.s)); case ARRAY_TYPE: php_warning ("Illegal offset type array"); return; case OBJECT_TYPE: php_warning ("Illegal offset type object"); return; default: php_assert (0); exit (1); } } void var::unset (const array <var>::const_iterator &it) { return ARRAY(a)->unset (it); } void var::unset (const array <var>::iterator &it) { return ARRAY(a)->unset (it); } array <var>::const_iterator var::begin (void) const { if (likely (type == ARRAY_TYPE)) { return CONST_ARRAY(a)->begin(); } php_warning ("Invalid argument supplied for foreach(), %s \"%s\" is given", get_type_c_str(), to_string().c_str()); return array <var>::const_iterator(); } array <var>::const_iterator var::end (void) const { if (likely (type == ARRAY_TYPE)) { return CONST_ARRAY(a)->end(); } return array <var>::const_iterator(); } array <var>::iterator var::begin (void) { if (likely (type == ARRAY_TYPE)) { return ARRAY(a)->begin(); } php_warning ("Invalid argument supplied for foreach(), %s \"%s\" is given", get_type_c_str(), to_string().c_str()); return array <var>::iterator(); } array <var>::iterator var::end (void) { if (likely (type == ARRAY_TYPE)) { return ARRAY(a)->end(); } return array <var>::iterator(); } int var::get_reference_counter (void) const { switch (type) { case NULL_TYPE: return -1; case BOOLEAN_TYPE: return -2; case INTEGER_TYPE: return -3; case FLOAT_TYPE: return -4; case STRING_TYPE: return STRING(s)->get_reference_counter(); case ARRAY_TYPE: return ARRAY(a)->get_reference_counter(); case OBJECT_TYPE: return OBJECT(o)->get_reference_counter(); default: php_assert (0); exit (1); } } const var operator + (const var &lhs, const var &rhs) { if (likely (lhs.type == var::INTEGER_TYPE && rhs.type == var::INTEGER_TYPE)) { return lhs.i + rhs.i; } if (lhs.type == var::ARRAY_TYPE && rhs.type == var::ARRAY_TYPE) { return *ARRAY(lhs.a) + *ARRAY(rhs.a); } const var arg1 = lhs.to_numeric(); const var arg2 = rhs.to_numeric(); if (arg1.type == var::INTEGER_TYPE) { if (arg2.type == var::INTEGER_TYPE) { return arg1.i + arg2.i; } else { return arg1.i + arg2.f; } } else { if (arg2.type == var::INTEGER_TYPE) { return arg1.f + arg2.i; } else { return arg1.f + arg2.f; } } } const var operator - (const var &lhs, const var &rhs) { if (likely (lhs.type == var::INTEGER_TYPE && rhs.type == var::INTEGER_TYPE)) { return lhs.i - rhs.i; } const var arg1 = lhs.to_numeric(); const var arg2 = rhs.to_numeric(); if (arg1.type == var::INTEGER_TYPE) { if (arg2.type == var::INTEGER_TYPE) { return arg1.i - arg2.i; } else { return arg1.i - arg2.f; } } else { if (arg2.type == var::INTEGER_TYPE) { return arg1.f - arg2.i; } else { return arg1.f - arg2.f; } } } const var operator * (const var &lhs, const var &rhs) { if (likely (lhs.type == var::INTEGER_TYPE && rhs.type == var::INTEGER_TYPE)) { return lhs.i * rhs.i; } const var arg1 = lhs.to_numeric(); const var arg2 = rhs.to_numeric(); if (arg1.type == var::INTEGER_TYPE) { if (arg2.type == var::INTEGER_TYPE) { return arg1.i * arg2.i; } else { return arg1.i * arg2.f; } } else { if (arg2.type == var::INTEGER_TYPE) { return arg1.f * arg2.i; } else { return arg1.f * arg2.f; } } } const var operator / (const var &lhs, const var &rhs) { if (likely (lhs.type == var::INTEGER_TYPE && rhs.type == var::INTEGER_TYPE)) { if (rhs.i == 0) { php_warning ("Integer division by zero"); return false; } if (lhs.i % rhs.i == 0) { return lhs.i / rhs.i; } return (double)lhs.i / rhs.i; } const var arg1 = lhs.to_numeric(); const var arg2 = rhs.to_numeric(); if (arg2.type == var::INTEGER_TYPE) { if (arg2.i == 0) { php_warning ("Integer division by zero"); return false; } if (arg1.type == var::INTEGER_TYPE) { if (arg1.i % arg2.i == 0) { return arg1.i / arg2.i; } return (double)arg1.i / arg2.i; } else { return arg1.f / arg2.i; } } else { if (arg2.f == 0.0) { php_warning ("Float division by zero"); return false; } if (arg1.type == var::INTEGER_TYPE) { return arg1.i / arg2.f; } else { return arg1.f / arg2.f; } } } const var operator % (const var &lhs, const var &rhs) { int div = rhs.to_int(); if (div == 0) { php_warning ("Modulo by zero"); return false; } return lhs.to_int() % div; } const var operator - (const string &lhs) { var arg1 = lhs.to_numeric(); if (arg1.type == var::INTEGER_TYPE) { arg1.i = -arg1.i; } else { arg1.f = -arg1.f; } return arg1; } const var operator + (const string &lhs) { return lhs.to_numeric(); } int operator & (const var &lhs, const var &rhs) { return lhs.to_int() & rhs.to_int(); } int operator | (const var &lhs, const var &rhs) { return lhs.to_int() | rhs.to_int(); } int operator ^ (const var &lhs, const var &rhs) { return lhs.to_int() ^ rhs.to_int(); } int operator << (const var &lhs, const var &rhs) { return lhs.to_int() << rhs.to_int(); } int operator >> (const var &lhs, const var &rhs) { return lhs.to_int() >> rhs.to_int(); } const var safe_add (const var &lhs, const var &rhs) { if (likely (lhs.type == var::INTEGER_TYPE && rhs.type == var::INTEGER_TYPE)) { return safe_add (lhs.i, rhs.i); } if (lhs.type == var::ARRAY_TYPE && rhs.type == var::ARRAY_TYPE) { return *ARRAY(lhs.a) + *ARRAY(rhs.a); } const var arg1 = lhs.to_numeric(); const var arg2 = rhs.to_numeric(); if (arg1.type == var::INTEGER_TYPE) { if (arg2.type == var::INTEGER_TYPE) { return safe_add (arg1.i, arg2.i); } else { return arg1.i + arg2.f; } } else { if (arg2.type == var::INTEGER_TYPE) { return arg1.f + arg2.i; } else { return arg1.f + arg2.f; } } } const var safe_sub (const var &lhs, const var &rhs) { if (likely (lhs.type == var::INTEGER_TYPE && rhs.type == var::INTEGER_TYPE)) { return safe_sub (lhs.i, rhs.i); } const var arg1 = lhs.to_numeric(); const var arg2 = rhs.to_numeric(); if (arg1.type == var::INTEGER_TYPE) { if (arg2.type == var::INTEGER_TYPE) { return safe_sub (arg1.i, arg2.i); } else { return arg1.i - arg2.f; } } else { if (arg2.type == var::INTEGER_TYPE) { return arg1.f - arg2.i; } else { return arg1.f - arg2.f; } } } const var safe_mul (const var &lhs, const var &rhs) { if (likely (lhs.type == var::INTEGER_TYPE && rhs.type == var::INTEGER_TYPE)) { return safe_mul (lhs.i, rhs.i); } const var arg1 = lhs.to_numeric(); const var arg2 = rhs.to_numeric(); if (arg1.type == var::INTEGER_TYPE) { if (arg2.type == var::INTEGER_TYPE) { return safe_mul (arg1.i, arg2.i); } else { return arg1.i * arg2.f; } } else { if (arg2.type == var::INTEGER_TYPE) { return arg1.f * arg2.i; } else { return arg1.f * arg2.f; } } } const var safe_shl (const var &lhs, const var &rhs) { return safe_shl (lhs.safe_to_int(), rhs.safe_to_int()); } bool eq2 (const var &lhs, const var &rhs) { if (unlikely (lhs.type == var::STRING_TYPE)) { if (likely (rhs.type == var::STRING_TYPE)) { return eq2 (*STRING(lhs.s), *STRING(rhs.s)); } else if (unlikely (rhs.type == var::NULL_TYPE)) { return STRING(lhs.s)->size() == 0; } } else if (unlikely (rhs.type == var::STRING_TYPE)) { if (unlikely (lhs.type == var::NULL_TYPE)) { return STRING(rhs.s)->size() == 0; } } if (lhs.type == var::BOOLEAN_TYPE || rhs.type == var::BOOLEAN_TYPE || lhs.type == var::NULL_TYPE || rhs.type == var::NULL_TYPE) { return lhs.to_bool() == rhs.to_bool(); } if (unlikely (lhs.type == var::ARRAY_TYPE || rhs.type == var::ARRAY_TYPE)) { if (likely (lhs.type == var::ARRAY_TYPE && rhs.type == var::ARRAY_TYPE)) { return eq2 (*ARRAY(lhs.a), *ARRAY(rhs.a)); } php_warning ("Unsupported operand types for operator == (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return false; } if (unlikely (lhs.type == var::OBJECT_TYPE || rhs.type == var::OBJECT_TYPE)) { if (likely (lhs.type == var::OBJECT_TYPE && rhs.type == var::OBJECT_TYPE)) { return eq2 (*OBJECT(lhs.o), *OBJECT(rhs.o)); } php_warning ("Unsupported operand types for operator == (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return false; } return lhs.to_float() == rhs.to_float(); } bool neq2 (const var &lhs, const var &rhs) { return !eq2 (lhs, rhs); } bool operator <= (const var &lhs, const var &rhs) { if (unlikely (lhs.type == var::STRING_TYPE)) { if (likely (rhs.type == var::STRING_TYPE)) { if (STRING(lhs.s)[0][0] <= '9' && STRING(rhs.s)[0][0] <= '9') { int lhs_int_val, rhs_int_val; if (STRING(lhs.s)->try_to_int (&lhs_int_val) && STRING(rhs.s)->try_to_int (&rhs_int_val)) { return lhs_int_val <= rhs_int_val; } double lhs_float_val, rhs_float_val; if (STRING(lhs.s)->try_to_float (&lhs_float_val) && STRING(rhs.s)->try_to_float (&rhs_float_val)) { STRING(lhs.s)->warn_on_float_conversion(); STRING(rhs.s)->warn_on_float_conversion(); if (is_ok_float (lhs_float_val) && is_ok_float (rhs_float_val)) { return lhs_float_val <= rhs_float_val; } } } return STRING(lhs.s)->compare (*STRING(rhs.s)) <= 0; } else if (unlikely (rhs.type == var::NULL_TYPE)) { return STRING(lhs.s)->size() == 0; } } else if (unlikely (rhs.type == var::STRING_TYPE)) { if (unlikely (lhs.type == var::NULL_TYPE)) { return true; } } if (lhs.type == var::BOOLEAN_TYPE || rhs.type == var::BOOLEAN_TYPE || lhs.type == var::NULL_TYPE || rhs.type == var::NULL_TYPE) { return lhs.to_bool() <= rhs.to_bool(); } if (unlikely (lhs.type == var::ARRAY_TYPE || rhs.type == var::ARRAY_TYPE)) { if (likely (lhs.type == var::ARRAY_TYPE && rhs.type == var::ARRAY_TYPE)) { return ARRAY(lhs.a)->count() <= ARRAY(rhs.a)->count(); } php_warning ("Unsupported operand types for operator <= (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return rhs.type == var::ARRAY_TYPE; } if (unlikely (lhs.type == var::OBJECT_TYPE || rhs.type == var::OBJECT_TYPE)) { php_warning ("Unsupported operand types for operator <= (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return rhs.type == var::OBJECT_TYPE; } return lhs.to_float() <= rhs.to_float(); } bool operator >= (const var &lhs, const var &rhs) { if (unlikely (lhs.type == var::STRING_TYPE)) { if (likely (rhs.type == var::STRING_TYPE)) { if (STRING(lhs.s)[0][0] <= '9' && STRING(rhs.s)[0][0] <= '9') { int lhs_int_val, rhs_int_val; if (STRING(lhs.s)->try_to_int (&lhs_int_val) && STRING(rhs.s)->try_to_int (&rhs_int_val)) { return lhs_int_val >= rhs_int_val; } double lhs_float_val, rhs_float_val; if (STRING(lhs.s)->try_to_float (&lhs_float_val) && STRING(rhs.s)->try_to_float (&rhs_float_val)) { STRING(lhs.s)->warn_on_float_conversion(); STRING(rhs.s)->warn_on_float_conversion(); if (is_ok_float (lhs_float_val) && is_ok_float (rhs_float_val)) { return lhs_float_val >= rhs_float_val; } } } return STRING(lhs.s)->compare (*STRING(rhs.s)) >= 0; } else if (unlikely (rhs.type == var::NULL_TYPE)) { return true; } } else if (unlikely (rhs.type == var::STRING_TYPE)) { if (unlikely (lhs.type == var::NULL_TYPE)) { return STRING(rhs.s)->size() == 0; } } if (lhs.type == var::BOOLEAN_TYPE || rhs.type == var::BOOLEAN_TYPE || lhs.type == var::NULL_TYPE || rhs.type == var::NULL_TYPE) { return lhs.to_bool() >= rhs.to_bool(); } if (unlikely (lhs.type == var::ARRAY_TYPE || rhs.type == var::ARRAY_TYPE)) { if (likely (lhs.type == var::ARRAY_TYPE && rhs.type == var::ARRAY_TYPE)) { return ARRAY(lhs.a)->count() >= ARRAY(rhs.a)->count(); } php_warning ("Unsupported operand types for operator >= (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return lhs.type == var::ARRAY_TYPE; } if (unlikely (lhs.type == var::OBJECT_TYPE || rhs.type == var::OBJECT_TYPE)) { php_warning ("Unsupported operand types for operator >= (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return lhs.type == var::OBJECT_TYPE; } return lhs.to_float() >= rhs.to_float(); } bool operator < (const var &lhs, const var &rhs) { if (unlikely (lhs.type == var::STRING_TYPE)) { if (likely (rhs.type == var::STRING_TYPE)) { if (STRING(lhs.s)[0][0] <= '9' && STRING(rhs.s)[0][0] <= '9') { int lhs_int_val, rhs_int_val; if (STRING(lhs.s)->try_to_int (&lhs_int_val) && STRING(rhs.s)->try_to_int (&rhs_int_val)) { return lhs_int_val < rhs_int_val; } double lhs_float_val, rhs_float_val; if (STRING(lhs.s)->try_to_float (&lhs_float_val) && STRING(rhs.s)->try_to_float (&rhs_float_val)) { STRING(lhs.s)->warn_on_float_conversion(); STRING(rhs.s)->warn_on_float_conversion(); if (is_ok_float (lhs_float_val) && is_ok_float (rhs_float_val)) { return lhs_float_val < rhs_float_val; } } } return STRING(lhs.s)->compare (*STRING(rhs.s)) < 0; } else if (unlikely (rhs.type == var::NULL_TYPE)) { return false; } } else if (unlikely (rhs.type == var::STRING_TYPE)) { if (unlikely (lhs.type == var::NULL_TYPE)) { return STRING(rhs.s)->size() != 0; } } if (lhs.type == var::BOOLEAN_TYPE || rhs.type == var::BOOLEAN_TYPE || lhs.type == var::NULL_TYPE || rhs.type == var::NULL_TYPE) { return lhs.to_bool() < rhs.to_bool(); } if (unlikely (lhs.type == var::ARRAY_TYPE || rhs.type == var::ARRAY_TYPE)) { if (likely (lhs.type == var::ARRAY_TYPE && rhs.type == var::ARRAY_TYPE)) { return ARRAY(lhs.a)->count() < ARRAY(rhs.a)->count(); } php_warning ("Unsupported operand types for operator < (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return lhs.type != var::ARRAY_TYPE; } if (unlikely (lhs.type == var::OBJECT_TYPE || rhs.type == var::OBJECT_TYPE)) { php_warning ("Unsupported operand types for operator < (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return lhs.type != var::OBJECT_TYPE; } return lhs.to_float() < rhs.to_float(); } bool operator > (const var &lhs, const var &rhs) { if (unlikely (lhs.type == var::STRING_TYPE)) { if (likely (rhs.type == var::STRING_TYPE)) { if (STRING(lhs.s)[0][0] <= '9' && STRING(rhs.s)[0][0] <= '9') { int lhs_int_val, rhs_int_val; if (STRING(lhs.s)->try_to_int (&lhs_int_val) && STRING(rhs.s)->try_to_int (&rhs_int_val)) { return lhs_int_val > rhs_int_val; } double lhs_float_val, rhs_float_val; if (STRING(lhs.s)->try_to_float (&lhs_float_val) && STRING(rhs.s)->try_to_float (&rhs_float_val)) { STRING(lhs.s)->warn_on_float_conversion(); STRING(rhs.s)->warn_on_float_conversion(); if (is_ok_float (lhs_float_val) && is_ok_float (rhs_float_val)) { return lhs_float_val > rhs_float_val; } } } return STRING(lhs.s)->compare (*STRING(rhs.s)) > 0; } else if (unlikely (rhs.type == var::NULL_TYPE)) { return STRING(lhs.s)->size() != 0; } } else if (unlikely (rhs.type == var::STRING_TYPE)) { if (unlikely (lhs.type == var::NULL_TYPE)) { return false; } } if (lhs.type == var::BOOLEAN_TYPE || rhs.type == var::BOOLEAN_TYPE || lhs.type == var::NULL_TYPE || rhs.type == var::NULL_TYPE) { return lhs.to_bool() > rhs.to_bool(); } if (unlikely (lhs.type == var::ARRAY_TYPE || rhs.type == var::ARRAY_TYPE)) { if (likely (lhs.type == var::ARRAY_TYPE && rhs.type == var::ARRAY_TYPE)) { return ARRAY(lhs.a)->count() > ARRAY(rhs.a)->count(); } php_warning ("Unsupported operand types for operator > (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return rhs.type != var::ARRAY_TYPE; } if (unlikely (lhs.type == var::OBJECT_TYPE || rhs.type == var::OBJECT_TYPE)) { php_warning ("Unsupported operand types for operator > (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return rhs.type != var::OBJECT_TYPE; } return lhs.to_float() > rhs.to_float(); } bool equals (const var &lhs, const var &rhs) { if (lhs.type != rhs.type) { return false; } switch (lhs.type) { case var::NULL_TYPE: return true; case var::BOOLEAN_TYPE: return lhs.b == rhs.b; case var::INTEGER_TYPE: return lhs.i == rhs.i; case var::FLOAT_TYPE: return lhs.f == rhs.f; case var::STRING_TYPE: return *STRING(lhs.s) == *STRING(rhs.s); case var::ARRAY_TYPE: return equals (*ARRAY(lhs.a), *ARRAY(rhs.a)); case var::OBJECT_TYPE: return equals (*OBJECT(lhs.o), *OBJECT(rhs.o)); default: php_assert (0); exit (1); } } bool not_equals (const var &lhs, const var &rhs) { return !equals (lhs, rhs); } void swap (var &lhs, var &rhs) { lhs.swap (rhs); } template <class T, class T1> array <T>& safe_set_add (array <T> &lhs, const array <T1> &rhs) { return lhs += rhs; } template <class T> array <T> safe_add (const array <T> &lhs, const array <T> &rhs) { return lhs + rhs; } var& safe_set_add (var &lhs, const var &rhs) { return lhs.safe_set_add (rhs); } var& safe_set_sub (var &lhs, const var &rhs) { return lhs.safe_set_sub (rhs); } var& safe_set_mul (var &lhs, const var &rhs) { return lhs.safe_set_mul (rhs); } var& safe_set_shl (var &lhs, const var &rhs) { return lhs.safe_set_shl (rhs); } int& safe_set_add (int &lhs, int rhs) { return lhs = safe_add (lhs, rhs); } int& safe_set_sub (int &lhs, int rhs) { return lhs = safe_sub (lhs, rhs); } int& safe_set_mul (int &lhs, int rhs) { return lhs = safe_mul (lhs, rhs); } int& safe_set_shl (int &lhs, int rhs) { return lhs = safe_shl (lhs, rhs); } int safe_add (int lhs, int rhs) { long long res = (long long)lhs + rhs; int resi = (int)res; if (resi != res) { php_warning ("Integer overflow in %d + %d", lhs, rhs); } return resi; } int safe_sub (int lhs, int rhs) { long long res = (long long)lhs - rhs; int resi = (int)res; if (resi != res) { php_warning ("Integer overflow in %d - %d", lhs, rhs); } return resi; } int safe_mul (int lhs, int rhs) { long long res = (long long)lhs * rhs; int resi = (int)res; if (resi != res) { php_warning ("Integer overflow in %d * %d", lhs, rhs); } return resi; } int safe_shl (int lhs, int rhs) { if ((unsigned int)rhs >= 32u) { php_warning ("Wrong right parameter %d in << operator", rhs); rhs = 0; } int res = lhs << rhs; if ((res >> rhs) != lhs) { php_warning ("Integer overflow in %d << %d", lhs, rhs); } return res; } double& safe_set_add (double &lhs, double rhs) { return lhs += rhs; } double& safe_set_sub (double &lhs, double rhs) { return lhs -= rhs; } double& safe_set_mul (double &lhs, double rhs) { return lhs *= rhs; } int safe_add (bool lhs, bool rhs) { return lhs + rhs; } int safe_add (bool lhs, int rhs) { return lhs + rhs; } double safe_add (bool lhs, double rhs) { return lhs + rhs; } int safe_add (int lhs, bool rhs) { return lhs + rhs; } double safe_add (int lhs, double rhs) { return lhs + rhs; } double safe_add (double lhs, bool rhs) { return lhs + rhs; } double safe_add (double lhs, int rhs) { return lhs + rhs; } double safe_add (double lhs, double rhs) { return lhs + rhs; } int safe_sub (bool lhs, bool rhs) { return lhs - rhs; } int safe_sub (bool lhs, int rhs) { return lhs - rhs; } double safe_sub (bool lhs, double rhs) { return lhs - rhs; } int safe_sub (int lhs, bool rhs) { return lhs - rhs; } double safe_sub (int lhs, double rhs) { return lhs - rhs; } double safe_sub (double lhs, bool rhs) { return lhs - rhs; } double safe_sub (double lhs, int rhs) { return lhs - rhs; } double safe_sub (double lhs, double rhs) { return lhs - rhs; } int safe_mul (bool lhs, bool rhs) { return lhs * rhs; } int safe_mul (bool lhs, int rhs) { return lhs * rhs; } double safe_mul (bool lhs, double rhs) { return lhs * rhs; } int safe_mul (int lhs, bool rhs) { return lhs * rhs; } double safe_mul (int lhs, double rhs) { return lhs * rhs; } double safe_mul (double lhs, bool rhs) { return lhs * rhs; } double safe_mul (double lhs, int rhs) { return lhs * rhs; } double safe_mul (double lhs, double rhs) { return lhs * rhs; } int& safe_incr_pre (int &lhs) { if (lhs == INT_MAX) { php_warning ("Integer overflow in ++%d", lhs); } return ++lhs; } int& safe_decr_pre (int &lhs) { if (lhs == INT_MIN) { php_warning ("Integer overflow in --%d", lhs); } return --lhs; } int safe_incr_post (int &lhs) { if (lhs == INT_MAX) { php_warning ("Integer overflow in %d++", lhs); } return lhs++; } int safe_decr_post (int &lhs) { if (lhs == INT_MIN) { php_warning ("Integer overflow in %d--", lhs); } return lhs--; } double& safe_incr_pre (double &lhs) { return ++lhs; } double& safe_decr_pre (double &lhs) { return --lhs; } double safe_incr_post (double &lhs) { return lhs++; } double safe_decr_post (double &lhs) { return lhs--; } var& safe_incr_pre (var &lhs) { return lhs.safe_incr_pre(); } var& safe_decr_pre (var &lhs) { return lhs.safe_decr_pre(); } var safe_incr_post (var &lhs) { return lhs.safe_incr_post(); } var safe_decr_post (var &lhs) { return lhs.safe_decr_post(); } bool eq2 (bool lhs, bool rhs) { return lhs == rhs; } bool eq2 (int lhs, int rhs) { return lhs == rhs; } bool eq2 (double lhs, double rhs) { return lhs == rhs; } bool eq2 (bool lhs, int rhs) { return lhs != !rhs; } bool eq2 (bool lhs, double rhs) { return lhs != (rhs == 0.0); } bool eq2 (int lhs, bool rhs) { return rhs != !lhs; } bool eq2 (double lhs, bool rhs) { return rhs != (lhs == 0.0); } bool eq2 (int lhs, double rhs) { return lhs == rhs; } bool eq2 (double lhs, int rhs) { return lhs == rhs; } bool eq2 (bool lhs, const string &rhs) { return lhs == rhs.to_bool(); } bool eq2 (int lhs, const string &rhs) { return lhs == rhs.to_float(); } bool eq2 (double lhs, const string &rhs) { return lhs == rhs.to_float(); } bool eq2 (const string &lhs, bool rhs) { return rhs == lhs.to_bool(); } bool eq2 (const string &lhs, int rhs) { return rhs == lhs.to_float(); } bool eq2 (const string &lhs, double rhs) { return rhs == lhs.to_float(); } template <class T> bool eq2 (bool lhs, const array <T> &rhs) { return lhs == !rhs.empty(); } template <class T> bool eq2 (int lhs, const array <T> &rhs) { php_warning ("Unsupported operand types for operator == (int and array)"); return false; } template <class T> bool eq2 (double lhs, const array <T> &rhs) { php_warning ("Unsupported operand types for operator == (float and array)"); return false; } template <class T> bool eq2 (const string &lhs, const array <T> &rhs) { php_warning ("Unsupported operand types for operator == (string and array)"); return false; } template <class T> bool eq2 (const array <T> &lhs, bool rhs) { return rhs == !lhs.empty(); } template <class T> bool eq2 (const array <T> &lhs, int rhs) { php_warning ("Unsupported operand types for operator == (array and int)"); return false; } template <class T> bool eq2 (const array <T> &lhs, double rhs) { php_warning ("Unsupported operand types for operator == (array and float)"); return false; } template <class T> bool eq2 (const array <T> &lhs, const string &rhs) { php_warning ("Unsupported operand types for operator == (array and string)"); return false; } template <class T> bool eq2 (bool lhs, const object_ptr <T> &rhs) { return lhs; } template <class T> bool eq2 (int lhs, const object_ptr <T> &rhs) { php_warning ("Unsupported operand types for operator == (int and object)"); return false; } template <class T> bool eq2 (double lhs, const object_ptr <T> &rhs) { php_warning ("Unsupported operand types for operator == (float and object)"); return false; } template <class T> bool eq2 (const string &lhs, const object_ptr <T> &rhs) { php_warning ("Unsupported operand types for operator == (string and object)"); return false; } template <class T, class T1> bool eq2 (const array <T1> &lhs, const object_ptr <T> &rhs) { php_warning ("Unsupported operand types for operator == (array and object)"); return false; } template <class T> bool eq2 (const object_ptr <T> &lhs, bool rhs) { return rhs; } template <class T> bool eq2 (const object_ptr <T> &lhs, int rhs) { php_warning ("Unsupported operand types for operator == (object and int)"); return false; } template <class T> bool eq2 (const object_ptr <T> &lhs, double rhs) { php_warning ("Unsupported operand types for operator == (object and float)"); return false; } template <class T> bool eq2 (const object_ptr <T> &lhs, const string &rhs) { php_warning ("Unsupported operand types for operator == (object and string)"); return false; } template <class T, class T1> bool eq2 (const object_ptr <T> &lhs, const array <T1> &rhs) { php_warning ("Unsupported operand types for operator == (object and array)"); return false; } bool eq2 (bool lhs, const var &rhs) { return lhs == rhs.to_bool(); } bool eq2 (int lhs, const var &rhs) { switch (rhs.type) { case var::NULL_TYPE: return lhs == 0; case var::BOOLEAN_TYPE: return !!lhs == rhs.b; case var::INTEGER_TYPE: return lhs == rhs.i; case var::FLOAT_TYPE: return lhs == rhs.f; case var::STRING_TYPE: return lhs == STRING(rhs.s)->to_float(); case var::ARRAY_TYPE: php_warning ("Unsupported operand types for operator == (int and array)"); return false; case var::OBJECT_TYPE: php_warning ("Unsupported operand types for operator == (int and object)"); return false; default: php_assert (0); exit (1); } } bool eq2 (double lhs, const var &rhs) { switch (rhs.type) { case var::NULL_TYPE: return lhs == 0.0; case var::BOOLEAN_TYPE: return (lhs != 0.0) == rhs.b; case var::INTEGER_TYPE: return lhs == rhs.i; case var::FLOAT_TYPE: return lhs == rhs.f; case var::STRING_TYPE: return lhs == STRING(rhs.s)->to_float(); case var::ARRAY_TYPE: php_warning ("Unsupported operand types for operator == (float and array)"); return false; case var::OBJECT_TYPE: php_warning ("Unsupported operand types for operator == (float and object)"); return false; default: php_assert (0); exit (1); } } bool eq2 (const string &lhs, const var &rhs) { return eq2 (var (lhs), rhs); } template <class T> bool eq2 (const array <T> &lhs, const var &rhs) { if (likely (rhs.is_array())) { return eq2 (lhs, *ARRAY(rhs.a)); } if (rhs.is_bool()) { return lhs.empty() != rhs.b; } if (rhs.is_null()) { return lhs.empty(); } php_warning ("Unsupported operand types for operator == (array and %s)", rhs.get_type_c_str()); return false; } template <class T> bool eq2 (const object_ptr <T> &lhs, const var &rhs) { if (likely (rhs.is_object())) { return eq2 (lhs, *OBJECT(rhs.o)); } if (rhs.is_bool()) { return rhs.b; } if (rhs.is_null()) { return false; } php_warning ("Unsupported operand types for operator == (object and %s)", rhs.get_type_c_str()); return false; } bool eq2 (const var &lhs, bool rhs) { return rhs == lhs.to_bool(); } bool eq2 (const var &lhs, int rhs) { switch (lhs.type) { case var::NULL_TYPE: return rhs == 0; case var::BOOLEAN_TYPE: return !!rhs == lhs.b; case var::INTEGER_TYPE: return rhs == lhs.i; case var::FLOAT_TYPE: return rhs == lhs.f; case var::STRING_TYPE: return rhs == STRING(lhs.s)->to_float(); case var::ARRAY_TYPE: php_warning ("Unsupported operand types for operator == (array and int)"); return false; case var::OBJECT_TYPE: php_warning ("Unsupported operand types for operator == (object and int)"); return false; default: php_assert (0); exit (1); } } bool eq2 (const var &lhs, double rhs) { switch (lhs.type) { case var::NULL_TYPE: return rhs == 0.0; case var::BOOLEAN_TYPE: return (rhs != 0.0) == lhs.b; case var::INTEGER_TYPE: return rhs == lhs.i; case var::FLOAT_TYPE: return rhs == lhs.f; case var::STRING_TYPE: return rhs == STRING(lhs.s)->to_float(); case var::ARRAY_TYPE: php_warning ("Unsupported operand types for operator == (array and float)"); return false; case var::OBJECT_TYPE: php_warning ("Unsupported operand types for operator == (object and float)"); return false; default: php_assert (0); exit (1); } } bool eq2 (const var &lhs, const string &rhs) { return eq2 (var (rhs), lhs); } template <class T> bool eq2 (const var &lhs, const array <T> &rhs) { if (likely (lhs.is_array())) { return eq2 (*ARRAY(lhs.a), rhs); } if (lhs.is_bool()) { return rhs.empty() != lhs.b; } if (lhs.is_null()) { return rhs.empty(); } php_warning ("Unsupported operand types for operator == (%s and array)", lhs.get_type_c_str()); return false; } template <class T> bool eq2 (const var &lhs, const object_ptr <T> &rhs) { if (likely (lhs.is_object())) { return eq2 (*OBJECT(lhs.o), rhs); } if (lhs.is_bool()) { return lhs.b; } if (lhs.is_null()) { return false; } php_warning ("Unsupported operand types for operator == (%s and object)", lhs.get_type_c_str()); return false; } template <class T1, class T2> bool neq2 (const T1 &lhs, const T2 &rhs) { return !eq2 (lhs, rhs); } bool equals (bool lhs, const var &rhs) { return rhs.is_bool() && equals (lhs, rhs.b); } bool equals (int lhs, const var &rhs) { return rhs.is_int() && equals (lhs, rhs.i); } bool equals (double lhs, const var &rhs) { return rhs.is_float() && equals (lhs, rhs.f); } bool equals (const string &lhs, const var &rhs) { return rhs.is_string() && equals (lhs, *STRING(rhs.s)); } template <class T> bool equals (const array <T> &lhs, const var &rhs) { return rhs.is_array() && equals (lhs, *ARRAY(rhs.a)); } template <class T> bool equals (const object_ptr <T> &lhs, const var &rhs) { return rhs.is_object() && equals (lhs, *OBJECT(rhs.o)); } bool equals (const var &lhs, bool rhs) { return lhs.is_bool() && equals (rhs, lhs.b); } bool equals (const var &lhs, int rhs) { return lhs.is_int() && equals (rhs, lhs.i); } bool equals (const var &lhs, double rhs) { return lhs.is_float() && equals (rhs, lhs.f); } bool equals (const var &lhs, const string &rhs) { return lhs.is_string() && equals (rhs, *STRING(lhs.s)); } template <class T> bool equals (const var &lhs, const array <T> &rhs) { return lhs.is_array() && equals (rhs, *ARRAY(lhs.a)); } template <class T> bool equals (const var &lhs, const object_ptr <T> &rhs) { return lhs.is_object() && equals (rhs, *OBJECT(lhs.o)); } template <class T> bool equals (const T &lhs, const T &rhs) { return lhs == rhs; } template <class T1, class T2> bool equals (const T1 &lhs, const T2 &rhs) { return false; } template <class T1, class T2> bool not_equals (const T1 &lhs, const T2 &rhs) { return !equals (lhs, rhs); } template <class T> bool eq2 (const var &v, const OrFalse <T> &value) { return likely (value.bool_value) ? eq2 (value.value, v) : eq2 (false, v); } template <class T> bool eq2 (const OrFalse <T> &value, const var &v) { return likely (value.bool_value) ? eq2 (value.value, v) : eq2 (false, v); } template <class T> bool equals (const OrFalse <T> &value, const var &v) { return likely (value.bool_value) ? equals (value.value, v) : equals (false, v); } template <class T> bool equals (const var &v, const OrFalse <T> &value) { return likely (value.bool_value) ? equals (value.value, v) : equals (false, v); } template <class T> bool not_equals (const OrFalse <T> &value, const var &v) { return likely (value.bool_value) ? not_equals (value.value, v) : not_equals (false, v); } template <class T> bool not_equals (const var &v, const OrFalse <T> &value) { return likely (value.bool_value) ? not_equals (value.value, v) : not_equals (false, v); }
23.255866
142
0.58576
redm-pro
f5cfafb744c7a053234516e2b4e10677edfc6c9f
9,424
cpp
C++
src/models/bwc/stsu_data_istream.cpp
steptosky/3DsMax-X-Obj-Exporter
c70f5a60056ee71aba1569f1189c38b9e01d2f0e
[ "BSD-3-Clause" ]
20
2017-07-07T06:07:30.000Z
2022-03-09T12:00:57.000Z
src/models/bwc/stsu_data_istream.cpp
steptosky/3DsMax-X-Obj-Exporter
c70f5a60056ee71aba1569f1189c38b9e01d2f0e
[ "BSD-3-Clause" ]
28
2017-07-07T06:08:27.000Z
2022-03-09T12:09:23.000Z
src/models/bwc/stsu_data_istream.cpp
steptosky/3DsMax-X-Obj-Exporter
c70f5a60056ee71aba1569f1189c38b9e01d2f0e
[ "BSD-3-Clause" ]
7
2018-01-24T19:43:22.000Z
2020-01-06T00:05:40.000Z
/* ** Copyright(C) 2017, StepToSky ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are met: ** ** 1.Redistributions of source code must retain the above copyright notice, this ** list of conditions and the following disclaimer. ** 2.Redistributions in binary form must reproduce the above copyright notice, ** this list of conditions and the following disclaimer in the documentation ** and / or other materials provided with the distribution. ** 3.Neither the name of StepToSky 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. ** ** Contacts: www.steptosky.com */ #include "stsu_data_istream.h" namespace sts_bwc { // backward compatibility /********************************************************************************************************/ ///////////////////////////////////////* Constructors/Destructor *//////////////////////////////////////// /********************************************************************************************************/ DataStreamI::DataStreamI(std::istream & inStream) : mStream(&inStream), mError(DataStreamI::eErrors::ok) {} DataStreamI::DataStreamI() : mStream(nullptr), mError(DataStreamI::eErrors::ok) { } DataStreamI::~DataStreamI() { } /********************************************************************************************************/ //////////////////////////////////////////////* Operators */////////////////////////////////////////////// /********************************************************************************************************/ DataStreamI & DataStreamI::operator>>(char & outVal) { outVal = 0; if (!mStream->read(&outVal, sizeof(char))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(int8_t & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(int8_t))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(uint8_t & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(uint8_t))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(int16_t & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(int16_t))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(uint16_t & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(uint16_t))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(int32_t & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(int32_t))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(uint32_t & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(uint32_t))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(int64_t & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(int64_t))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(uint64_t & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(uint64_t))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(bool & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(bool))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(float & outVal) { outVal = 0.0f; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(float))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(double & outVal) { outVal = 0.0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(double))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(char *& outVal) { uint64_t len = 0; return readBytes(outVal, len); } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(wchar_t *& outVal) { uint64_t len = 0; return readBytes(outVal, len); } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(std::string & outVal) { uint64_t len; char * str; readBytes(str, len); outVal = std::string(str, len); return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(std::wstring & outVal) { uint64_t len; char * str; readBytes(str, len); outVal = std::wstring(reinterpret_cast<wchar_t*>(str), len / sizeof(wchar_t)); return *this; } /********************************************************************************************************/ //////////////////////////////////////////////* Functions */////////////////////////////////////////////// /********************************************************************************************************/ DataStreamI & DataStreamI::readBytes(wchar_t *& outVal, uint64_t & outLen) { outVal = nullptr; outLen = 0; uint64_t byteCount; *this >> byteCount; if (byteCount == 0) { mError = eErrors::readZerroBytes; return *this; } uint64_t len = byteCount / sizeof(wchar_t); outVal = new wchar_t[len + 1]; if (!mStream->read(reinterpret_cast<char *>(outVal), byteCount)) { mError = eErrors::readError; delete[] outVal; return *this; } outVal[len] = L'\0'; outLen = byteCount; return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::readBytes(char *& outVal, uint64_t & outLen) { outVal = nullptr; outLen = 0; uint64_t len; *this >> len; if (len == 0) { mError = eErrors::readZerroBytes; return *this; } outVal = new char[len + 1]; if (!mStream->read(outVal, len)) { mError = eErrors::readError; delete[] outVal; return *this; } outVal[len] = '\0'; outLen = len; return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::readRawData(char * outVal, uint64_t inLen) { if (!mStream->read(outVal, inLen)) { mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::skipRawBytes(uint64_t inLen) { if (!mStream->seekg(inLen, mStream->cur)) { mError = eErrors::seekError; } return *this; } /********************************************************************************************************/ ////////////////////////////////////////////////////////////////////////////////////////////////////////// /********************************************************************************************************/ } // namespace sts
32.608997
106
0.463073
steptosky
f5d718cde2194d572b700cd9ed350c21a449b747
17,638
cpp
C++
src/qt/blocknetquicksend.cpp
mraksoll4/scalaris1
f6e677780f51d570ff1ad8177e003fb8936aacc0
[ "MIT" ]
2
2021-04-11T15:25:15.000Z
2021-10-01T17:37:19.000Z
src/qt/blocknetquicksend.cpp
mraksoll4/scalaris1
f6e677780f51d570ff1ad8177e003fb8936aacc0
[ "MIT" ]
null
null
null
src/qt/blocknetquicksend.cpp
mraksoll4/scalaris1
f6e677780f51d570ff1ad8177e003fb8936aacc0
[ "MIT" ]
5
2021-03-24T11:53:45.000Z
2021-11-24T00:49:08.000Z
// Copyright (c) 2018-2019 The Blocknet developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/blocknetquicksend.h> #include <qt/blocknetaddressbook.h> #include <qt/blocknethdiv.h> #include <qt/blockneticonbtn.h> #include <qt/blocknetsendfundsrequest.h> #include <qt/blocknetsendfundsutil.h> #include <qt/addresstablemodel.h> #include <qt/optionsmodel.h> #include <qt/sendcoinsdialog.h> #include <amount.h> #include <base58.h> #include <wallet/coincontrol.h> #include <validation.h> #include <QMessageBox> #include <QKeyEvent> BlocknetQuickSend::BlocknetQuickSend(WalletModel *w, QWidget *parent) : QFrame(parent), walletModel(w), layout(new QVBoxLayout) { // this->setStyleSheet("border: 1px solid red"); this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); this->setLayout(layout); layout->setContentsMargins(BGU::spi(45), BGU::spi(10), BGU::spi(45), BGU::spi(30)); displayUnit = walletModel->getOptionsModel()->getDisplayUnit(); auto displayUnitName = BitcoinUnits::longName(displayUnit); titleLbl = new QLabel(tr("Quick Send")); titleLbl->setObjectName("h4"); auto *subtitleLbl = new QLabel(tr("Who would you like to send funds to?")); subtitleLbl->setObjectName("h2"); auto *addrBox = new QFrame; addrBox->setContentsMargins(QMargins()); auto *addrBoxLayout = new QHBoxLayout; addrBoxLayout->setContentsMargins(QMargins()); addrBox->setLayout(addrBoxLayout); addressTi = new BlocknetLineEdit(BGU::spi(400)); addressTi->setObjectName("address"); addressTi->setPlaceholderText(tr("Enter Scalaris Address...")); addressTi->setFocusPolicy(Qt::FocusPolicy::StrongFocus); addressTi->setValidator(new QRegExpValidator(QRegExp("[a-zA-Z0-9]{33,35}"), this)); auto *addAddressBtn = new BlocknetIconBtn(QString(), ":/redesign/QuickActions/AddressBookIcon.png"); addrBoxLayout->addWidget(addressTi, 0, Qt::AlignTop); addrBoxLayout->addSpacing(BGU::spi(20)); addrBoxLayout->addWidget(addAddressBtn, 0, Qt::AlignTop); auto *amountLbl = new QLabel(tr("How much would you like to send?")); amountLbl->setObjectName("h2"); auto *amountBox = new QFrame; auto *amountBoxLayout = new QHBoxLayout; amountBoxLayout->setContentsMargins(QMargins()); amountBox->setLayout(amountBoxLayout); amountTi = new BlocknetLineEdit; amountTi->setPlaceholderText(tr("Enter Amount...")); amountTi->setValidator(new BlocknetNumberValidator(0, BLOCKNETGUI_FUNDS_MAX, BitcoinUnits::decimals(displayUnit))); amountTi->setMaxLength(BLOCKNETGUI_MAXCHARS); auto *coinLbl = new QLabel(displayUnitName); coinLbl->setObjectName("coin"); coinLbl->setFixedHeight(amountTi->minimumHeight()); amountBoxLayout->addWidget(amountTi, 0, Qt::AlignLeft); amountBoxLayout->addWidget(coinLbl, 0, Qt::AlignLeft); amountBoxLayout->addStretch(1); // address div auto *div1 = new BlocknetHDiv; // grid divs auto *gdiv1 = new BlocknetHDiv; auto *gdiv2 = new BlocknetHDiv; auto *gdiv3 = new BlocknetHDiv; // Display total auto *totalGrid = new QFrame; // totalGrid->setStyleSheet("border: 1px solid red"); totalGrid->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); auto *totalsLayout = new QGridLayout; totalsLayout->setContentsMargins(QMargins()); totalsLayout->setSpacing(BGU::spi(50)); totalsLayout->setVerticalSpacing(0); totalGrid->setLayout(totalsLayout); auto *feeLbl = new QLabel(tr("Transaction Fee")); feeLbl->setObjectName("header"); feeValueLbl = new QLabel; feeValueLbl->setObjectName("standard"); auto *feeCol3 = new QLabel; auto *totalLbl = new QLabel(tr("Total")); totalLbl->setObjectName("header"); totalValueLbl = new QLabel(BitcoinUnits::formatWithUnit(displayUnit, 0)); totalValueLbl->setObjectName("header"); auto *totalCol3 = new QLabel; warningLbl = new QLabel; warningLbl->setObjectName("warning"); // Grid rows and columns (in order of rows and columns) totalsLayout->addWidget(gdiv1, 0, 0, 1, 3, Qt::AlignVCenter); totalsLayout->addWidget(feeLbl, 1, 0, Qt::AlignLeft | Qt::AlignVCenter); totalsLayout->addWidget(feeValueLbl, 1, 1, Qt::AlignLeft | Qt::AlignVCenter); totalsLayout->addWidget(feeCol3, 1, 2 ); totalsLayout->addWidget(gdiv2, 2, 0, 1, 3, Qt::AlignVCenter); totalsLayout->addWidget(totalLbl, 3, 0, Qt::AlignLeft | Qt::AlignVCenter); totalsLayout->addWidget(totalValueLbl, 3, 1, Qt::AlignLeft | Qt::AlignVCenter); totalsLayout->addWidget(totalCol3, 3, 2 ); totalsLayout->addWidget(gdiv3, 4, 0, 1, 3, Qt::AlignVCenter); totalsLayout->addWidget(warningLbl, 5, 0, 1, 3, Qt::AlignLeft); totalsLayout->setColumnStretch(2, 1); // 3rd column totalsLayout->setRowMinimumHeight(0, BGU::spi(15)); // div 1 totalsLayout->setRowMinimumHeight(1, BGU::spi(40)); // fee totalsLayout->setRowMinimumHeight(2, BGU::spi(15)); // div 2 totalsLayout->setRowMinimumHeight(3, BGU::spi(40)); // total totalsLayout->setRowMinimumHeight(4, BGU::spi(15)); // div 3 totalsLayout->setRowMinimumHeight(5, BGU::spi(30)); // warning confirmBtn = new BlocknetFormBtn; confirmBtn->setText(tr("Confirm Payment")); confirmBtn->setFocusPolicy(Qt::TabFocus); cancelBtn = new BlocknetFormBtn; cancelBtn->setObjectName("cancel"); cancelBtn->setText(tr("Cancel")); auto *btnBox = new QFrame; auto *btnBoxLayout = new QHBoxLayout; btnBoxLayout->setContentsMargins(QMargins()); btnBoxLayout->setSpacing(BGU::spi(15)); btnBox->setLayout(btnBoxLayout); btnBoxLayout->addWidget(cancelBtn, 0, Qt::AlignLeft); btnBoxLayout->addWidget(confirmBtn, 0, Qt::AlignLeft); btnBoxLayout->addStretch(1); layout->addWidget(titleLbl, 0, Qt::AlignTop | Qt::AlignLeft); layout->addSpacing(BGU::spi(40)); layout->addWidget(subtitleLbl, 0, Qt::AlignTop); layout->addSpacing(BGU::spi(20)); layout->addWidget(addrBox, 0, Qt::AlignLeft); layout->addSpacing(BGU::spi(10)); layout->addWidget(div1, 0); layout->addSpacing(BGU::spi(20)); layout->addWidget(amountLbl, 0); layout->addSpacing(BGU::spi(20)); layout->addWidget(amountBox, 0); layout->addSpacing(BGU::spi(20)); layout->addWidget(totalGrid, 0); layout->addSpacing(BGU::spi(20)); layout->addWidget(btnBox); layout->addStretch(1); connect(amountTi, &BlocknetLineEdit::textEdited, this, [this](const QString & text) { onAmountChanged(); }); connect(cancelBtn, &BlocknetFormBtn::clicked, this, &BlocknetQuickSend::onCancel); connect(confirmBtn, &BlocknetFormBtn::clicked, this, &BlocknetQuickSend::onSubmit); connect(addAddressBtn, &BlocknetIconBtn::clicked, this, &BlocknetQuickSend::openAddressBook); } bool BlocknetQuickSend::validated() { return walletModel->validateAddress(addressTi->text()) && !amountTi->text().isEmpty() && BlocknetSendFundsModel::stringToInt(amountTi->text(), displayUnit) > 0; } void BlocknetQuickSend::keyPressEvent(QKeyEvent *event) { QWidget::keyPressEvent(event); if (this->isHidden()) return; if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) onSubmit(); } bool BlocknetQuickSend::focusNextPrevChild(bool next) { if (next && amountTi->hasFocus()) { amountTi->clearFocus(); this->setFocus(Qt::FocusReason::ActiveWindowFocusReason); return true; } return QFrame::focusNextPrevChild(next); } void BlocknetQuickSend::mouseReleaseEvent(QMouseEvent *event) { QWidget::mouseReleaseEvent(event); if (this->amountTi->hasFocus() && !this->amountTi->rect().contains(event->pos())) { this->amountTi->clearFocus(); this->setFocus(Qt::FocusReason::ActiveWindowFocusReason); } } void BlocknetQuickSend::showEvent(QShowEvent *event) { QWidget::showEvent(event); if (!addressTi->hasFocus() && !amountTi->hasFocus()) addressTi->setFocus(Qt::FocusReason::ActiveWindowFocusReason); connect(walletModel, &WalletModel::encryptionStatusChanged, this, &BlocknetQuickSend::onEncryptionStatus); connect(walletModel->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &BlocknetQuickSend::onDisplayUnit); } void BlocknetQuickSend::hideEvent(QHideEvent *event) { QWidget::hideEvent(event); disconnect(walletModel, &WalletModel::encryptionStatusChanged, this, &BlocknetQuickSend::onEncryptionStatus); disconnect(walletModel->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &BlocknetQuickSend::onDisplayUnit); } void BlocknetQuickSend::addAddress(const QString &address) { addressTi->setText(address); } void BlocknetQuickSend::openAddressBook() { BlocknetAddressBookDialog dlg(walletModel, Qt::WindowSystemMenuHint | Qt::WindowTitleHint); dlg.singleShotMode(); connect(&dlg, &BlocknetAddressBookDialog::send, [this](const QString &address) { addAddress(address); }); dlg.exec(); } void BlocknetQuickSend::onAmountChanged() { BlocknetSendFundsModel model; const auto addrLabel = walletModel->getAddressTableModel()->labelForAddress(addressTi->text()); model.addRecipient(addressTi->text(), BlocknetSendFundsModel::stringToInt(amountTi->text(), displayUnit), addrLabel); CCoinControl cc = model.getCoinControl(walletModel); if (!walletModel->wallet().isLocked()) { // if the wallet is unlocked, calculate exact fees auto status = model.prepareFunds(walletModel, cc); QString feeAmount = BitcoinUnits::formatWithUnit(displayUnit, model.txFees()); feeValueLbl->setText(feeAmount); // Display or clear the warning message according to the wallet status if (status.status != WalletModel::OK) warningLbl->setText(BlocknetSendFundsPage::processSendCoinsReturn(walletModel, status).first); else warningLbl->clear(); } else if (cc.HasSelected()) { // estimate b/c wallet is locked here const auto feeInfo = BlocknetEstimateFee(walletModel, cc, model.subtractFee(), model.txRecipients()); QString feeAmount = BitcoinUnits::formatWithUnit(displayUnit, std::get<0>(feeInfo)); feeValueLbl->setText(QString("%1 %2").arg(feeAmount, tr("(estimated)"))); model.setEstimatedFees(std::get<0>(feeInfo)); } else { // estimate b/c wallet is locked here cc.m_feerate.reset(); // explicitly use only fee estimation rate for smart fee labels int estimatedConfirmations; FeeReason reason; CFeeRate feeRate = CFeeRate(walletModel->wallet().getMinimumFee(1000, cc, &estimatedConfirmations, &reason)); QString feeAmount = BitcoinUnits::formatWithUnit(displayUnit, feeRate.GetFeePerK()) + "/kB"; feeValueLbl->setText(QString("%1 %2").arg(feeAmount, tr("(estimated)"))); model.setEstimatedFees(feeRate.GetFeePerK()); } CAmount fees = walletModel->wallet().isLocked() ? model.estimatedFees() : model.txFees(); if (model.subtractFee()) fees *= -1; totalValueLbl->setText(BitcoinUnits::formatWithUnit(displayUnit, (walletModel->wallet().isLocked() ? fees : 0) + model.txTotalAmount())); } void BlocknetQuickSend::onSubmit() { if (!this->validated()) { QMessageBox::warning(this->parentWidget(), tr("Issue"), tr("Please specify a send address and an amount larger than %1") .arg(BitcoinUnits::formatWithUnit(displayUnit, ::minRelayTxFee.GetFeePerK()))); return; } // Unlock wallet context (for relock) WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == WalletModel::EncryptionStatus::Locked || util::unlockedForStakingOnly) { const bool stateUnlockForStaking = util::unlockedForStakingOnly; WalletModel::UnlockContext ctx(walletModel->requestUnlock()); if (!ctx.isValid() || util::unlockedForStakingOnly) { QMessageBox::warning(this->parentWidget(), tr("Issue"), tr("Failed to unlock the wallet")); } else { submitFunds(); util::unlockedForStakingOnly = stateUnlockForStaking; // restore unlocked for staking state } return; } submitFunds(); } WalletModel::SendCoinsReturn BlocknetQuickSend::submitFunds() { QList<SendCoinsRecipient> recipients; const auto addrLabel = walletModel->getAddressTableModel()->labelForAddress(addressTi->text()); recipients.push_back(SendCoinsRecipient{ addressTi->text(), addrLabel, BlocknetSendFundsModel::stringToInt(amountTi->text(), displayUnit), QString() }); WalletModelTransaction currentTransaction(recipients); CCoinControl ctrl; WalletModel::SendCoinsReturn prepareStatus = walletModel->prepareTransaction(currentTransaction, ctrl); const auto feeMsg = BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), currentTransaction.getTransactionFee()); if (prepareStatus.status != WalletModel::OK) { // process prepareStatus and on error generate message shown to user auto res = BlocknetSendFundsPage::processSendCoinsReturn(walletModel, prepareStatus, feeMsg); updateLabels(prepareStatus); if (res.second) QMessageBox::critical(this->parentWidget(), tr("Issue"), res.first); else QMessageBox::warning(this->parentWidget(), tr("Issue"), res.first); return prepareStatus; } const auto txFee = currentTransaction.getTransactionFee(); const auto totalAmt = currentTransaction.getTotalTransactionAmount() + txFee; // Update labels feeValueLbl->setText(BitcoinUnits::formatWithUnit(displayUnit, txFee)); totalValueLbl->setText(BitcoinUnits::formatWithUnit(displayUnit, totalAmt)); // Format confirmation message QStringList formatted; QString questionString = tr("Are you sure you want to send?"); questionString.append("<br /><span style='font-size:10pt;'>"); questionString.append(tr("Please, review your transaction.")); questionString.append("</span><br />%1"); if (txFee > 0) { // append fee string if a fee is required questionString.append("<hr /><b>"); questionString.append(tr("Transaction fee")); questionString.append("</b>"); // append transaction size questionString.append(" (" + QString::number((double)currentTransaction.getTransactionSize() / 1000) + " kB): "); // append transaction fee value questionString.append("<span style='color:#aa0000; font-weight:bold;'>"); questionString.append(BitcoinUnits::formatHtmlWithUnit(displayUnit, txFee)); questionString.append("</span><br />"); } // add total amount in all subdivision units questionString.append("<hr />"); questionString.append(QString("<b>%1</b>: <b>%2</b>").arg(tr("Total Amount")) .arg(BitcoinUnits::formatHtmlWithUnit(displayUnit, totalAmt))); SendConfirmationDialog confirmationDialog(tr("Confirm send coins"), questionString.arg(formatted.join("<br />")), SEND_CONFIRM_DELAY, this); confirmationDialog.exec(); WalletModel::SendCoinsReturn sendStatus(WalletModel::StatusCode::TransactionCommitFailed); bool canceledSend{false}; auto retval = static_cast<QMessageBox::StandardButton>(confirmationDialog.result()); if (retval == QMessageBox::Yes) { // now send the prepared transaction sendStatus = walletModel->sendCoins(currentTransaction); // process sendStatus and on error generate message shown to user auto res = BlocknetSendFundsPage::processSendCoinsReturn(walletModel, sendStatus, feeMsg); if (sendStatus.status == WalletModel::OK) Q_EMIT submit(); else { updateLabels(sendStatus); if (res.second) QMessageBox::critical(this->parentWidget(), tr("Issue"), res.first); else QMessageBox::warning(this->parentWidget(), tr("Issue"), res.first); } } else canceledSend = true; // Display warning message if necessary if (!canceledSend && sendStatus.status != WalletModel::OK && warningLbl) warningLbl->setText(BlocknetSendFundsRequest::sendStatusMsg(sendStatus, "", displayUnit)); return sendStatus; } void BlocknetQuickSend::onEncryptionStatus() { if (walletModel->getEncryptionStatus() == WalletModel::Unlocked && !addressTi->text().isEmpty()) onAmountChanged(); } void BlocknetQuickSend::onDisplayUnit(int unit) { displayUnit = unit; amountTi->setValidator(new BlocknetNumberValidator(0, BLOCKNETGUI_FUNDS_MAX, BitcoinUnits::decimals(displayUnit))); onAmountChanged(); } void BlocknetQuickSend::updateLabels(const WalletModel::SendCoinsReturn & result) { // Handle errors if (result.status != WalletModel::OK) warningLbl->setText(BlocknetSendFundsRequest::sendStatusMsg(result, "", displayUnit)); else warningLbl->clear(); feeValueLbl->setText(QString("%1 %2").arg(BitcoinUnits::formatWithUnit(displayUnit, txFees), tr("(estimated)"))); totalValueLbl->setText(BitcoinUnits::formatWithUnit(displayUnit, totalAmount)); }
46.052219
141
0.688003
mraksoll4
f5d736ca137cd0cc012a6c46249853388c41060f
10,851
cpp
C++
src/tty_interface.cpp
lanza/fzy
b5a04d7789f84a55d05f683cc443739e8fcae5c7
[ "MIT" ]
null
null
null
src/tty_interface.cpp
lanza/fzy
b5a04d7789f84a55d05f683cc443739e8fcae5c7
[ "MIT" ]
null
null
null
src/tty_interface.cpp
lanza/fzy
b5a04d7789f84a55d05f683cc443739e8fcae5c7
[ "MIT" ]
null
null
null
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../config.h" #include "fzxx/match.h" #include "fzxx/tty_interface.h" static int isprint_unicode(char c) { return isprint(c) || c & (1 << 7); } static int is_boundary(char c) { return ~c & (1 << 7) || c & (1 << 6); } static void clear(tty_interface_t *state) { TTYWrapper *tty = state->tty; tty->setcol(0); size_t line = 0; while (line++ < state->options->num_lines) { tty->newline(); } tty->clearline(); if (state->options->num_lines > 0) { tty->moveup(line - 1); } tty->flush(); } static void draw_match(tty_interface_t *state, const char *choice, int selected) { TTYWrapper *tty = state->tty; options_t *options = state->options; char *search = state->last_search; int n = strlen(search); size_t positions[n + 1]; for (int i = 0; i < n + 1; i++) positions[i] = -1; score_t score = match_positions(search, choice, &positions[0]); if (options->show_scores) { if (score == SCORE_MIN) { tty->printf("( ) "); } else { tty->printf("(%5.2f) ", score); } } if (selected) #ifdef TTY_SELECTION_UNDERLINE tty->setunderline(); #else tty->setinvert(); #endif tty->setnowrap(); for (size_t i = 0, p = 0; choice[i] != '\0'; i++) { if (positions[p] == i) { tty->setfg(TTY_COLOR_HIGHLIGHT); p++; } else { tty->setfg(TTY_COLOR_NORMAL); } tty->printf("%c", choice[i]); } tty->setwrap(); tty->setnormal(); } static void draw(tty_interface_t *state) { TTYWrapper *tty = state->tty; choices_t *choices = state->choices; options_t *options = state->options; unsigned int num_lines = options->num_lines; size_t start = 0; size_t current_selection = choices->selection; if (current_selection + options->scrolloff >= num_lines) { start = current_selection + options->scrolloff - num_lines + 1; size_t available = choices_available(choices); if (start + num_lines >= available && available > 0) { start = available - num_lines; } } tty->setcol(0); tty->printf("%s%s", options->prompt, state->search); tty->clearline(); for (size_t i = start; i < start + num_lines; i++) { tty->printf("\n"); tty->clearline(); const char *choice = choices_get(choices, i); if (choice) { draw_match(state, choice, i == choices->selection); } } if (num_lines > 0) { tty->moveup(num_lines); } tty->setcol(0); fputs(options->prompt, tty->fout); for (size_t i = 0; i < state->cursor; i++) fputc(state->search[i], tty->fout); tty->flush(); } static void update_search(tty_interface_t *state) { choices_search(state->choices, state->search); strcpy(state->last_search, state->search); } static void update_state(tty_interface_t *state) { if (strcmp(state->last_search, state->search)) { update_search(state); draw(state); } } static void action_emit(tty_interface_t *state) { update_state(state); /* Reset the tty as close as possible to the previous state */ clear(state); /* ttyout should be flushed before outputting on stdout */ state->tty->close(); const char *selection = choices_get(state->choices, state->choices->selection); if (selection) { /* output the selected result */ printf("%s\n", selection); } else { /* No match, output the query instead */ printf("%s\n", state->search); } state->exit = EXIT_SUCCESS; } static void action_del_char(tty_interface_t *state) { if (*state->search) { size_t length = strlen(state->search); if (state->cursor == 0) { return; } size_t original_cursor = state->cursor; state->cursor--; while (!is_boundary(state->search[state->cursor]) && state->cursor) state->cursor--; memmove(&state->search[state->cursor], &state->search[original_cursor], length - original_cursor + 1); } } static void action_del_word(tty_interface_t *state) { size_t original_cursor = state->cursor; size_t cursor = state->cursor; while (cursor && isspace(state->search[cursor - 1])) cursor--; while (cursor && !isspace(state->search[cursor - 1])) cursor--; memmove(&state->search[cursor], &state->search[original_cursor], strlen(state->search) - original_cursor + 1); state->cursor = cursor; } static void action_del_all(tty_interface_t *state) { memmove(state->search, &state->search[state->cursor], strlen(state->search) - state->cursor + 1); state->cursor = 0; } static void action_prev(tty_interface_t *state) { update_state(state); choices_prev(state->choices); } static void action_ignore(tty_interface_t *state) { (void)state; } static void action_next(tty_interface_t *state) { update_state(state); choices_next(state->choices); } static void action_left(tty_interface_t *state) { if (state->cursor > 0) { state->cursor--; while (!is_boundary(state->search[state->cursor]) && state->cursor) state->cursor--; } } static void action_right(tty_interface_t *state) { if (state->cursor < strlen(state->search)) { state->cursor++; while (!is_boundary(state->search[state->cursor])) state->cursor++; } } static void action_beginning(tty_interface_t *state) { state->cursor = 0; } static void action_end(tty_interface_t *state) { state->cursor = strlen(state->search); } static void action_pageup(tty_interface_t *state) { update_state(state); for (size_t i = 0; i < state->options->num_lines && state->choices->selection > 0; i++) choices_prev(state->choices); } static void action_pagedown(tty_interface_t *state) { update_state(state); for (size_t i = 0; i < state->options->num_lines && state->choices->selection < state->choices->available - 1; i++) choices_next(state->choices); } static void action_autocomplete(tty_interface_t *state) { update_state(state); const char *current_selection = choices_get(state->choices, state->choices->selection); if (current_selection) { strncpy(state->search, choices_get(state->choices, state->choices->selection), SEARCH_SIZE_MAX); state->cursor = strlen(state->search); } } static void action_exit(tty_interface_t *state) { clear(state); state->tty->close(); state->exit = EXIT_FAILURE; } static void append_search(tty_interface_t *state, char ch) { char *search = state->search; size_t search_size = strlen(search); if (search_size < SEARCH_SIZE_MAX) { memmove(&search[state->cursor + 1], &search[state->cursor], search_size - state->cursor + 1); search[state->cursor] = ch; state->cursor++; } } void tty_interface_init(tty_interface_t *state, TTYWrapper *tty, choices_t *choices, options_t *options) { state->tty = tty; state->choices = choices; state->options = options; state->ambiguous_key_pending = 0; strcpy(state->input, ""); strcpy(state->search, ""); strcpy(state->last_search, ""); state->exit = -1; if (options->init_search) strncpy(state->search, options->init_search, SEARCH_SIZE_MAX); state->cursor = strlen(state->search); update_search(state); } typedef struct { const char *key; void (*action)(tty_interface_t *); } keybinding_t; #define KEY_CTRL(key) ((const char[]){((key) - ('@')), '\0'}) static const keybinding_t keybindings[] = { {"\x1b", action_exit}, /* ESC */ {"\x7f", action_del_char}, /* DEL */ {KEY_CTRL('H'), action_del_char}, /* Backspace (C-H) */ {KEY_CTRL('W'), action_del_word}, /* C-W */ {KEY_CTRL('U'), action_del_all}, /* C-U */ {KEY_CTRL('I'), action_autocomplete}, /* TAB (C-I ) */ {KEY_CTRL('C'), action_exit}, /* C-C */ {KEY_CTRL('D'), action_exit}, /* C-D */ {KEY_CTRL('M'), action_emit}, /* CR */ {KEY_CTRL('P'), action_prev}, /* C-P */ {KEY_CTRL('N'), action_next}, /* C-N */ {KEY_CTRL('K'), action_prev}, /* C-K */ {KEY_CTRL('J'), action_next}, /* C-J */ {KEY_CTRL('A'), action_beginning}, /* C-A */ {KEY_CTRL('E'), action_end}, /* C-E */ {"\x1bOD", action_left}, /* LEFT */ {"\x1b[D", action_left}, /* LEFT */ {"\x1bOC", action_right}, /* RIGHT */ {"\x1b[C", action_right}, /* RIGHT */ {"\x1b[1~", action_beginning}, /* HOME */ {"\x1b[H", action_beginning}, /* HOME */ {"\x1b[4~", action_end}, /* END */ {"\x1b[F", action_end}, /* END */ {"\x1b[A", action_prev}, /* UP */ {"\x1bOA", action_prev}, /* UP */ {"\x1b[B", action_next}, /* DOWN */ {"\x1bOB", action_next}, /* DOWN */ {"\x1b[5~", action_pageup}, {"\x1b[6~", action_pagedown}, {"\x1b[200~", action_ignore}, {"\x1b[201~", action_ignore}, {NULL, NULL}}; #undef KEY_CTRL static void handle_input(tty_interface_t *state, const char *s, int handle_ambiguous_key) { state->ambiguous_key_pending = 0; char *input = state->input; strcat(state->input, s); /* Figure out if we have completed a keybinding and whether we're in the * middle of one (both can happen, because of Esc). */ int found_keybinding = -1; int in_middle = 0; for (int i = 0; keybindings[i].key; i++) { if (!strcmp(input, keybindings[i].key)) found_keybinding = i; else if (!strncmp(input, keybindings[i].key, strlen(state->input))) in_middle = 1; } /* If we have an unambiguous keybinding, run it. */ if (found_keybinding != -1 && (!in_middle || handle_ambiguous_key)) { keybindings[found_keybinding].action(state); strcpy(input, ""); return; } /* We could have a complete keybinding, or could be in the middle of one. * We'll need to wait a few milliseconds to find out. */ if (found_keybinding != -1 && in_middle) { state->ambiguous_key_pending = 1; return; } /* Wait for more if we are in the middle of a keybinding */ if (in_middle) return; /* No matching keybinding, add to search */ for (int i = 0; input[i]; i++) if (isprint_unicode(input[i])) append_search(state, input[i]); /* We have processed the input, so clear it */ strcpy(input, ""); } int tty_interface_run(tty_interface_t *state) { draw(state); for (;;) { do { char s[2] = {state->tty->getchar(), '\0'}; handle_input(state, s, 0); if (state->exit >= 0) return state->exit; draw(state); } while (state->tty->input_ready(state->ambiguous_key_pending)); if (state->ambiguous_key_pending) { char s[1] = ""; handle_input(state, s, 1); if (state->exit >= 0) return state->exit; } update_state(state); } return state->exit; }
27.263819
79
0.61469
lanza
f5d75d5299d2004eb65463fa93108348b0cf7f4c
20,819
cpp
C++
src/storage/data_table.cpp
hjhhsy120/terrier
c53e1ac9de629ec340c42e9797a7460fdf2a56dc
[ "MIT" ]
1
2019-03-08T18:59:57.000Z
2019-03-08T18:59:57.000Z
src/storage/data_table.cpp
LiuXiaoxuanPKU/terrier
35916e9435201016903d8a01e3f587b8edb36f0b
[ "MIT" ]
34
2019-03-21T20:47:59.000Z
2019-05-17T06:06:46.000Z
src/storage/data_table.cpp
LiuXiaoxuanPKU/terrier
35916e9435201016903d8a01e3f587b8edb36f0b
[ "MIT" ]
null
null
null
#include "storage/data_table.h" #include <pthread.h> #include <cstring> #include <list> #include <unordered_map> #include "common/allocator.h" #include "storage/block_access_controller.h" #include "storage/storage_util.h" #include "transaction/transaction_context.h" #include "transaction/transaction_util.h" namespace terrier::storage { DataTable::DataTable(BlockStore *const store, const BlockLayout &layout, const layout_version_t layout_version) : block_store_(store), layout_version_(layout_version), accessor_(layout) { TERRIER_ASSERT(layout.AttrSize(VERSION_POINTER_COLUMN_ID) == 8, "First column must have size 8 for the version chain."); TERRIER_ASSERT(layout.NumColumns() > NUM_RESERVED_COLUMNS, "First column is reserved for version info, second column is reserved for logical delete."); if (block_store_ != nullptr) { RawBlock *new_block = NewBlock(); // insert block blocks_.push_back(new_block); } insertion_head_ = blocks_.begin(); } DataTable::~DataTable() { common::SpinLatch::ScopedSpinLatch guard(&blocks_latch_); for (RawBlock *block : blocks_) { StorageUtil::DeallocateVarlens(block, accessor_); for (col_id_t i : accessor_.GetBlockLayout().Varlens()) accessor_.GetArrowBlockMetadata(block).GetColumnInfo(accessor_.GetBlockLayout(), i).Deallocate(); block_store_->Release(block); } } bool DataTable::Select(terrier::transaction::TransactionContext *txn, terrier::storage::TupleSlot slot, terrier::storage::ProjectedRow *out_buffer) const { data_table_counter_.IncrementNumSelect(1); return SelectIntoBuffer(txn, slot, out_buffer); } void DataTable::Scan(transaction::TransactionContext *const txn, SlotIterator *const start_pos, ProjectedColumns *const out_buffer) const { // TODO(Tianyu): So far this is not that much better than tuple-at-a-time access, // but can be improved if block is read-only, or if we implement version synopsis, to just use std::memcpy when it's // safe uint32_t filled = 0; while (filled < out_buffer->MaxTuples() && *start_pos != end()) { ProjectedColumns::RowView row = out_buffer->InterpretAsRow(filled); const TupleSlot slot = **start_pos; // Only fill the buffer with valid, visible tuples if (SelectIntoBuffer(txn, slot, &row)) { out_buffer->TupleSlots()[filled] = slot; filled++; } ++(*start_pos); } out_buffer->SetNumTuples(filled); } DataTable::SlotIterator &DataTable::SlotIterator::operator++() { common::SpinLatch::ScopedSpinLatch guard(&table_->blocks_latch_); // Jump to the next block if already the last slot in the block. if (current_slot_.GetOffset() == table_->accessor_.GetBlockLayout().NumSlots() - 1) { ++block_; // Cannot dereference if the next block is end(), so just use nullptr to denote current_slot_ = {block_ == table_->blocks_.end() ? nullptr : *block_, 0}; } else { current_slot_ = {*block_, current_slot_.GetOffset() + 1}; } return *this; } DataTable::SlotIterator DataTable::end() const { // NOLINT for STL name compability common::SpinLatch::ScopedSpinLatch guard(&blocks_latch_); // TODO(Tianyu): Need to look in detail at how this interacts with compaction when that gets in. // The end iterator could either point to an unfilled slot in a block, or point to nothing if every block in the // table is full. In the case that it points to nothing, we will use the end-iterator of the blocks list and // 0 to denote that this is the case. This solution makes increment logic simple and natural. if (blocks_.empty()) return {this, blocks_.end(), 0}; auto last_block = --blocks_.end(); uint32_t insert_head = (*last_block)->GetInsertHead(); // Last block is full, return the default end iterator that doesn't point to anything if (insert_head == accessor_.GetBlockLayout().NumSlots()) return {this, blocks_.end(), 0}; // Otherwise, insert head points to the slot that will be inserted next, which would be exactly what we want. return {this, last_block, insert_head}; } bool DataTable::Update(transaction::TransactionContext *const txn, const TupleSlot slot, const ProjectedRow &redo) { TERRIER_ASSERT(redo.NumColumns() <= accessor_.GetBlockLayout().NumColumns() - NUM_RESERVED_COLUMNS, "The input buffer cannot change the reserved columns, so it should have fewer attributes."); TERRIER_ASSERT(redo.NumColumns() > 0, "The input buffer should modify at least one attribute."); UndoRecord *const undo = txn->UndoRecordForUpdate(this, slot, redo); slot.GetBlock()->controller_.WaitUntilHot(); UndoRecord *version_ptr; do { version_ptr = AtomicallyReadVersionPtr(slot, accessor_); // Since we disallow write-write conflicts, the version vector pointer is essentially an implicit // write lock on the tuple. if (HasConflict(*txn, version_ptr) || !Visible(slot, accessor_)) { // Mark this UndoRecord as never installed by setting the table pointer to nullptr. This is inspected in the // TransactionManager's Rollback() and GC's Unlink logic undo->Table() = nullptr; return false; } // Store before-image before making any changes or grabbing lock for (uint16_t i = 0; i < undo->Delta()->NumColumns(); i++) StorageUtil::CopyAttrIntoProjection(accessor_, slot, undo->Delta(), i); // Update the next pointer of the new head of the version chain undo->Next() = version_ptr; } while (!CompareAndSwapVersionPtr(slot, accessor_, version_ptr, undo)); // Update in place with the new value. for (uint16_t i = 0; i < redo.NumColumns(); i++) { TERRIER_ASSERT(redo.ColumnIds()[i] != VERSION_POINTER_COLUMN_ID, "Input buffer should not change the version pointer column."); // TODO(Matt): It would be nice to check that a ProjectedRow that modifies the logical delete column only originated // from the DataTable calling Update() within Delete(), rather than an outside soure modifying this column, but // that's difficult with this implementation StorageUtil::CopyAttrFromProjection(accessor_, slot, redo, i); } data_table_counter_.IncrementNumUpdate(1); return true; } void DataTable::CheckMoveHead(std::list<RawBlock *>::iterator block) { // Assume block is full common::SpinLatch::ScopedSpinLatch guard_head(&header_latch_); if (block == insertion_head_) { // If the header block is full, move the header to point to the next block insertion_head_++; } // If there are no more free blocks, create a new empty block and point the insertion_head to it if (insertion_head_ == blocks_.end()) { RawBlock *new_block = NewBlock(); // take latch common::SpinLatch::ScopedSpinLatch guard_block(&blocks_latch_); // insert block blocks_.push_back(new_block); // set insertion header to --end() insertion_head_ = --blocks_.end(); } } TupleSlot DataTable::Insert(transaction::TransactionContext *const txn, const ProjectedRow &redo) { TERRIER_ASSERT(redo.NumColumns() == accessor_.GetBlockLayout().NumColumns() - NUM_RESERVED_COLUMNS, "The input buffer never changes the version pointer column, so it should have exactly 1 fewer " "attribute than the DataTable's layout."); // Insertion header points to the first block that has free tuple slots // Once a txn arrives, it will start from the insertion header to find the first // idle (no other txn is trying to get tuple slots in that block) and non-full block. // If no such block is found, the txn will create a new block. // Before the txn writes to the block, it will set block status to busy. // The first bit of block insert_head_ is used to indicate if the block is busy // If the first bit is 1, it indicates one txn is writing to the block. TupleSlot result; auto block = insertion_head_; while (true) { // No free block left if (block == blocks_.end()) { RawBlock *new_block = NewBlock(); TERRIER_ASSERT(accessor_.SetBlockBusyStatus(new_block), "Status of new block should not be busy"); // No need to flip the busy status bit accessor_.Allocate(new_block, &result); // take latch common::SpinLatch::ScopedSpinLatch guard(&blocks_latch_); // insert block blocks_.push_back(new_block); block = --blocks_.end(); break; } if (accessor_.SetBlockBusyStatus(*block)) { // No one is inserting into this block if (accessor_.Allocate(*block, &result)) { // The block is not full, succeed break; } // Fail to insert into the block, flip back the status bit accessor_.ClearBlockBusyStatus(*block); // if the full block is the insertion_header, move the insertion_header // Next insert txn will search from the new insertion_header CheckMoveHead(block); } // The block is full or the block is being inserted by other txn, try next block ++block; } // Do not need to wait unit finish inserting, // can flip back the status bit once the thread gets the allocated tuple slot accessor_.ClearBlockBusyStatus(*block); InsertInto(txn, redo, result); data_table_counter_.IncrementNumInsert(1); return result; } void DataTable::InsertInto(transaction::TransactionContext *txn, const ProjectedRow &redo, TupleSlot dest) { TERRIER_ASSERT(accessor_.Allocated(dest), "destination slot must already be allocated"); TERRIER_ASSERT(accessor_.IsNull(dest, VERSION_POINTER_COLUMN_ID), "The slot needs to be logically deleted to every running transaction"); // At this point, sequential scan down the block can still see this, except it thinks it is logically deleted if we 0 // the primary key column UndoRecord *undo = txn->UndoRecordForInsert(this, dest); TERRIER_ASSERT(dest.GetBlock()->controller_.GetBlockState()->load() == BlockState::HOT, "Should only be able to insert into hot blocks"); AtomicallyWriteVersionPtr(dest, accessor_, undo); // Set the logically deleted bit to present as the undo record is ready accessor_.AccessForceNotNull(dest, VERSION_POINTER_COLUMN_ID); // Update in place with the new value. for (uint16_t i = 0; i < redo.NumColumns(); i++) { TERRIER_ASSERT(redo.ColumnIds()[i] != VERSION_POINTER_COLUMN_ID, "Insert buffer should not change the version pointer column."); StorageUtil::CopyAttrFromProjection(accessor_, dest, redo, i); } } bool DataTable::Delete(transaction::TransactionContext *const txn, const TupleSlot slot) { data_table_counter_.IncrementNumDelete(1); UndoRecord *const undo = txn->UndoRecordForDelete(this, slot); slot.GetBlock()->controller_.WaitUntilHot(); UndoRecord *version_ptr; do { version_ptr = AtomicallyReadVersionPtr(slot, accessor_); // Since we disallow write-write conflicts, the version vector pointer is essentially an implicit // write lock on the tuple. if (HasConflict(*txn, version_ptr) || !Visible(slot, accessor_)) { // Mark this UndoRecord as never installed by setting the table pointer to nullptr. This is inspected in the // TransactionManager's Rollback() and GC's Unlink logic undo->Table() = nullptr; return false; } // Update the next pointer of the new head of the version chain undo->Next() = version_ptr; } while (!CompareAndSwapVersionPtr(slot, accessor_, version_ptr, undo)); // We have the write lock. Go ahead and flip the logically deleted bit to true accessor_.SetNull(slot, VERSION_POINTER_COLUMN_ID); return true; } template <class RowType> bool DataTable::SelectIntoBuffer(transaction::TransactionContext *const txn, const TupleSlot slot, RowType *const out_buffer) const { TERRIER_ASSERT(out_buffer->NumColumns() <= accessor_.GetBlockLayout().NumColumns() - NUM_RESERVED_COLUMNS, "The output buffer never returns the version pointer columns, so it should have " "fewer attributes."); TERRIER_ASSERT(out_buffer->NumColumns() > 0, "The output buffer should return at least one attribute."); // This cannot be visible if it's already deallocated. if (!accessor_.Allocated(slot)) return false; UndoRecord *version_ptr; bool visible; do { version_ptr = AtomicallyReadVersionPtr(slot, accessor_); // Copy the current (most recent) tuple into the output buffer. These operations don't need to be atomic, // because so long as we set the version ptr before updating in place, the reader will know if a conflict // can potentially happen, and chase the version chain before returning anyway, for (uint16_t i = 0; i < out_buffer->NumColumns(); i++) { TERRIER_ASSERT(out_buffer->ColumnIds()[i] != VERSION_POINTER_COLUMN_ID, "Output buffer should not read the version pointer column."); StorageUtil::CopyAttrIntoProjection(accessor_, slot, out_buffer, i); } // We still need to check the allocated bit because GC could have flipped it since last check visible = Visible(slot, accessor_); // Here we will need to check that the version pointer did not change during our read. If it did, the content // we have read might have been rolled back and an abort has already unlinked the associated undo-record, // we will have to loop around to avoid a dirty read. // // There is still an a-b-a problem if aborting transactions unlink themselves. Thus, in the system aborting // transactions still check out a timestamp and "commit" after rolling back their changes to guard against this, // The exact interleaving is this: // // transaction 1 transaction 2 // begin // read version_ptr // begin // write a -> a1 // read a1 // rollback a1 -> a // check version_ptr // return a1 // // For this to manifest, there has to be high contention on a given tuple slot, and insufficient CPU resources // (way more threads than there are cores, around 8x seems to work) such that threads are frequently swapped // out. compare-and-swap along with the pointer reduces the probability of this happening to be essentially // infinitesimal, but it's still a probabilistic fix. To 100% prevent this race, we have to wait until no // concurrent transaction with the abort that could have had a dirty read is alive to unlink this. The easiest // way to achieve that is to take a timestamp as well when all changes have been rolled back for an aborted // transaction, and let GC handle the unlinking. } while (version_ptr != AtomicallyReadVersionPtr(slot, accessor_)); // Nullptr in version chain means no other versions visible to any transaction alive at this point. // Alternatively, if the current transaction holds the write lock, it should be able to read its own updates. if (version_ptr == nullptr || version_ptr->Timestamp().load() == txn->FinishTime()) { return visible; } // Apply deltas until we reconstruct a version safe for us to read while (version_ptr != nullptr && transaction::TransactionUtil::NewerThan(version_ptr->Timestamp().load(), txn->StartTime())) { switch (version_ptr->Type()) { case DeltaRecordType::UPDATE: // Normal delta to be applied. Does not modify the logical delete column. StorageUtil::ApplyDelta(accessor_.GetBlockLayout(), *(version_ptr->Delta()), out_buffer); break; case DeltaRecordType::INSERT: visible = false; break; case DeltaRecordType::DELETE: visible = true; break; default: throw std::runtime_error("unexpected delta record type"); } version_ptr = version_ptr->Next(); } return visible; } template bool DataTable::SelectIntoBuffer<ProjectedRow>(transaction::TransactionContext *txn, const TupleSlot slot, ProjectedRow *const out_buffer) const; template bool DataTable::SelectIntoBuffer<ProjectedColumns::RowView>(transaction::TransactionContext *txn, const TupleSlot slot, ProjectedColumns::RowView *const out_buffer) const; UndoRecord *DataTable::AtomicallyReadVersionPtr(const TupleSlot slot, const TupleAccessStrategy &accessor) const { // Okay to ignore presence bit, because we use that for logical delete, not for validity of the version pointer value byte *ptr_location = accessor.AccessWithoutNullCheck(slot, VERSION_POINTER_COLUMN_ID); return reinterpret_cast<std::atomic<UndoRecord *> *>(ptr_location)->load(); } void DataTable::AtomicallyWriteVersionPtr(const TupleSlot slot, const TupleAccessStrategy &accessor, UndoRecord *const desired) { // Okay to ignore presence bit, because we use that for logical delete, not for validity of the version pointer value byte *ptr_location = accessor.AccessWithoutNullCheck(slot, VERSION_POINTER_COLUMN_ID); reinterpret_cast<std::atomic<UndoRecord *> *>(ptr_location)->store(desired); } bool DataTable::Visible(const TupleSlot slot, const TupleAccessStrategy &accessor) const { const bool present = accessor.Allocated(slot); const bool not_deleted = !accessor.IsNull(slot, VERSION_POINTER_COLUMN_ID); return present && not_deleted; } bool DataTable::HasConflict(const transaction::TransactionContext &txn, UndoRecord *const version_ptr) const { if (version_ptr == nullptr) return false; // Nobody owns this tuple's write lock, no older version visible const transaction::timestamp_t version_timestamp = version_ptr->Timestamp().load(); const transaction::timestamp_t txn_id = txn.FinishTime(); const transaction::timestamp_t start_time = txn.StartTime(); const bool owned_by_other_txn = (!transaction::TransactionUtil::Committed(version_timestamp) && version_timestamp != txn_id); const bool newer_committed_version = transaction::TransactionUtil::Committed(version_timestamp) && transaction::TransactionUtil::NewerThan(version_timestamp, start_time); return owned_by_other_txn || newer_committed_version; } bool DataTable::CompareAndSwapVersionPtr(const TupleSlot slot, const TupleAccessStrategy &accessor, UndoRecord *expected, UndoRecord *const desired) { // Okay to ignore presence bit, because we use that for logical delete, not for validity of the version pointer value byte *ptr_location = accessor.AccessWithoutNullCheck(slot, VERSION_POINTER_COLUMN_ID); return reinterpret_cast<std::atomic<UndoRecord *> *>(ptr_location)->compare_exchange_strong(expected, desired); } RawBlock *DataTable::NewBlock() { RawBlock *new_block = block_store_->Get(); accessor_.InitializeRawBlock(this, new_block, layout_version_); data_table_counter_.IncrementNumNewBlock(1); return new_block; } bool DataTable::HasConflict(const transaction::TransactionContext &txn, const TupleSlot slot) const { UndoRecord *const version_ptr = AtomicallyReadVersionPtr(slot, accessor_); return HasConflict(txn, version_ptr); } bool DataTable::IsVisible(const transaction::TransactionContext &txn, const TupleSlot slot) const { UndoRecord *version_ptr; bool visible; do { version_ptr = AtomicallyReadVersionPtr(slot, accessor_); // Here we will need to check that the version pointer did not change during our read. If it did, the visibility of // this tuple might have changed and we should check again. visible = Visible(slot, accessor_); } while (version_ptr != AtomicallyReadVersionPtr(slot, accessor_)); // Nullptr in version chain means no other versions visible to any transaction alive at this point. // Alternatively, if the current transaction holds the write lock, it should be able to read its own updates. if (version_ptr == nullptr || version_ptr->Timestamp().load() == txn.FinishTime()) { return visible; } // Apply deltas until we determine a version safe for us to read while (version_ptr != nullptr && transaction::TransactionUtil::NewerThan(version_ptr->Timestamp().load(), txn.StartTime())) { switch (version_ptr->Type()) { case DeltaRecordType::UPDATE: // Normal delta to be applied. Does not modify the logical delete column. break; case DeltaRecordType::INSERT: visible = false; break; case DeltaRecordType::DELETE: visible = true; } version_ptr = version_ptr->Next(); } return visible; } } // namespace terrier::storage
48.870892
120
0.706662
hjhhsy120
f5d9a478ce87317c90a39a2bb45891a397feaf34
14,016
cpp
C++
tilefetcher.cpp
ateijelo/steps
85392492fd6011c7af8f2de1604abee6f6f4b9df
[ "Apache-2.0" ]
1
2019-06-03T21:20:49.000Z
2019-06-03T21:20:49.000Z
tilefetcher.cpp
ateijelo/steps
85392492fd6011c7af8f2de1604abee6f6f4b9df
[ "Apache-2.0" ]
null
null
null
tilefetcher.cpp
ateijelo/steps
85392492fd6011c7af8f2de1604abee6f6f4b9df
[ "Apache-2.0" ]
1
2018-11-12T12:35:18.000Z
2018-11-12T12:35:18.000Z
/* * tilefetcher.cpp -- part of Steps, a simple maps app * * Copyright 2009-2016 Andy Teijelo <www.ateijelo.com> * * 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 <QApplication> #include <QtAlgorithms> #include <QByteArray> #include <QSettings> #include <QtEndian> #include <QtDebug> #include <QFile> #include <QDir> #include <QSqlError> #include <QSqlQuery> #include "disktask.h" #include "networktask.h" #include "tilefetcher.h" #include "constants.h" #include "debug.h" TileFetcher::TileFetcher(QObject *parent) : QObject(parent) { for (int i=0; i<2; i++) { QThread *t = new QThread(this); idleDiskThreads.insert(t); t->start(); } for (int i=0; i<1; i++) { QThread *t = new QThread(this); idleNetworkThreads.insert(t); t->start(); } wakeUpEvent = QEvent::Type(QEvent::registerEventType()); pendingWakeUp = false; } TileFetcher::~TileFetcher() { foreach (QThread *t, idleDiskThreads+activeDiskThreads+idleNetworkThreads+activeNetworkThreads) { t->quit(); t->wait(); } } void TileFetcher::customEvent(QEvent *event) { fDebug(DEBUG_FETCHREQUESTS) << "TileFetcher::customEvent()"; if (event->type() == wakeUpEvent) { fDebug(DEBUG_FETCHREQUESTS) << " wakeUpEvent"; pendingWakeUp = false; work(); } } void TileFetcher::wakeUp() { fDebug(DEBUG_FETCHREQUESTS) << "TileFetcher::wakeUp()"; if (!pendingWakeUp) { pendingWakeUp = true; qApp->postEvent(this, new QEvent(wakeUpEvent)); } } void TileFetcher::fetchTile(const QString &maptype, int x, int y, int zoom) { fDebug(DEBUG_FETCHREQUESTS) << "TileFetcher::fetchTile" << maptype << x << y << zoom; // QMutexLocker l(&mutex); TileId r(maptype,x,y,zoom); if (requests.contains(r)) { fDebug(DEBUG_FETCHREQUESTS) << " request already queued."; return; } if (diskRequests.contains(r)) { fDebug(DEBUG_FETCHREQUESTS) << " request already in disk queue."; return; } if (networkRequests.contains(r)) { fDebug(DEBUG_FETCHREQUESTS) << " request already in network queue."; return; } requests.insert(r); wakeUp(); } void TileFetcher::forgetRequest(const QString &type, int x, int y, int zoom) { fDebug(DEBUG_FETCHREQUESTS) << "TileFetcher::forgetRequest" << type << x << y << zoom; // QMutexLocker l(&mutex); TileId r(type,x,y,zoom); QSet<TileId>::iterator i; i = requests.find(r); if (i != requests.end()) { requests.erase(i); } i = diskRequests.find(r); if (i != diskRequests.end()) { diskRequests.erase(i); } i = networkRequests.find(r); if (i != networkRequests.end()) { networkRequests.erase(i); } } void TileFetcher::networkTileData(const QString &type, int x, int y, int z, const QByteArray &data) { TileId tile(type,x,y,z); if (!data.isEmpty()) { emit tileData(type,x,y,z,data); memCache.insert(tile,data); diskWriteRequests.insert(tile,data); } activeNetworkRequests.remove(tile); wakeUp(); } void TileFetcher::diskTaskFinished(Task *task) { QThread* thread = task->thread(); QSet<QThread*>::iterator i = activeDiskThreads.find(thread); if (i == activeDiskThreads.end()) { fDebug(DEBUG_DISK) << "The thread of the disk task that just finished is not in the active list!"; exit(EXIT_FAILURE); } activeDiskThreads.erase(i); idleDiskThreads.insert(thread); task->deleteLater(); wakeUp(); } void TileFetcher::networkTaskFinished(Task *task) { QThread* thread = task->thread(); QSet<QThread*>::iterator i = activeNetworkThreads.find(thread); if (i == activeNetworkThreads.end()) { fDebug(DEBUG_NETWORK) << "The thread of the network task just finished is not in the active list!"; exit(EXIT_FAILURE); } activeNetworkThreads.erase(i); idleNetworkThreads.insert(thread); NetworkTask *n = static_cast<NetworkTask*>(task); activeNetworkRequests.remove(n->tileId()); task->deleteLater(); wakeUp(); } void TileFetcher::reload() { memCache.clear(); db.close(); } void TileFetcher::readMgm(const TileId& tile) { int mgm_x = tile.x >> 3; int mgm_y = tile.y >> 3; QSettings settings; QString filename = QString("%1/%2_%3/%4_%5.mgm") .arg(settings.value(SettingsKeys::CachePath,"").toString()) .arg(tile.type) .arg(tile.zoom) .arg(mgm_x) .arg(mgm_y); fDebug(DEBUG_DISK) << this << "started. Fetching" << tile.x << tile.y << "from" << filename; QFile mgm(filename); QHash<TileId,QPair<quint32,quint32> > mgmTiles; if (mgm.open(QIODevice::ReadOnly)) { quint64 r = 0; quint32 tile_start = 64*6 + 2; quint32 tile_end; quint16 no_tiles; r += mgm.read((char*)(&no_tiles),2); if (r != 2) { fDebug(DEBUG_DISK) << "error reading no_tiles"; no_tiles = 0; } no_tiles = qFromBigEndian(no_tiles); for (int i=0; i<no_tiles; i++) { quint8 tx,ty; r = mgm.read((char*)(&tx),1); r += mgm.read((char*)(&ty),1); r += mgm.read((char*)(&tile_end),4); if (r != 6) { fDebug(DEBUG_DISK) << "error reading tile entry " << i; break; } tile_end = qFromBigEndian(tile_end); TileId t(tile.type,tx + (mgm_x << 3),ty + (mgm_y << 3),tile.zoom); if (diskRequests.contains(t)) { mgmTiles.insert(t,qMakePair(tile_start,tile_end - tile_start)); diskRequests.remove(t); } tile_start = tile_end; } } if (!mgmTiles.contains(tile)) { diskRequests.remove(tile); networkRequests.insert(tile); } /* QSet<TileId>::iterator i = diskRequests.begin(); while (i != diskRequests.end()) { TileId t = *i; bool tBelongsHere = ((t.type == tile.type) && ((t.x >> 3) == mgm_x) && ((t.y >> 3) == mgm_y) && (t.zoom == tile.zoom)); if (tBelongsHere) { fDebug(DEBUG_DISK) << "tile" << t << "in queue, in the range of the mgm, but absent."; i = diskRequests.erase(i); networkRequests.insert(t); } else { i++; } } */ for (QHash<TileId,QPair<quint32,quint32> >::iterator i = mgmTiles.begin(); i != mgmTiles.end(); i++) { TileId t = i.key(); QPair<quint32,quint32> p = i.value(); quint32 tile_start = p.first; quint32 tile_size = p.second; mgm.seek(tile_start); QByteArray data = mgm.read(tile_size); if (static_cast<quint32>(data.size()) != tile_size) { fDebug(DEBUG_DISK) << "error reading tile " << tile.x << "," << tile.y << "data"; networkRequests.insert(t); continue; } else { fDebug(DEBUG_DISK) << "found tile" << t << "in mgm"; emit tileData(t.type,t.x,t.y,t.zoom,data); memCache.insert(t,data); } } } QByteArray TileFetcher::readMBTile(const TileId &tile) { QByteArray nothing; QSettings settings; QString path = settings.value(SettingsKeys::MBTilesPath,"").toString(); fDebug(DEBUG_DATABASE) << "readMBTile: " << tile; if (path.isEmpty()) { return nothing; } fDebug(DEBUG_DATABASE) << "db path:" << path; if (!db.isOpen()) { db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(path); if (!db.open()) return nothing; emit loadedMBTiles(path); fDebug(DEBUG_DATABASE) << "opened database:" << path; } //fDebug(DEBUG_DATABASE) << "db.hostName:" << db.hostName(); QSqlQuery q; q.prepare("SELECT tile_data FROM tiles WHERE " "zoom_level = :zoom AND " "tile_column = :x AND " "tile_row = :y LIMIT 1"); // .arg(tile.zoom) // .arg(tile.x) // .arg(tile.y) // ); q.bindValue(":zoom", tile.zoom); q.bindValue(":x", tile.x); q.bindValue(":y", tile.y); bool b = q.exec(); fDebug(DEBUG_DATABASE) << "exec returned" << b; //fDebug(DEBUG_DATABASE) << "x:" << tile.x << "y:" << tile.y << "zoom:" << tile.zoom; while (q.next()) { QByteArray r = q.value(0).toByteArray(); fDebug(DEBUG_DATABASE) << " query returned" << r.size() << "bytes"; return r; } fDebug(DEBUG_DATABASE) << " returned nothing"; return nothing; } bool TileFetcher::readSingleFile(const TileId& tile) { QSettings settings; QDir d(settings.value(SettingsKeys::CachePath,"").toString()); QFile f(d.absoluteFilePath(QString("cache/%1/%2/%3_%4").arg(tile.type).arg(tile.zoom).arg(tile.x).arg(tile.y))); fDebug(DEBUG_DISK) << "opening" << f.fileName(); if (f.open(QIODevice::ReadOnly)) { QByteArray data = f.readAll(); emit tileData(tile.type,tile.x,tile.y,tile.zoom,data); memCache.insert(tile,data); diskRequests.remove(tile); return true; } fDebug(DEBUG_DISK) << " failed"; return false; } void TileFetcher::work() { debug("TileFetcher::work"); while (requests.count() > 0) { QSet<TileId>::iterator i = requests.begin(); TileId r = *i; QByteArray a = memCache.getTileData(r); if (!a.isEmpty()) { emit tileData(r.type,r.x,r.y,r.zoom,a); requests.erase(i); continue; } requests.erase(i); diskRequests.insert(r); } while (diskRequests.count() > 0) { debug("while (diskRequests.count() > 0):"); QSet<TileId>::iterator i = diskRequests.begin(); TileId tile = *i; if (readSingleFile(tile)) continue; QByteArray data = readMBTile(tile); diskRequests.remove(tile); if (data.isNull()) { //fDebug(DEBUG_DISK) << "error reading tile " << tile.x << "," << tile.y << "data"; networkRequests.insert(tile); } else { //fDebug(DEBUG_DISK) << "found tile" << t << "in mgm"; emit tileData(tile.type,tile.x,tile.y,tile.zoom,data); memCache.insert(tile,data); } //readMgm(tile); } while (qMin(idleDiskThreads.count(),diskWriteRequests.count()) > 0) { QHash<TileId,QByteArray>::iterator i = diskWriteRequests.begin(); TileId r = i.key(); QByteArray a = i.value(); DiskTask *task = new DiskTask(); task->storeTile(r,a); connect(task,SIGNAL(finished(Task*)),this,SLOT(diskTaskFinished(Task*))); QSet<QThread*>::iterator j = idleDiskThreads.begin(); QThread *thread = *j; activeDiskThreads.insert(thread); idleDiskThreads.erase(j); task->moveToThread(thread); task->start(); diskWriteRequests.erase(i); } while (qMin(idleNetworkThreads.count(),networkRequests.count()) > 0) { QList<TileId> l = networkRequests.values(); qSort(l.begin(),l.end(),fetchOrder); QSet<TileId>::iterator i = networkRequests.find(l.at(0)); TileId r = *i; NetworkTask *task = new NetworkTask(r); connect(task,SIGNAL(tileData(QString,int,int,int,QByteArray)), this,SLOT(networkTileData(QString,int,int,int,QByteArray))); connect(task,SIGNAL(finished(Task*)), this,SLOT(networkTaskFinished(Task*))); QSet<QThread*>::iterator j = idleNetworkThreads.begin(); QThread *thread = *j; activeNetworkThreads.insert(thread); idleNetworkThreads.erase(j); task->moveToThread(thread); task->start(); networkRequests.erase(i); activeNetworkRequests.insert(r); } } bool fetchOrder(const TileId& t1, const TileId& t2) { if (t1.zoom < t2.zoom) return true; if (t1.zoom > t2.zoom) return false; if (t1.y < t2.y) return true; if (t1.y > t2.y) return false; if (t1.x < t2.x) return true; if (t1.x > t2.x) return false; return false; } void TileFetcher::debug(const QString& header) { if fEnabled(DEBUG_FETCHQUEUES) { qDebug() << header; // qDebug() << " idleDiskThreads:" << idleDiskThreads; qDebug() << " requests:"; foreach (const TileId& r, requests) qDebug() << " " << r.type << r.x << r.y << r.zoom; qDebug() << " diskRequests:"; foreach (const TileId& r, diskRequests) qDebug() << " " << r.type << r.x << r.y << r.zoom; qDebug() << " networkRequests:"; foreach (const TileId& r, networkRequests) qDebug() << " " << r.type << r.x << r.y << r.zoom; qDebug() << " activeNetworkRequests:"; foreach (const TileId& r, activeNetworkRequests) qDebug() << " " << r.type << r.x << r.y << r.zoom; } }
28.37247
116
0.560859
ateijelo
f5d9d030b9be8ddae444348af6c7a5ba2a530626
49,061
cpp
C++
Direct3D/ShadowMap/shadowmap.cpp
walbourn/directx-sdk-legacy-samples
93e8cc554b5ecb5cd574a06071ed784b6cb73fc5
[ "MIT" ]
27
2021-03-01T23:50:39.000Z
2022-03-04T03:27:17.000Z
Direct3D/ShadowMap/shadowmap.cpp
walbourn/directx-sdk-legacy-samples
93e8cc554b5ecb5cd574a06071ed784b6cb73fc5
[ "MIT" ]
3
2021-03-02T00:39:56.000Z
2021-12-02T19:50:03.000Z
Direct3D/ShadowMap/shadowmap.cpp
walbourn/directx-sdk-legacy-samples
93e8cc554b5ecb5cd574a06071ed784b6cb73fc5
[ "MIT" ]
3
2021-03-29T16:23:54.000Z
2022-03-05T08:35:05.000Z
//-------------------------------------------------------------------------------------- // File: ShadowMap.cpp // // Starting point for new Direct3D applications // // Copyright (c) Microsoft Corporation. // Licensed under the MIT License (MIT). //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTcamera.h" #include "DXUTsettingsdlg.h" #include "SDKmisc.h" #include "SDKmesh.h" #include "resource.h" //#define DEBUG_VS // Uncomment this line to debug vertex shaders //#define DEBUG_PS // Uncomment this line to debug pixel shaders #define SHADOWMAP_SIZE 512 #define HELPTEXTCOLOR D3DXCOLOR( 0.0f, 1.0f, 0.3f, 1.0f ) LPCWSTR g_aszMeshFile[] = { L"room.x", L"airplane\\airplane 2.x", L"misc\\car.x", L"misc\\sphere.x", L"UI\\arrow.x", L"UI\\arrow.x", L"UI\\arrow.x", L"UI\\arrow.x", L"UI\\arrow.x", L"UI\\arrow.x", L"UI\\arrow.x", L"UI\\arrow.x", L"ring.x", L"ring.x", }; #define NUM_OBJ (sizeof(g_aszMeshFile)/sizeof(g_aszMeshFile[0])) D3DXMATRIXA16 g_amInitObjWorld[NUM_OBJ] = { D3DXMATRIXA16( 3.5f, 0.0f, 0.0f, 0.0f, 0.0f, 3.0f, 0.0f, 0.0f, 0.0f, 0.0f, 3.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ), D3DXMATRIXA16( 0.43301f, 0.25f, 0.0f, 0.0f, -0.25f, 0.43301f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 5.0f, 1.33975f, 0.0f, 1.0f ), D3DXMATRIXA16( 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, -14.5f, -7.1f, 0.0f, 1.0f ), D3DXMATRIXA16( 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, 0.0f, 0.0f, -7.0f, 0.0f, 1.0f ), D3DXMATRIXA16( 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.5f, 0.0f, 0.0f, -9.0f, 0.0f, 0.0f, 5.0f, 0.2f, 5.0f, 1.0f ), D3DXMATRIXA16( 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.5f, 0.0f, 0.0f, -9.0f, 0.0f, 0.0f, 5.0f, 0.2f, -5.0f, 1.0f ), D3DXMATRIXA16( 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.5f, 0.0f, 0.0f, -9.0f, 0.0f, 0.0f, -5.0f, 0.2f, 5.0f, 1.0f ), D3DXMATRIXA16( 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.5f, 0.0f, 0.0f, -9.0f, 0.0f, 0.0f, -5.0f, 0.2f, -5.0f, 1.0f ), D3DXMATRIXA16( 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.5f, 0.0f, 0.0f, -9.0f, 0.0f, 0.0f, 14.0f, 0.2f, 14.0f, 1.0f ), D3DXMATRIXA16( 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.5f, 0.0f, 0.0f, -9.0f, 0.0f, 0.0f, 14.0f, 0.2f, -14.0f, 1.0f ), D3DXMATRIXA16( 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.5f, 0.0f, 0.0f, -9.0f, 0.0f, 0.0f, -14.0f, 0.2f, 14.0f, 1.0f ), D3DXMATRIXA16( 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.5f, 0.0f, 0.0f, -9.0f, 0.0f, 0.0f, -14.0f, 0.2f, -14.0f, 1.0f ), D3DXMATRIXA16( 0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9f, 0.0f, -14.5f, -9.0f, 0.0f, 1.0f ), D3DXMATRIXA16( 0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9f, 0.0f, 14.5f, -9.0f, 0.0f, 1.0f ), }; D3DVERTEXELEMENT9 g_aVertDecl[] = { { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, D3DDECL_END() }; //----------------------------------------------------------------------------- // Name: class CObj // Desc: Encapsulates a mesh object in the scene by grouping its world matrix // with the mesh. //----------------------------------------------------------------------------- #pragma warning( disable : 4324 ) struct CObj { CDXUTXFileMesh m_Mesh; D3DXMATRIXA16 m_mWorld; }; //----------------------------------------------------------------------------- // Name: class CViewCamera // Desc: A camera class derived from CFirstPersonCamera. The arrow keys and // numpad keys are disabled for this type of camera. //----------------------------------------------------------------------------- class CViewCamera : public CFirstPersonCamera { protected: virtual D3DUtil_CameraKeys MapKey( UINT nKey ) { // Provide custom mapping here. // Same as default mapping but disable arrow keys. switch( nKey ) { case 'A': return CAM_STRAFE_LEFT; case 'D': return CAM_STRAFE_RIGHT; case 'W': return CAM_MOVE_FORWARD; case 'S': return CAM_MOVE_BACKWARD; case 'Q': return CAM_MOVE_DOWN; case 'E': return CAM_MOVE_UP; case VK_HOME: return CAM_RESET; } return CAM_UNKNOWN; } }; //----------------------------------------------------------------------------- // Name: class CLightCamera // Desc: A camera class derived from CFirstPersonCamera. The letter keys // are disabled for this type of camera. This class is intended for use // by the spot light. //----------------------------------------------------------------------------- class CLightCamera : public CFirstPersonCamera { protected: virtual D3DUtil_CameraKeys MapKey( UINT nKey ) { // Provide custom mapping here. // Same as default mapping but disable arrow keys. switch( nKey ) { case VK_LEFT: return CAM_STRAFE_LEFT; case VK_RIGHT: return CAM_STRAFE_RIGHT; case VK_UP: return CAM_MOVE_FORWARD; case VK_DOWN: return CAM_MOVE_BACKWARD; case VK_PRIOR: return CAM_MOVE_UP; // pgup case VK_NEXT: return CAM_MOVE_DOWN; // pgdn case VK_NUMPAD4: return CAM_STRAFE_LEFT; case VK_NUMPAD6: return CAM_STRAFE_RIGHT; case VK_NUMPAD8: return CAM_MOVE_FORWARD; case VK_NUMPAD2: return CAM_MOVE_BACKWARD; case VK_NUMPAD9: return CAM_MOVE_UP; case VK_NUMPAD3: return CAM_MOVE_DOWN; case VK_HOME: return CAM_RESET; } return CAM_UNKNOWN; } }; //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- ID3DXFont* g_pFont = NULL; // Font for drawing text ID3DXFont* g_pFontSmall = NULL; // Font for drawing text ID3DXSprite* g_pTextSprite = NULL; // Sprite for batching draw text calls ID3DXEffect* g_pEffect = NULL; // D3DX effect interface bool g_bShowHelp = true; // If true, it renders the UI control text CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs CD3DSettingsDlg g_SettingsDlg; // Device settings dialog CDXUTDialog g_HUD; // dialog for standard controls CFirstPersonCamera g_VCamera; // View camera CFirstPersonCamera g_LCamera; // Camera obj to help adjust light CObj g_Obj[NUM_OBJ]; // Scene object meshes LPDIRECT3DVERTEXDECLARATION9 g_pVertDecl = NULL;// Vertex decl for the sample LPDIRECT3DTEXTURE9 g_pTexDef = NULL; // Default texture for objects D3DLIGHT9 g_Light; // The spot light in the scene CDXUTXFileMesh g_LightMesh; LPDIRECT3DTEXTURE9 g_pShadowMap = NULL; // Texture to which the shadow map is rendered LPDIRECT3DSURFACE9 g_pDSShadow = NULL; // Depth-stencil buffer for rendering to shadow map float g_fLightFov; // FOV of the spot light (in radian) D3DXMATRIXA16 g_mShadowProj; // Projection matrix for shadow map bool g_bRightMouseDown = false;// Indicates whether right mouse button is held bool g_bCameraPerspective // Indicates whether we should render view from = true; // the camera's or the light's perspective bool g_bFreeLight = true; // Whether the light is freely moveable. //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- #define IDC_TOGGLEFULLSCREEN 1 #define IDC_TOGGLEREF 3 #define IDC_CHANGEDEVICE 4 #define IDC_CHECKBOX 5 #define IDC_LIGHTPERSPECTIVE 6 #define IDC_ATTACHLIGHTTOCAR 7 //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- void InitializeDialogs(); bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ); HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ); void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ); void RenderText(); LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ); void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ); void CALLBACK MouseProc( bool bLeftButtonDown, bool bRightButtonDown, bool bMiddleButtonDown, bool bSideButton1Down, bool bSideButton2Down, int nMouseWheelDelta, int xPos, int yPos, void* pUserContext ); void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ); void CALLBACK OnLostDevice( void* pUserContext ); void CALLBACK OnDestroyDevice( void* pUserContext ); void RenderScene( IDirect3DDevice9* pd3dDevice, bool bRenderShadow, float fElapsedTime, const D3DXMATRIX* pmView, const D3DXMATRIX* pmProj ); //-------------------------------------------------------------------------------------- // Entry point to the program. Initializes everything and goes into a message processing // loop. Idle time is used to render the scene. //-------------------------------------------------------------------------------------- INT WINAPI wWinMain( HINSTANCE, HINSTANCE, LPWSTR, int ) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif // Initialize the camera g_VCamera.SetScalers( 0.01f, 15.0f ); g_LCamera.SetScalers( 0.01f, 8.0f ); g_VCamera.SetRotateButtons( true, false, false ); g_LCamera.SetRotateButtons( false, false, true ); // Set up the view parameters for the camera D3DXVECTOR3 vFromPt = D3DXVECTOR3( 0.0f, 5.0f, -18.0f ); D3DXVECTOR3 vLookatPt = D3DXVECTOR3( 0.0f, -1.0f, 0.0f ); g_VCamera.SetViewParams( &vFromPt, &vLookatPt ); vFromPt = D3DXVECTOR3( 0.0f, 0.0f, -12.0f ); vLookatPt = D3DXVECTOR3( 0.0f, -2.0f, 1.0f ); g_LCamera.SetViewParams( &vFromPt, &vLookatPt ); // Initialize the spot light g_fLightFov = D3DX_PI / 2.0f; g_Light.Diffuse.r = 1.0f; g_Light.Diffuse.g = 1.0f; g_Light.Diffuse.b = 1.0f; g_Light.Diffuse.a = 1.0f; g_Light.Position = D3DXVECTOR3( -8.0f, -8.0f, 0.0f ); g_Light.Direction = D3DXVECTOR3( 1.0f, -1.0f, 0.0f ); D3DXVec3Normalize( ( D3DXVECTOR3* )&g_Light.Direction, ( D3DXVECTOR3* )&g_Light.Direction ); g_Light.Range = 10.0f; g_Light.Theta = g_fLightFov / 2.0f; g_Light.Phi = g_fLightFov / 2.0f; // Set the callback functions. These functions allow DXUT to notify // the application about device changes, user input, and windows messages. The // callbacks are optional so you need only set callbacks for events you're interested // in. However, if you don't handle the device reset/lost callbacks then the sample // framework won't be able to reset your device since the application must first // release all device resources before resetting. Likewise, if you don't handle the // device created/destroyed callbacks then DXUT won't be able to // recreate your device resources. DXUTSetCallbackD3D9DeviceAcceptable( IsDeviceAcceptable ); DXUTSetCallbackD3D9DeviceCreated( OnCreateDevice ); DXUTSetCallbackD3D9DeviceReset( OnResetDevice ); DXUTSetCallbackD3D9FrameRender( OnFrameRender ); DXUTSetCallbackD3D9DeviceLost( OnLostDevice ); DXUTSetCallbackD3D9DeviceDestroyed( OnDestroyDevice ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackKeyboard( KeyboardProc ); DXUTSetCallbackMouse( MouseProc ); DXUTSetCallbackFrameMove( OnFrameMove ); DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); InitializeDialogs(); // Show the cursor and clip it when in full screen DXUTSetCursorSettings( true, true ); // Initialize DXUT and create the desired Win32 window and Direct3D // device for the application. Calling each of these functions is optional, but they // allow you to set several options which control the behavior of the framework. DXUTInit( true, true ); // Parse the command line and show msgboxes DXUTSetHotkeyHandling( true, true, true ); // handle the defaul hotkeys DXUTCreateWindow( L"ShadowMap" ); DXUTCreateDevice( true, 640, 480 ); // Pass control to DXUT for handling the message pump and // dispatching render calls. DXUT will call your FrameMove // and FrameRender callback when there is idle time between handling window messages. DXUTMainLoop(); // Perform any application-level cleanup here. Direct3D device resources are released within the // appropriate callback functions and therefore don't require any cleanup code here. return DXUTGetExitCode(); } //-------------------------------------------------------------------------------------- // Sets up the dialogs //-------------------------------------------------------------------------------------- void InitializeDialogs() { g_SettingsDlg.Init( &g_DialogResourceManager ); g_HUD.Init( &g_DialogResourceManager ); g_HUD.SetCallback( OnGUIEvent ); int iY = 10; g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 35, iY, 125, 22 ); g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 35, iY += 24, 125, 22 ); g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 35, iY += 24, 125, 22, VK_F2 ); g_HUD.AddCheckBox( IDC_CHECKBOX, L"Display help text", 35, iY += 24, 125, 22, true, VK_F1 ); g_HUD.AddCheckBox( IDC_LIGHTPERSPECTIVE, L"View from light's perspective", 0, iY += 24, 160, 22, false, L'V' ); g_HUD.AddCheckBox( IDC_ATTACHLIGHTTOCAR, L"Attach light to car", 0, iY += 24, 160, 22, false, L'F' ); } //-------------------------------------------------------------------------------------- // Called during device initialization, this code checks the device for some // minimum set of capabilities, and rejects those that don't pass by returning false. //-------------------------------------------------------------------------------------- bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext ) { // Skip backbuffer formats that don't support alpha blending IDirect3D9* pD3D = DXUTGetD3D9Object(); if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, BackBufferFormat ) ) ) return false; // Must support pixel shader 2.0 if( pCaps->PixelShaderVersion < D3DPS_VERSION( 2, 0 ) ) return false; // need to support D3DFMT_R32F render target if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_CUBETEXTURE, D3DFMT_R32F ) ) ) return false; // need to support D3DFMT_A8R8G8B8 render target if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_CUBETEXTURE, D3DFMT_A8R8G8B8 ) ) ) return false; return true; } //-------------------------------------------------------------------------------------- // This callback function is called immediately before a device is created to allow the // application to modify the device settings. The supplied pDeviceSettings parameter // contains the settings that the framework has selected for the new device, and the // application can make any desired changes directly to this structure. Note however that // DXUT will not correct invalid device settings so care must be taken // to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail. //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ) { assert( DXUT_D3D9_DEVICE == pDeviceSettings->ver ); HRESULT hr; IDirect3D9* pD3D = DXUTGetD3D9Object(); D3DCAPS9 caps; V( pD3D->GetDeviceCaps( pDeviceSettings->d3d9.AdapterOrdinal, pDeviceSettings->d3d9.DeviceType, &caps ) ); // Turn vsync off pDeviceSettings->d3d9.pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; g_SettingsDlg.GetDialogControl()->GetComboBox( DXUTSETTINGSDLG_PRESENT_INTERVAL )->SetEnabled( false ); // If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW // then switch to SWVP. if( ( caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) == 0 || caps.VertexShaderVersion < D3DVS_VERSION( 1, 1 ) ) { pDeviceSettings->d3d9.BehaviorFlags = D3DCREATE_SOFTWARE_VERTEXPROCESSING; } // Debugging vertex shaders requires either REF or software vertex processing // and debugging pixel shaders requires REF. #ifdef DEBUG_VS if( pDeviceSettings->d3d9.DeviceType != D3DDEVTYPE_REF ) { pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING; pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_PUREDEVICE; pDeviceSettings->d3d9.BehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; } #endif #ifdef DEBUG_PS pDeviceSettings->d3d9.DeviceType = D3DDEVTYPE_REF; #endif // For the first device created if its a REF device, optionally display a warning dialog box static bool s_bFirstTime = true; if( s_bFirstTime ) { s_bFirstTime = false; if( pDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_REF ) DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver ); } return true; } //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // created, which will happen during application initialization and windowed/full screen // toggles. This is the best location to create D3DPOOL_MANAGED resources since these // resources need to be reloaded whenever the device is destroyed. Resources created // here should be released in the OnDestroyDevice callback. //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; V_RETURN( g_DialogResourceManager.OnD3D9CreateDevice( pd3dDevice ) ); V_RETURN( g_SettingsDlg.OnD3D9CreateDevice( pd3dDevice ) ); // Initialize the font V_RETURN( D3DXCreateFont( pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &g_pFont ) ); V_RETURN( D3DXCreateFont( pd3dDevice, 12, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &g_pFontSmall ) ); // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the // shader debugger. Debugging vertex shaders requires either REF or software vertex // processing, and debugging pixel shaders requires REF. The // D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the // shader debugger. It enables source level debugging, prevents instruction // reordering, prevents dead code elimination, and forces the compiler to compile // against the next higher available software target, which ensures that the // unoptimized shaders do not exceed the shader model limitations. Setting these // flags will cause slower rendering since the shaders will be unoptimized and // forced into software. See the DirectX documentation for more information about // using the shader debugger. DWORD dwShaderFlags = D3DXFX_NOT_CLONEABLE; #if defined( DEBUG ) || defined( _DEBUG ) // Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags |= D3DXSHADER_DEBUG; #endif #ifdef DEBUG_VS dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; #endif #ifdef DEBUG_PS dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; #endif // Read the D3DX effect file WCHAR str[MAX_PATH]; V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"ShadowMap.fx" ) ); // If this fails, there should be debug output as to // they the .fx file failed to compile V_RETURN( D3DXCreateEffectFromFile( pd3dDevice, str, NULL, NULL, dwShaderFlags, NULL, &g_pEffect, NULL ) ); // Create vertex declaration V_RETURN( pd3dDevice->CreateVertexDeclaration( g_aVertDecl, &g_pVertDecl ) ); // Initialize the meshes for( int i = 0; i < NUM_OBJ; ++i ) { V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, g_aszMeshFile[i] ) ); if( FAILED( g_Obj[i].m_Mesh.Create( pd3dDevice, str ) ) ) return DXUTERR_MEDIANOTFOUND; V_RETURN( g_Obj[i].m_Mesh.SetVertexDecl( pd3dDevice, g_aVertDecl ) ); g_Obj[i].m_mWorld = g_amInitObjWorld[i]; } // Initialize the light mesh V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"spotlight.x" ) ); if( FAILED( g_LightMesh.Create( pd3dDevice, str ) ) ) return DXUTERR_MEDIANOTFOUND; V_RETURN( g_LightMesh.SetVertexDecl( pd3dDevice, g_aVertDecl ) ); // World transform to identity D3DXMATRIXA16 mIdent; D3DXMatrixIdentity( &mIdent ); V_RETURN( pd3dDevice->SetTransform( D3DTS_WORLD, &mIdent ) ); return S_OK; } //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // reset, which will happen after a lost device scenario. This is the best location to // create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever // the device is lost. Resources created here should be released in the OnLostDevice // callback. //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; V_RETURN( g_DialogResourceManager.OnD3D9ResetDevice() ); V_RETURN( g_SettingsDlg.OnD3D9ResetDevice() ); if( g_pFont ) V_RETURN( g_pFont->OnResetDevice() ); if( g_pFontSmall ) V_RETURN( g_pFontSmall->OnResetDevice() ); if( g_pEffect ) V_RETURN( g_pEffect->OnResetDevice() ); // Create a sprite to help batch calls when drawing many lines of text V_RETURN( D3DXCreateSprite( pd3dDevice, &g_pTextSprite ) ); // Setup the camera's projection parameters float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height; g_VCamera.SetProjParams( D3DX_PI / 4, fAspectRatio, 0.1f, 100.0f ); g_LCamera.SetProjParams( D3DX_PI / 4, fAspectRatio, 0.1f, 100.0f ); // Create the default texture (used when a triangle does not use a texture) V_RETURN( pd3dDevice->CreateTexture( 1, 1, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &g_pTexDef, NULL ) ); D3DLOCKED_RECT lr; V_RETURN( g_pTexDef->LockRect( 0, &lr, NULL, 0 ) ); *( LPDWORD )lr.pBits = D3DCOLOR_RGBA( 255, 255, 255, 255 ); V_RETURN( g_pTexDef->UnlockRect( 0 ) ); // Restore the scene objects for( int i = 0; i < NUM_OBJ; ++i ) V_RETURN( g_Obj[i].m_Mesh.RestoreDeviceObjects( pd3dDevice ) ); V_RETURN( g_LightMesh.RestoreDeviceObjects( pd3dDevice ) ); // Restore the effect variables V_RETURN( g_pEffect->SetVector( "g_vLightDiffuse", ( D3DXVECTOR4* )&g_Light.Diffuse ) ); V_RETURN( g_pEffect->SetFloat( "g_fCosTheta", cosf( g_Light.Theta ) ) ); // Create the shadow map texture V_RETURN( pd3dDevice->CreateTexture( SHADOWMAP_SIZE, SHADOWMAP_SIZE, 1, D3DUSAGE_RENDERTARGET, D3DFMT_R32F, D3DPOOL_DEFAULT, &g_pShadowMap, NULL ) ); // Create the depth-stencil buffer to be used with the shadow map // We do this to ensure that the depth-stencil buffer is large // enough and has correct multisample type/quality when rendering // the shadow map. The default depth-stencil buffer created during // device creation will not be large enough if the user resizes the // window to a very small size. Furthermore, if the device is created // with multisampling, the default depth-stencil buffer will not // work with the shadow map texture because texture render targets // do not support multisample. DXUTDeviceSettings d3dSettings = DXUTGetDeviceSettings(); V_RETURN( pd3dDevice->CreateDepthStencilSurface( SHADOWMAP_SIZE, SHADOWMAP_SIZE, d3dSettings.d3d9.pp.AutoDepthStencilFormat, D3DMULTISAMPLE_NONE, 0, TRUE, &g_pDSShadow, NULL ) ); // Initialize the shadow projection matrix D3DXMatrixPerspectiveFovLH( &g_mShadowProj, g_fLightFov, 1, 0.01f, 100.0f ); g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 ); g_HUD.SetSize( 170, pBackBufferSurfaceDesc->Height ); CDXUTControl* pControl = g_HUD.GetControl( IDC_LIGHTPERSPECTIVE ); if( pControl ) pControl->SetLocation( 0, pBackBufferSurfaceDesc->Height - 50 ); pControl = g_HUD.GetControl( IDC_ATTACHLIGHTTOCAR ); if( pControl ) pControl->SetLocation( 0, pBackBufferSurfaceDesc->Height - 25 ); return S_OK; } //-------------------------------------------------------------------------------------- // This callback function will be called once at the beginning of every frame. This is the // best location for your application to handle updates to the scene, but is not // intended to contain actual rendering calls, which should instead be placed in the // OnFrameRender callback. //-------------------------------------------------------------------------------------- void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ) { // Update the camera's position based on user input g_VCamera.FrameMove( fElapsedTime ); g_LCamera.FrameMove( fElapsedTime ); // Animate the plane, car and sphere meshes D3DXMATRIXA16 m; D3DXMatrixRotationY( &m, D3DX_PI * fElapsedTime / 4.0f ); D3DXMatrixMultiply( &g_Obj[1].m_mWorld, &g_Obj[1].m_mWorld, &m ); D3DXMatrixRotationY( &m, -D3DX_PI * fElapsedTime / 4.0f ); D3DXMatrixMultiply( &g_Obj[2].m_mWorld, &g_Obj[2].m_mWorld, &m ); D3DXVECTOR3 vR( 0.1f, 1.0f, -0.2f ); D3DXMatrixRotationAxis( &m, &vR, -D3DX_PI * fElapsedTime / 6.0f ); D3DXMatrixMultiply( &g_Obj[3].m_mWorld, &m, &g_Obj[3].m_mWorld ); } //-------------------------------------------------------------------------------------- // Renders the scene onto the current render target using the current // technique in the effect. //-------------------------------------------------------------------------------------- void RenderScene( IDirect3DDevice9* pd3dDevice, bool bRenderShadow, float fElapsedTime, const D3DXMATRIX* pmView, const D3DXMATRIX* pmProj ) { HRESULT hr; // Set the projection matrix V( g_pEffect->SetMatrix( "g_mProj", pmProj ) ); // Update the light parameters in the effect if( g_bFreeLight ) { // Freely moveable light. Get light parameter // from the light camera. D3DXVECTOR3 v = *g_LCamera.GetEyePt(); D3DXVECTOR4 v4; D3DXVec3Transform( &v4, &v, pmView ); V( g_pEffect->SetVector( "g_vLightPos", &v4 ) ); *( D3DXVECTOR3* )&v4 = *g_LCamera.GetWorldAhead(); v4.w = 0.0f; // Set w 0 so that the translation part doesn't come to play D3DXVec4Transform( &v4, &v4, pmView ); // Direction in view space D3DXVec3Normalize( ( D3DXVECTOR3* )&v4, ( D3DXVECTOR3* )&v4 ); V( g_pEffect->SetVector( "g_vLightDir", &v4 ) ); } else { // Light attached to car. Get the car's world position and direction. D3DXMATRIXA16 m = g_Obj[2].m_mWorld; D3DXVECTOR3 v( m._41, m._42, m._43 ); D3DXVECTOR4 vPos; D3DXVec3Transform( &vPos, &v, pmView ); D3DXVECTOR4 v4( 0.0f, 0.0f, -1.0f, 1.0f ); // In object space, car is facing -Z m._41 = m._42 = m._43 = 0.0f; // Remove the translation D3DXVec4Transform( &v4, &v4, &m ); // Obtain direction in world space v4.w = 0.0f; // Set w 0 so that the translation part doesn't come to play D3DXVec4Transform( &v4, &v4, pmView ); // Direction in view space D3DXVec3Normalize( ( D3DXVECTOR3* )&v4, ( D3DXVECTOR3* )&v4 ); V( g_pEffect->SetVector( "g_vLightDir", &v4 ) ); vPos += v4 * 4.0f; // Offset the center by 3 so that it's closer to the headlight. V( g_pEffect->SetVector( "g_vLightPos", &vPos ) ); } // Clear the render buffers V( pd3dDevice->Clear( 0L, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0x000000ff, 1.0f, 0L ) ); if( bRenderShadow ) V( g_pEffect->SetTechnique( "RenderShadow" ) ); // Begin the scene if( SUCCEEDED( pd3dDevice->BeginScene() ) ) { if( !bRenderShadow ) V( g_pEffect->SetTechnique( "RenderScene" ) ); // Render the objects for( int obj = 0; obj < NUM_OBJ; ++obj ) { D3DXMATRIXA16 mWorldView = g_Obj[obj].m_mWorld; D3DXMatrixMultiply( &mWorldView, &mWorldView, pmView ); V( g_pEffect->SetMatrix( "g_mWorldView", &mWorldView ) ); LPD3DXMESH pMesh = g_Obj[obj].m_Mesh.GetMesh(); UINT cPass; V( g_pEffect->Begin( &cPass, 0 ) ); for( UINT p = 0; p < cPass; ++p ) { V( g_pEffect->BeginPass( p ) ); for( DWORD i = 0; i < g_Obj[obj].m_Mesh.m_dwNumMaterials; ++i ) { D3DXVECTOR4 vDif( g_Obj[obj].m_Mesh.m_pMaterials[i].Diffuse.r, g_Obj[obj].m_Mesh.m_pMaterials[i].Diffuse.g, g_Obj[obj].m_Mesh.m_pMaterials[i].Diffuse.b, g_Obj[obj].m_Mesh.m_pMaterials[i].Diffuse.a ); V( g_pEffect->SetVector( "g_vMaterial", &vDif ) ); if( g_Obj[obj].m_Mesh.m_pTextures[i] ) V( g_pEffect->SetTexture( "g_txScene", g_Obj[obj].m_Mesh.m_pTextures[i] ) ) else V( g_pEffect->SetTexture( "g_txScene", g_pTexDef ) ) V( g_pEffect->CommitChanges() ); V( pMesh->DrawSubset( i ) ); } V( g_pEffect->EndPass() ); } V( g_pEffect->End() ); } // Render light if( !bRenderShadow ) V( g_pEffect->SetTechnique( "RenderLight" ) ); D3DXMATRIXA16 mWorldView = *g_LCamera.GetWorldMatrix(); D3DXMatrixMultiply( &mWorldView, &mWorldView, pmView ); V( g_pEffect->SetMatrix( "g_mWorldView", &mWorldView ) ); UINT cPass; LPD3DXMESH pMesh = g_LightMesh.GetMesh(); V( g_pEffect->Begin( &cPass, 0 ) ); for( UINT p = 0; p < cPass; ++p ) { V( g_pEffect->BeginPass( p ) ); for( DWORD i = 0; i < g_LightMesh.m_dwNumMaterials; ++i ) { D3DXVECTOR4 vDif( g_LightMesh.m_pMaterials[i].Diffuse.r, g_LightMesh.m_pMaterials[i].Diffuse.g, g_LightMesh.m_pMaterials[i].Diffuse.b, g_LightMesh.m_pMaterials[i].Diffuse.a ); V( g_pEffect->SetVector( "g_vMaterial", &vDif ) ); V( g_pEffect->SetTexture( "g_txScene", g_LightMesh.m_pTextures[i] ) ); V( g_pEffect->CommitChanges() ); V( pMesh->DrawSubset( i ) ); } V( g_pEffect->EndPass() ); } V( g_pEffect->End() ); if( !bRenderShadow ) // Render stats and help text RenderText(); // Render the UI elements if( !bRenderShadow ) g_HUD.OnRender( fElapsedTime ); V( pd3dDevice->EndScene() ); } } //-------------------------------------------------------------------------------------- // This callback function will be called at the end of every frame to perform all the // rendering calls for the scene, and it will also be called if the window needs to be // repainted. After this function has returned, DXUT will call // IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain //-------------------------------------------------------------------------------------- void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { // If the settings dialog is being shown, then // render it instead of rendering the app's scene if( g_SettingsDlg.IsActive() ) { g_SettingsDlg.OnRender( fElapsedTime ); return; } HRESULT hr; // // Compute the view matrix for the light // This changes depending on the light mode // (free movement or attached) // D3DXMATRIXA16 mLightView; if( g_bFreeLight ) mLightView = *g_LCamera.GetViewMatrix(); else { // Light attached to car. mLightView = g_Obj[2].m_mWorld; D3DXVECTOR3 vPos( mLightView._41, mLightView._42, mLightView._43 ); // Offset z by -2 so that it's closer to headlight D3DXVECTOR4 vDir = D3DXVECTOR4( 0.0f, 0.0f, -1.0f, 1.0f ); // In object space, car is facing -Z mLightView._41 = mLightView._42 = mLightView._43 = 0.0f; // Remove the translation D3DXVec4Transform( &vDir, &vDir, &mLightView ); // Obtain direction in world space vDir.w = 0.0f; // Set w 0 so that the translation part below doesn't come to play D3DXVec4Normalize( &vDir, &vDir ); vPos.x += vDir.x * 4.0f; // Offset the center by 4 so that it's closer to the headlight vPos.y += vDir.y * 4.0f; vPos.z += vDir.z * 4.0f; vDir.x += vPos.x; // vDir denotes the look-at point vDir.y += vPos.y; vDir.z += vPos.z; D3DXVECTOR3 vUp( 0.0f, 1.0f, 0.0f ); D3DXMatrixLookAtLH( &mLightView, &vPos, ( D3DXVECTOR3* )&vDir, &vUp ); } // // Render the shadow map // LPDIRECT3DSURFACE9 pOldRT = NULL; V( pd3dDevice->GetRenderTarget( 0, &pOldRT ) ); LPDIRECT3DSURFACE9 pShadowSurf; if( SUCCEEDED( g_pShadowMap->GetSurfaceLevel( 0, &pShadowSurf ) ) ) { pd3dDevice->SetRenderTarget( 0, pShadowSurf ); SAFE_RELEASE( pShadowSurf ); } LPDIRECT3DSURFACE9 pOldDS = NULL; if( SUCCEEDED( pd3dDevice->GetDepthStencilSurface( &pOldDS ) ) ) pd3dDevice->SetDepthStencilSurface( g_pDSShadow ); { CDXUTPerfEventGenerator g( DXUT_PERFEVENTCOLOR, L"Shadow Map" ); RenderScene( pd3dDevice, true, fElapsedTime, &mLightView, &g_mShadowProj ); } if( pOldDS ) { pd3dDevice->SetDepthStencilSurface( pOldDS ); pOldDS->Release(); } pd3dDevice->SetRenderTarget( 0, pOldRT ); SAFE_RELEASE( pOldRT ); // // Now that we have the shadow map, render the scene. // const D3DXMATRIX* pmView = g_bCameraPerspective ? g_VCamera.GetViewMatrix() : &mLightView; // Initialize required parameter V( g_pEffect->SetTexture( "g_txShadow", g_pShadowMap ) ); // Compute the matrix to transform from view space to // light projection space. This consists of // the inverse of view matrix * view matrix of light * light projection matrix D3DXMATRIXA16 mViewToLightProj; mViewToLightProj = *pmView; D3DXMatrixInverse( &mViewToLightProj, NULL, &mViewToLightProj ); D3DXMatrixMultiply( &mViewToLightProj, &mViewToLightProj, &mLightView ); D3DXMatrixMultiply( &mViewToLightProj, &mViewToLightProj, &g_mShadowProj ); V( g_pEffect->SetMatrix( "g_mViewToLightProj", &mViewToLightProj ) ); { CDXUTPerfEventGenerator g( DXUT_PERFEVENTCOLOR, L"Scene" ); RenderScene( pd3dDevice, false, fElapsedTime, pmView, g_VCamera.GetProjMatrix() ); } g_pEffect->SetTexture( "g_txShadow", NULL ); } //-------------------------------------------------------------------------------------- // Render the help and statistics text. This function uses the ID3DXFont interface for // efficient text rendering. //-------------------------------------------------------------------------------------- void RenderText() { // The helper object simply helps keep track of text position, and color // and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr ); // If NULL is passed in as the sprite object, then it will work however the // pFont->DrawText() will not be batched together. Batching calls will improves performance. CDXUTTextHelper txtHelper( g_pFont, g_pTextSprite, 15 ); // Output statistics txtHelper.Begin(); txtHelper.SetInsertionPos( 5, 5 ); txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) ); txtHelper.DrawTextLine( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) ); // Show FPS txtHelper.DrawTextLine( DXUTGetDeviceStats() ); txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f ) ); // Draw help if( g_bShowHelp ) { const D3DSURFACE_DESC* pd3dsdBackBuffer = DXUTGetD3D9BackBufferSurfaceDesc(); txtHelper.SetInsertionPos( 10, pd3dsdBackBuffer->Height - 15 * 10 ); txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 0.75f, 0.0f, 1.0f ) ); txtHelper.DrawTextLine( L"Controls:" ); txtHelper.SetInsertionPos( 15, pd3dsdBackBuffer->Height - 15 * 9 ); WCHAR text[512]; swprintf_s(text,L"Rotate camera\nMove camera\n" L"Rotate light\nMove light\n" L"Change light mode (Current: %s)\nChange view reference (Current: %s)\n" L"Hidehelp\nQuit", g_bFreeLight ? L"Free" : L"Car-attached", g_bCameraPerspective ? L"Camera" : L"Light" ); txtHelper.DrawTextLine(text); txtHelper.SetInsertionPos( 265, pd3dsdBackBuffer->Height - 15 * 9 ); txtHelper.DrawTextLine( L"Left drag mouse\nW,S,A,D,Q,E\n" L"Right drag mouse\nW,S,A,D,Q,E while holding right mouse\n" L"F\nV\nF1\nESC" ); } else { txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f ) ); txtHelper.DrawTextLine( L"Press F1 for help" ); } txtHelper.End(); } //-------------------------------------------------------------------------------------- // Before handling window messages, DXUT passes incoming windows // messages to the application through this callback function. If the application sets // *pbNoFurtherProcessing to TRUE, then DXUT will not process this message. //-------------------------------------------------------------------------------------- LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ) { // Always allow dialog resource manager calls to handle global messages // so GUI state is updated correctly *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; if( g_SettingsDlg.IsActive() ) { g_SettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam ); return 0; } *pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; // Pass all windows messages to camera and dialogs so they can respond to user input if( WM_KEYDOWN != uMsg || g_bRightMouseDown ) g_LCamera.HandleMessages( hWnd, uMsg, wParam, lParam ); if( WM_KEYDOWN != uMsg || !g_bRightMouseDown ) { if( g_bCameraPerspective ) g_VCamera.HandleMessages( hWnd, uMsg, wParam, lParam ); else g_LCamera.HandleMessages( hWnd, uMsg, wParam, lParam ); } return 0; } //-------------------------------------------------------------------------------------- // As a convenience, DXUT inspects the incoming windows messages for // keystroke messages and decodes the message parameters to pass relevant keyboard // messages to the application. The framework does not remove the underlying keystroke // messages, which are still passed to the application's MsgProc callback. //-------------------------------------------------------------------------------------- void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ) { } void CALLBACK MouseProc( bool bLeftButtonDown, bool bRightButtonDown, bool bMiddleButtonDown, bool bSideButton1Down, bool bSideButton2Down, int nMouseWheelDelta, int xPos, int yPos, void* pUserContext ) { g_bRightMouseDown = bRightButtonDown; } //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ) { switch( nControlID ) { case IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen(); break; case IDC_TOGGLEREF: DXUTToggleREF(); break; case IDC_CHANGEDEVICE: g_SettingsDlg.SetActive( !g_SettingsDlg.IsActive() ); break; case IDC_CHECKBOX: { CDXUTCheckBox* pCheck = ( CDXUTCheckBox* )pControl; g_bShowHelp = pCheck->GetChecked(); break; } case IDC_LIGHTPERSPECTIVE: { CDXUTCheckBox* pCheck = ( CDXUTCheckBox* )pControl; g_bCameraPerspective = !pCheck->GetChecked(); if( g_bCameraPerspective ) { g_VCamera.SetRotateButtons( true, false, false ); g_LCamera.SetRotateButtons( false, false, true ); } else { g_VCamera.SetRotateButtons( false, false, false ); g_LCamera.SetRotateButtons( true, false, true ); } break; } case IDC_ATTACHLIGHTTOCAR: { CDXUTCheckBox* pCheck = ( CDXUTCheckBox* )pControl; g_bFreeLight = !pCheck->GetChecked(); break; } } } //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // entered a lost state and before IDirect3DDevice9::Reset is called. Resources created // in the OnResetDevice callback should be released here, which generally includes all // D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for // information about lost devices. //-------------------------------------------------------------------------------------- void CALLBACK OnLostDevice( void* pUserContext ) { g_DialogResourceManager.OnD3D9LostDevice(); g_SettingsDlg.OnD3D9LostDevice(); if( g_pFont ) g_pFont->OnLostDevice(); if( g_pFontSmall ) g_pFontSmall->OnLostDevice(); if( g_pEffect ) g_pEffect->OnLostDevice(); SAFE_RELEASE( g_pTextSprite ); SAFE_RELEASE( g_pDSShadow ); SAFE_RELEASE( g_pShadowMap ); SAFE_RELEASE( g_pTexDef ); for( int i = 0; i < NUM_OBJ; ++i ) g_Obj[i].m_Mesh.InvalidateDeviceObjects(); g_LightMesh.InvalidateDeviceObjects(); } //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // been destroyed, which generally happens as a result of application termination or // windowed/full screen toggles. Resources created in the OnCreateDevice callback // should be released here, which generally includes all D3DPOOL_MANAGED resources. //-------------------------------------------------------------------------------------- void CALLBACK OnDestroyDevice( void* pUserContext ) { g_DialogResourceManager.OnD3D9DestroyDevice(); g_SettingsDlg.OnD3D9DestroyDevice(); SAFE_RELEASE( g_pEffect ); SAFE_RELEASE( g_pFont ); SAFE_RELEASE( g_pFontSmall ); SAFE_RELEASE( g_pVertDecl ); SAFE_RELEASE( g_pEffect ); for( int i = 0; i < NUM_OBJ; ++i ) g_Obj[i].m_Mesh.Destroy(); g_LightMesh.Destroy(); }
44.763686
128
0.573001
walbourn
f5da2bde0c2c8159bbee2205fc934ba5da95351d
18,998
cpp
C++
metric/n-api/crossfilter/ext/jsfeature_top_i64.cpp
Stepka/telegram_clustering_contest
52a012af2ce821410caa98cba840364710eb4256
[ "Apache-2.0" ]
2
2019-12-03T17:08:04.000Z
2021-08-25T05:06:29.000Z
metric/n-api/crossfilter/ext/jsfeature_top_i64.cpp
Stepka/telegram_clustering_contest
52a012af2ce821410caa98cba840364710eb4256
[ "Apache-2.0" ]
1
2021-09-02T02:25:51.000Z
2021-09-02T02:25:51.000Z
metric/n-api/crossfilter/ext/jsfeature_top_i64.cpp
Stepka/telegram_clustering_contest
52a012af2ce821410caa98cba840364710eb4256
[ "Apache-2.0" ]
null
null
null
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Copyright (c) 2019 Panda Team */ #include <node_api.h> #include "jsfeature_top.hpp" #include "utils.hpp" template napi_value top_<int64_t,int64_t,int64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<int64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,int64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<int64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,int32_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<int32_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,int32_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<int32_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,bool,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<bool>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,bool,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<bool>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,double,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<double>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,double,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<double>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,std::string,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<std::string>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,std::string,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<std::string>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,uint64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<uint64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,uint64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<uint64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,int64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<int64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,int64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<int64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,int32_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<int32_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,int32_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<int32_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,bool,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<bool>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,bool,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<bool>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,double,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<double>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,double,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<double>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,std::string,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<std::string>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,std::string,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<std::string>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,uint64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<uint64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,uint64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<uint64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,int64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<int64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,int64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<int64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,int32_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<int32_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,int32_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<int32_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,bool,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<bool>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,bool,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<bool>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,double,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<double>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,double,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<double>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,std::string,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<std::string>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,std::string,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<std::string>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,uint64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<uint64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,uint64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<uint64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,int64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<int64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,int64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<int64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,int32_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<int32_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,int32_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<int32_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,bool,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<bool>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,bool,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<bool>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,double,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<double>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,double,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<double>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,std::string,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<std::string>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,std::string,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<std::string>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,uint64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<uint64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,uint64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<uint64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,int64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<int64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,int64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<int64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,int32_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<int32_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,int32_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<int32_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,bool,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<bool>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,bool,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<bool>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,double,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<double>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,double,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<double>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,std::string,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<std::string>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,std::string,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<std::string>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,uint64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<uint64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,uint64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<uint64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,int64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<int64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,int64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<int64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,int32_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<int32_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,int32_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<int32_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,bool,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<bool>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,bool,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<bool>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,double,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<double>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,double,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<double>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,std::string,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<std::string>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,std::string,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<std::string>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,uint64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<uint64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,uint64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<uint64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj);
122.567742
140
0.793662
Stepka
f5da61636291a496c1598e7b1bfba63cad7ea3ce
1,970
cpp
C++
examples/Example5/Menu.cpp
hasaranga/RFC-Framework
9c1881d412db6f9f7670b910a0918a631208cfd1
[ "MIT" ]
9
2017-10-02T08:15:50.000Z
2021-08-09T21:29:46.000Z
examples/Example5/Menu.cpp
hasaranga/RFC-Framework
9c1881d412db6f9f7670b910a0918a631208cfd1
[ "MIT" ]
1
2021-09-18T07:38:53.000Z
2021-09-26T12:11:48.000Z
examples/Example5/Menu.cpp
hasaranga/RFC-Framework
9c1881d412db6f9f7670b910a0918a631208cfd1
[ "MIT" ]
8
2017-10-02T13:21:29.000Z
2021-07-30T09:35:31.000Z
#include "../../amalgamated/rfc_amalgamated.h" class MyWindow : public KFrame, public KMenuItemListener { protected: KMenuBar menuBar; KMenu mFile, mEdit, mHelp; KMenuItem miOpen, miExit, miCut, miCopy, miPaste, miAbout; public: MyWindow() { this->SetText(L"My Window"); this->Create(); miOpen.SetText(L"Open..."); miExit.SetText(L"Exit"); miCut.SetText(L"Cut"); miCopy.SetText(L"Copy"); miPaste.SetText(L"Paste"); miAbout.SetText(L"About..."); miOpen.SetListener(this); miExit.SetListener(this); miCut.SetListener(this); miCopy.SetListener(this); miPaste.SetListener(this); miAbout.SetListener(this); // add menu items into menu mFile.AddMenuItem(&miOpen); mFile.AddSeperator(); mFile.AddMenuItem(&miExit); mEdit.AddMenuItem(&miCut); mEdit.AddSeperator(); mEdit.AddMenuItem(&miCopy); mEdit.AddMenuItem(&miPaste); mHelp.AddMenuItem(&miAbout); // add menu into menubar menuBar.AddMenu(L"File", &mFile); menuBar.AddMenu(L"Edit", &mEdit); menuBar.AddMenu(L"Help", &mHelp); menuBar.AddToWindow(this); // add menubar into the window } void OnMenuItemPress(KMenuItem *menuItem) { if (menuItem == &miAbout) { ::MessageBoxW(this->GetHWND(), L"RFC Menu/Popup Example", L"About", MB_ICONINFORMATION); } else if (menuItem == &miExit) { this->OnClose(); // destroy window and quit from message loop! } } // macro to handle window messages... BEGIN_KMSG_HANDLER ON_KMSG(WM_RBUTTONUP, OnRClickWindow) // call OnRClickWindow method when WM_RBUTTONUP msg received END_KMSG_HANDLER(KFrame) // KFrame is our parent! LRESULT OnRClickWindow(WPARAM wParam, LPARAM lParam) { mEdit.PopUpMenu(this); // show mEdit menu as popup return 0; } }; class MyApplication : public KApplication { public: int Main(KString **argv, int argc) { MyWindow window; window.CenterScreen(); window.SetVisible(true); ::DoMessagePump(); return 0; } }; START_RFC_APPLICATION(MyApplication);
21.648352
100
0.706091
hasaranga
f5da84a4e5c245fc5410753b80f0f20e400a1a58
303
cpp
C++
Fun/fun_force_2_digits_cout.cpp
XuhuaHuang/EmbeddedProgramming
ce645e3993f105dbb9ed76d79f854c92e0578670
[ "MIT" ]
2
2020-09-16T20:16:27.000Z
2020-09-23T18:10:28.000Z
Fun/fun_force_2_digits_cout.cpp
XuhuaHuang/EmbeddedProgramming
ce645e3993f105dbb9ed76d79f854c92e0578670
[ "MIT" ]
null
null
null
Fun/fun_force_2_digits_cout.cpp
XuhuaHuang/EmbeddedProgramming
ce645e3993f105dbb9ed76d79f854c92e0578670
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> using namespace std; int main(void) { int numPrecision = 2; cout.precision(numPrecision); double a = 0; int b = 1; cout << "Value for \"double a\" is: " << fixed << a << endl; cout << "Value for \"int b\" is: " /* << fixed */ << b << endl; return 0; }
15.15
64
0.577558
XuhuaHuang
f5db9b1cd4ab5149de5c2222e5504e1d8fafbf02
2,726
cpp
C++
Day7/Day7.cpp
ATRI17Z/adventofcode18
5d743d7d277b416e3b5a287b0df598c4d5d67c6f
[ "MIT" ]
1
2018-12-05T18:32:50.000Z
2018-12-05T18:32:50.000Z
Day7/Day7.cpp
ATRI17Z/adventofcode18
5d743d7d277b416e3b5a287b0df598c4d5d67c6f
[ "MIT" ]
null
null
null
Day7/Day7.cpp
ATRI17Z/adventofcode18
5d743d7d277b416e3b5a287b0df598c4d5d67c6f
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <map> #include <deque> #include <algorithm> #include <climits> #include <chrono> #include "InstructionScheduler.h" std::string getInputAsString(std::string); std::vector<std::string> getInputPerLines(std::string); /******************************************************** * Day 7 Puzzle: * Using an OO approach to have objects for each task * and each worker. To to its morphological creation * the solution is not clean at all but at least it works * at is. Many things should be improved in multiple ways */ int main() { auto start = std::chrono::high_resolution_clock::now(); std::string str; std::ifstream input; std::vector<std::string> lines; InstructionScheduler scheduler = InstructionScheduler(); // Load input as Single String //str = getInputAsString("input_Day7_test.txt"); // Get Input as vector of lines lines = getInputPerLines("input_Day7.txt"); for (int i = 0; i < lines.size(); ++i) { std::string before, after; before = lines[i][5]; after = lines[i][36]; // Create Instructions scheduler.addInstruction(before, after); //scheduler.printInstructions(); } // Schedule Instructions PART ONE std::cout << std::endl << "PART ONE: " << std::endl; scheduler.getSchedule(); auto finishONE = std::chrono::high_resolution_clock::now(); // Schedule Instructions PART TWO std::cout << std::endl << "PART TWO: " << std::endl; //scheduler.getTimedSchedule(2); // for testData scheduler.getTimedSchedule(5); auto finishTWO = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsedONE = finishONE - start; std::chrono::duration<double> elapsedTWO = finishTWO - finishONE; std::cout << "Elapsed time: P1: " << elapsedONE.count() * 1000 << "ms P2: " << elapsedTWO.count() * 1000 << "ms" << std::endl; return 0; } /****************************** * INPUT HELPER FUNCTIONS * ******************************/ std::string getInputAsString(std::string fileName) { std::string str; // Open File std::ifstream in(fileName); if (!in.is_open() || !in.good()) { std::cout << "Failed to open input" << std::endl; return 0; } // Create String str.assign((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); in.close(); return str; } std::vector<std::string> getInputPerLines(std::string fileName) { std::vector<std::string> lines; std::string line; // Open File std::ifstream in(fileName); if (!in.is_open() || !in.good()) { std::cout << "Failed to open input" << std::endl; } // Create Vector of lines while (getline(in, line)) { lines.push_back(line); } in.close(); return lines; }
26.211538
127
0.65077
ATRI17Z
f5dd62ffee22fc4d427e125832b5a72e4e6777dc
2,215
cpp
C++
test/test_stable_sort_large.cpp
pruthvistony/rocThrust
c986b97395d4a6cbacc7a4600d11bdf389de639a
[ "Apache-2.0" ]
null
null
null
test/test_stable_sort_large.cpp
pruthvistony/rocThrust
c986b97395d4a6cbacc7a4600d11bdf389de639a
[ "Apache-2.0" ]
null
null
null
test/test_stable_sort_large.cpp
pruthvistony/rocThrust
c986b97395d4a6cbacc7a4600d11bdf389de639a
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2008-2013 NVIDIA Corporation * Modifications Copyright© 2019 Advanced Micro Devices, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thrust/functional.h> #include <thrust/sort.h> #include "test_header.hpp" template <typename T, unsigned int N> void _TestStableSortWithLargeKeys(void) { size_t n = (128 * 1024) / sizeof(FixedVector<T, N>); thrust::host_vector<FixedVector<T, N>> h_keys(n); for(size_t i = 0; i < n; i++) h_keys[i] = FixedVector<T, N>(rand()); thrust::device_vector<FixedVector<T, N>> d_keys = h_keys; thrust::stable_sort(h_keys.begin(), h_keys.end()); thrust::stable_sort(d_keys.begin(), d_keys.end()); ASSERT_EQ_QUIET(h_keys, d_keys); } TEST(StableSortLargeTests, TestStableSortWithLargeKeys) { _TestStableSortWithLargeKeys<int, 1>(); _TestStableSortWithLargeKeys<int, 2>(); _TestStableSortWithLargeKeys<int, 4>(); _TestStableSortWithLargeKeys<int, 8>(); // STREAM HPC investigate and fix `error: local memory limit exceeded` // (make block size smaller for large keys and values in rocPRIM) #if THRUST_DEVICE_SYSTEM != THRUST_DEVICE_SYSTEM_HIP _TestStableSortWithLargeKeys<int, 16>(); _TestStableSortWithLargeKeys<int, 32>(); _TestStableSortWithLargeKeys<int, 64>(); _TestStableSortWithLargeKeys<int, 128>(); _TestStableSortWithLargeKeys<int, 256>(); _TestStableSortWithLargeKeys<int, 512>(); _TestStableSortWithLargeKeys<int, 1024>(); // XXX these take too long to compile // _TestStableSortWithLargeKeys<int, 2048>(); // _TestStableSortWithLargeKeys<int, 4096>(); // _TestStableSortWithLargeKeys<int, 8192>(); #endif }
34.609375
83
0.722799
pruthvistony
f5def028edf9cc51d0028f1345017031b1c31b25
947
cpp
C++
#Preparation/Placement-Overview/PrepInsta/max-contiguos-array.cpp
sounishnath003/CPP-for-beginner
d4755ab4ae098d63c9a0666d8eb4d152106d4a20
[ "MIT" ]
4
2020-05-14T04:41:04.000Z
2021-06-13T06:42:03.000Z
#Preparation/Placement-Overview/PrepInsta/max-contiguos-array.cpp
sounishnath003/CPP-for-beginner
d4755ab4ae098d63c9a0666d8eb4d152106d4a20
[ "MIT" ]
null
null
null
#Preparation/Placement-Overview/PrepInsta/max-contiguos-array.cpp
sounishnath003/CPP-for-beginner
d4755ab4ae098d63c9a0666d8eb4d152106d4a20
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define fo(i, n) for(int i = 1; i < n; i++) using namespace std ; #define deb(x) {cout << #x << " " << x << endl ;} int max_contiguos_subarray(vector<int> &nums) { stack<int> cached ; cached.push(nums[0]) ; int n = nums.size() ; int cnt = INT_MIN, t = 0 ; if(is_sorted(nums.begin(), nums.end(), less<int>{})) return nums.size() ; if(is_sorted(nums.begin(), nums.end(), greater<int>{})) return 0 ; fo(i, n) { if (cached.top() > nums[i] ) { t = cached.size() ; while(!cached.empty()) { cached.pop() ; } cached.push(nums[i]) ; } if (cached.top() < nums[i]) { cached.push(nums[i]) ; int l = cached.size() ; cnt = max(cnt, l) ; } } return max(cnt, t); } int main(int argc, char const *argv[]){ ios::sync_with_stdio(0) ; vector<int> nums{60, 45, 48, 52}; cout << go(nums) ; return 0; }
24.921053
77
0.510032
sounishnath003
f5df0e72004df1e45f4c36c00742299324900e40
1,209
hpp
C++
include/nodamushi/svd/value/void_value.hpp
nodamushi/nsvd-reader
cf3a840aaac78d5791df1cf045596ec20dc03257
[ "CC0-1.0" ]
null
null
null
include/nodamushi/svd/value/void_value.hpp
nodamushi/nsvd-reader
cf3a840aaac78d5791df1cf045596ec20dc03257
[ "CC0-1.0" ]
null
null
null
include/nodamushi/svd/value/void_value.hpp
nodamushi/nsvd-reader
cf3a840aaac78d5791df1cf045596ec20dc03257
[ "CC0-1.0" ]
null
null
null
/*! @brief value&lt;void&gt; @file nodamushi/svd/value/void_value.hpp */ /* * These codes are licensed under CC0. * http://creativecommons.org/publicdomain/zero/1.0/ */ #ifndef NODAMUSHI_SVD_VALUE_VOID_VALUE_HPP #define NODAMUSHI_SVD_VALUE_VOID_VALUE_HPP # include "nodamushi/svd/value.hpp" namespace nodamushi{ namespace svd{ // void template<bool attribute,bool r,char... name>struct value<void,attribute,r,name...> { using type = void; static constexpr bool REQUIRED=false; static constexpr bool ATTRIBUTE=attribute; constexpr bool empty()const noexcept{return true;} constexpr operator bool()const noexcept{return false;} constexpr bool check_require()const noexcept{return true;} constexpr bool is_required()const noexcept{return false;} constexpr bool is_attribute()const noexcept{return attribute;} int operator*()const noexcept{return 0;} int get()const noexcept{return 0;} NODAMUSHI_CONSTEXPR_STRING get_name()const noexcept { # if __cplusplus >= 201703 return get_const_string<name...>(); # else const char arr[] = {name...,'\0'}; return std::string(arr); # endif } }; }}// end namespace nodamushi::svd #endif // NODAMUSHI_SVD_VALUE_VOID_VALUE_HPP
26.866667
82
0.74359
nodamushi
f5e001516d43c3b57cd4f33d19473a3eef7f3e79
1,938
inl
C++
ace/OS_NS_sys_select.inl
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
ace/OS_NS_sys_select.inl
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
ace/OS_NS_sys_select.inl
binary42/OCI
08191bfe4899f535ff99637d019734ed044f479d
[ "MIT" ]
null
null
null
// -*- C++ -*- // // $Id: OS_NS_sys_select.inl 2179 2013-05-28 22:16:51Z mesnierp $ #include "ace/OS_NS_errno.h" #include "ace/OS_NS_macros.h" #include "ace/Time_Value.h" ACE_BEGIN_VERSIONED_NAMESPACE_DECL // It would be really cool to add another version of select that would // function like the one we're defending against below! ACE_INLINE int ACE_OS::select (int width, fd_set *rfds, fd_set *wfds, fd_set *efds, const ACE_Time_Value *timeout) { ACE_OS_TRACE ("ACE_OS::select"); #if defined (ACE_HAS_NONCONST_SELECT_TIMEVAL) // We must defend against non-conformity! timeval copy; timeval *timep = 0; if (timeout != 0) { copy = *timeout; timep = &copy; } else timep = 0; #else const timeval *timep = (timeout == 0 ? (const timeval *)0 : *timeout); #endif /* ACE_HAS_NONCONST_SELECT_TIMEVAL */ #if defined (ACE_LACKS_SELECT) ACE_UNUSED_ARG (width); ACE_UNUSED_ARG (rfds); ACE_UNUSED_ARG (wfds); ACE_UNUSED_ARG (efds); ACE_UNUSED_ARG (timeout); ACE_NOTSUP_RETURN (-1); #else ACE_SOCKCALL_RETURN (::select (width, rfds, wfds, efds, timep), int, -1); #endif } ACE_INLINE int ACE_OS::select (int width, fd_set *rfds, fd_set *wfds, fd_set *efds, const ACE_Time_Value &timeout) { ACE_OS_TRACE ("ACE_OS::select"); #if defined (ACE_HAS_NONCONST_SELECT_TIMEVAL) # define ___ACE_TIMEOUT &copy timeval copy = timeout; #else # define ___ACE_TIMEOUT timep const timeval *timep = timeout; #endif /* ACE_HAS_NONCONST_SELECT_TIMEVAL */ #if defined (ACE_LACKS_SELECT) ACE_UNUSED_ARG (width); ACE_UNUSED_ARG (rfds); ACE_UNUSED_ARG (wfds); ACE_UNUSED_ARG (efds); ACE_UNUSED_ARG (timeout); ACE_NOTSUP_RETURN (-1); #else ACE_SOCKCALL_RETURN (::select (width, rfds, wfds, efds, ___ACE_TIMEOUT), int, -1); #endif #undef ___ACE_TIMEOUT } ACE_END_VERSIONED_NAMESPACE_DECL
25.84
74
0.680599
binary42
f5e066f0d870954ca333c029b0f98e32e4e026c1
2,713
cpp
C++
src/libharp-mpi/harp_mpi_metadata.cpp
tskisner/HARP
e21435511c3dc95ce1318c852002a95ca59634b1
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/libharp-mpi/harp_mpi_metadata.cpp
tskisner/HARP
e21435511c3dc95ce1318c852002a95ca59634b1
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/libharp-mpi/harp_mpi_metadata.cpp
tskisner/HARP
e21435511c3dc95ce1318c852002a95ca59634b1
[ "BSD-3-Clause-LBNL" ]
null
null
null
/* High Performance Astrophysical Reconstruction and Processing (HARP) (c) 2014-2015, The Regents of the University of California, through Lawrence Berkeley National Laboratory. See top level LICENSE file for details. */ #include <harp_mpi_internal.hpp> using namespace std; using namespace harp; mpi_spec_p harp::mpi_load_spec ( boost::mpi::communicator const & comm, boost::property_tree::ptree const & tree ) { boost::property_tree::ptree props; string type = tree.get < string > ( "type" ); props = tree.get_child ( "props" ); return mpi_spec_p ( new mpi_spec ( comm, type, props ) ); } mpi_image_p harp::mpi_load_image ( boost::mpi::communicator const & comm, boost::property_tree::ptree const & tree ) { boost::property_tree::ptree props; string type = tree.get < string > ( "type" ); props = tree.get_child ( "props" ); return mpi_image_p ( new mpi_image ( comm, type, props ) ); } mpi_psf_p harp::mpi_load_psf ( boost::mpi::communicator const & comm, boost::property_tree::ptree const & tree ) { boost::property_tree::ptree props; string type = tree.get < string > ( "type" ); props = tree.get_child ( "props" ); return mpi_psf_p ( new mpi_psf ( comm, type, props ) ); } mpi_targets_p harp::mpi_load_targets ( boost::mpi::communicator const & comm, boost::property_tree::ptree const & tree ) { boost::property_tree::ptree props; string type = tree.get < string > ( "type" ); props = tree.get_child ( "props" ); return mpi_targets_p ( new mpi_targets ( comm, type, props ) ); } harp::mpi_group::mpi_group ( boost::mpi::communicator const & comm, boost::property_tree::ptree const & tree ) { load ( comm, tree ); } void harp::mpi_group::load ( boost::mpi::communicator const & comm, boost::property_tree::ptree const & tree ) { handle_.reset(); boost::property_tree::ptree psf_tree = tree.get_child ( "psf" ); handle_ = mpi_load_psf ( comm, psf_tree ); imgs_.clear(); boost::property_tree::ptree::const_iterator v = tree.begin(); while ( v != tree.end() ) { if ( v->first == "image" ) { imgs_.push_back ( mpi_load_image ( comm, v->second ) ); } ++v; } return; } std::list < mpi_group_p > harp::mpi_load_groups ( boost::mpi::communicator const & comm, std::string const & path ) { // Read JSON into a property tree boost::property_tree::ptree tree; boost::property_tree::json_parser::read_json ( path, tree ); std::list < mpi_group_p > ret; boost::property_tree::ptree::const_iterator v = tree.begin(); while ( v != tree.end() ) { if ( v->first == "group" ) { ret.push_back ( mpi_group_p ( new mpi_group ( comm, v->second ) ) ); } ++v; } return ret; }
25.35514
122
0.664947
tskisner
f5e1f88a2f50eba65f4395e9fc1dd9ae552292da
9,825
cpp
C++
src/webots/wren/WbSupportPolygonRepresentation.cpp
victorhu3/webots
60d173850f0b4714c500db004e69f2df8cfb9e8a
[ "Apache-2.0" ]
1
2020-11-11T09:31:28.000Z
2020-11-11T09:31:28.000Z
src/webots/wren/WbSupportPolygonRepresentation.cpp
victorhu3/webots
60d173850f0b4714c500db004e69f2df8cfb9e8a
[ "Apache-2.0" ]
2
2020-05-18T12:49:14.000Z
2020-12-01T15:13:43.000Z
src/webots/wren/WbSupportPolygonRepresentation.cpp
victorhu3/webots
60d173850f0b4714c500db004e69f2df8cfb9e8a
[ "Apache-2.0" ]
1
2022-02-25T12:34:18.000Z
2022-02-25T12:34:18.000Z
// Copyright 1996-2020 Cyberbotics 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 "WbSupportPolygonRepresentation.hpp" #include "WbMathsUtilities.hpp" #include "WbPolygon.hpp" #include "WbRotation.hpp" #include "WbWrenRenderingContext.hpp" #include "WbWrenShaders.hpp" #include <wren/config.h> #include <wren/dynamic_mesh.h> #include <wren/material.h> #include <wren/node.h> #include <wren/renderable.h> #include <wren/scene.h> #include <wren/static_mesh.h> #include <wren/transform.h> // Colors used by support polygon representation in RGBA format // note: alpha = 1.0f -> full transparency static const float STABLE_POLYGON_COLOR[4] = {0.6f, 0.9f, 0.6f, 0.5f}; static const float STABLE_POLYGON_OUTLINE_COLOR[4] = {0.2f, 1.0f, 0.2f, 0.5f}; static const float STABLE_CENTER_OF_MASS_COLOR[4] = {0.5f, 1.0f, 0.5f, 0.0f}; static const float UNSTABLE_POLYGON_COLOR[4] = {0.9f, 0.6f, 0.6f, 0.5f}; static const float UNSTABLE_POLYGON_OUTLINE_COLOR[4] = {1.0f, 0.2f, 0.1f, 0.5f}; static const float UNSTABLE_CENTER_OF_MASS_COLOR[4] = {1.0f, 0.2f, 0.2f, 0.0f}; WbSupportPolygonRepresentation::WbSupportPolygonRepresentation() { mTransform = wr_transform_new(); mCenterOfMassTransform = wr_transform_new(); mPolygonMesh = wr_dynamic_mesh_new(false, false, false); mPolygonOutlineMesh = wr_dynamic_mesh_new(false, false, false); const float vertices[12] = {-1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f}; mCenterOfMassMesh = wr_static_mesh_line_set_new(4, vertices, NULL); mPolygonMaterial = wr_phong_material_new(); wr_material_set_default_program(mPolygonMaterial, WbWrenShaders::simpleShader()); wr_phong_material_set_color(mPolygonMaterial, STABLE_POLYGON_COLOR); wr_phong_material_set_transparency(mPolygonMaterial, STABLE_POLYGON_COLOR[3]); mPolygonOutlineMaterial = wr_phong_material_new(); wr_material_set_default_program(mPolygonOutlineMaterial, WbWrenShaders::lineSetShader()); wr_phong_material_set_color(mPolygonOutlineMaterial, STABLE_POLYGON_OUTLINE_COLOR); wr_phong_material_set_transparency(mPolygonOutlineMaterial, STABLE_POLYGON_OUTLINE_COLOR[3]); mCenterOfMassMaterial = wr_phong_material_new(); wr_material_set_default_program(mCenterOfMassMaterial, WbWrenShaders::lineSetShader()); wr_phong_material_set_color(mCenterOfMassMaterial, STABLE_CENTER_OF_MASS_COLOR); wr_phong_material_set_transparency(mCenterOfMassMaterial, STABLE_CENTER_OF_MASS_COLOR[3]); mPolygonRenderable = wr_renderable_new(); wr_renderable_set_mesh(mPolygonRenderable, WR_MESH(mPolygonMesh)); wr_renderable_set_drawing_order(mPolygonRenderable, WR_RENDERABLE_DRAWING_ORDER_AFTER_1); wr_renderable_set_material(mPolygonRenderable, mPolygonMaterial, NULL); wr_renderable_set_visibility_flags(mPolygonRenderable, WbWrenRenderingContext::VF_SELECTED_OUTLINE); wr_renderable_set_face_culling(mPolygonRenderable, false); wr_renderable_set_drawing_mode(mPolygonRenderable, WR_RENDERABLE_DRAWING_MODE_TRIANGLE_FAN); mPolygonOutlineRenderable = wr_renderable_new(); wr_renderable_set_mesh(mPolygonOutlineRenderable, WR_MESH(mPolygonOutlineMesh)); wr_renderable_set_drawing_order(mPolygonOutlineRenderable, WR_RENDERABLE_DRAWING_ORDER_AFTER_1); wr_renderable_set_drawing_mode(mPolygonOutlineRenderable, WR_RENDERABLE_DRAWING_MODE_LINES); wr_renderable_set_material(mPolygonOutlineRenderable, mPolygonOutlineMaterial, NULL); wr_renderable_set_visibility_flags(mPolygonRenderable, WbWrenRenderingContext::VF_SELECTED_OUTLINE); mCenterOfMassRenderable = wr_renderable_new(); wr_renderable_set_mesh(mCenterOfMassRenderable, WR_MESH(mCenterOfMassMesh)); wr_renderable_set_drawing_order(mCenterOfMassRenderable, WR_RENDERABLE_DRAWING_ORDER_AFTER_1); wr_renderable_set_drawing_mode(mCenterOfMassRenderable, WR_RENDERABLE_DRAWING_MODE_LINES); wr_renderable_set_material(mCenterOfMassRenderable, mCenterOfMassMaterial, NULL); wr_renderable_set_visibility_flags(mCenterOfMassRenderable, WbWrenRenderingContext::VF_SELECTED_OUTLINE); const float s = 0.1f * wr_config_get_line_scale(); const float scale[3] = {s, s, s}; wr_transform_set_scale(mCenterOfMassTransform, scale); wr_transform_attach_child(mTransform, WR_NODE(mPolygonRenderable)); wr_transform_attach_child(mTransform, WR_NODE(mPolygonOutlineRenderable)); wr_transform_attach_child(mCenterOfMassTransform, WR_NODE(mCenterOfMassRenderable)); WrTransform *root = wr_scene_get_root(wr_scene_get_instance()); wr_transform_attach_child(mTransform, WR_NODE(mCenterOfMassTransform)); wr_transform_attach_child(root, WR_NODE(mTransform)); wr_node_set_visible(WR_NODE(mTransform), false); } WbSupportPolygonRepresentation::~WbSupportPolygonRepresentation() { cleanup(); } void WbSupportPolygonRepresentation::show(bool visible) { wr_node_set_visible(WR_NODE(mTransform), visible); } static void addVertex(WrDynamicMesh *mesh, int index, float x, float y, float z) { const float vertex[3] = {x, y, z}; wr_dynamic_mesh_add_vertex(mesh, vertex); wr_dynamic_mesh_add_index(mesh, index); } void WbSupportPolygonRepresentation::draw(const WbPolygon &p, float y, const WbVector3 &globalCenterOfMass, const WbVector3 *worldBasis) { const int size = p.actualSize(); wr_dynamic_mesh_clear(mPolygonMesh); wr_dynamic_mesh_clear(mPolygonOutlineMesh); // No contact points if (size == 0) { show(false); return; } show(true); const double globalComX = globalCenterOfMass.dot(worldBasis[X]); const double globalComZ = globalCenterOfMass.dot(worldBasis[Z]); const bool stable = p.contains(globalComX, globalComZ); // Set materials if (stable) { wr_phong_material_set_color(mPolygonMaterial, STABLE_POLYGON_COLOR); wr_phong_material_set_color(mPolygonOutlineMaterial, STABLE_POLYGON_OUTLINE_COLOR); wr_phong_material_set_color(mCenterOfMassMaterial, STABLE_CENTER_OF_MASS_COLOR); wr_phong_material_set_transparency(mPolygonMaterial, STABLE_POLYGON_COLOR[3]); wr_phong_material_set_transparency(mPolygonOutlineMaterial, STABLE_POLYGON_OUTLINE_COLOR[3]); wr_phong_material_set_transparency(mCenterOfMassMaterial, STABLE_CENTER_OF_MASS_COLOR[3]); } else { wr_phong_material_set_color(mPolygonMaterial, UNSTABLE_POLYGON_COLOR); wr_phong_material_set_color(mPolygonOutlineMaterial, UNSTABLE_POLYGON_OUTLINE_COLOR); wr_phong_material_set_color(mCenterOfMassMaterial, UNSTABLE_CENTER_OF_MASS_COLOR); wr_phong_material_set_transparency(mPolygonMaterial, UNSTABLE_POLYGON_COLOR[3]); wr_phong_material_set_transparency(mPolygonOutlineMaterial, UNSTABLE_POLYGON_OUTLINE_COLOR[3]); wr_phong_material_set_transparency(mCenterOfMassMaterial, UNSTABLE_CENTER_OF_MASS_COLOR[3]); } // Set orientations WbRotation rotation(worldBasis[X], worldBasis[Y], worldBasis[Z]); rotation.normalize(); float orientation[4]; rotation.toFloatArray(orientation); wr_transform_set_orientation(mTransform, orientation); // Set the projected center of mass position const float position[3] = {static_cast<float>(globalComX), y, static_cast<float>(globalComZ)}; wr_transform_set_position(mCenterOfMassTransform, position); const float l = wr_config_get_line_scale() * WbWrenRenderingContext::SOLID_LINE_SCALE_FACTOR; // A single contact point if (size == 1) { addVertex(mPolygonOutlineMesh, 0, p[0].x() - l, y, p[0].y()); addVertex(mPolygonOutlineMesh, 1, p[0].x() + l, y, p[0].y()); addVertex(mPolygonOutlineMesh, 2, p[0].x(), y, p[0].y() - l); addVertex(mPolygonOutlineMesh, 3, p[0].x(), y, p[0].y() + l); addVertex(mPolygonOutlineMesh, 4, p[0].x(), y - l, p[0].y()); addVertex(mPolygonOutlineMesh, 5, p[0].x(), y + l, p[0].y()); return; } // Draws the outline int vertexCounter = 0; const int sizeMinusOne = size - 1; for (int i = 0; i < sizeMinusOne; ++i) { addVertex(mPolygonOutlineMesh, vertexCounter++, p[i].x(), y, p[i].y()); addVertex(mPolygonOutlineMesh, vertexCounter++, p[i + 1].x(), y, p[i + 1].y()); } if (size > 2) { // Closes the edge loop addVertex(mPolygonOutlineMesh, vertexCounter++, p[sizeMinusOne].x(), y, p[sizeMinusOne].y()); addVertex(mPolygonOutlineMesh, vertexCounter++, p[0].x(), y, p[0].y()); } else return; // Draws the filled polygon addVertex(mPolygonMesh, 0, p[0].x(), y, p[0].y()); addVertex(mPolygonMesh, 1, p[1].x(), y, p[1].y()); addVertex(mPolygonMesh, 2, p[2].x(), y, p[2].y()); // Draw one side (face culling disabled) for (int i = 3; i <= sizeMinusOne; i++) addVertex(mPolygonMesh, i, p[i].x(), y, p[i].y()); } void WbSupportPolygonRepresentation::setScale(const float *scale) { wr_transform_set_scale(mCenterOfMassTransform, scale); } void WbSupportPolygonRepresentation::cleanup() { wr_node_delete(WR_NODE(mTransform)); wr_node_delete(WR_NODE(mCenterOfMassTransform)); wr_node_delete(WR_NODE(mPolygonRenderable)); wr_node_delete(WR_NODE(mPolygonOutlineRenderable)); wr_node_delete(WR_NODE(mCenterOfMassRenderable)); wr_dynamic_mesh_delete(mPolygonMesh); wr_dynamic_mesh_delete(mPolygonOutlineMesh); wr_static_mesh_delete(mCenterOfMassMesh); wr_material_delete(mPolygonMaterial); wr_material_delete(mPolygonOutlineMaterial); wr_material_delete(mCenterOfMassMaterial); }
44.659091
107
0.780356
victorhu3
f5e434116a671ac9e1f4f04cafb86df2af834171
2,892
cc
C++
cms/src/model/CreateMyGroupAlertBatchResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
3
2020-01-06T08:23:14.000Z
2022-01-22T04:41:35.000Z
cms/src/model/CreateMyGroupAlertBatchResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
null
null
null
cms/src/model/CreateMyGroupAlertBatchResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/cms/model/CreateMyGroupAlertBatchResult.h> #include <json/json.h> using namespace AlibabaCloud::Cms; using namespace AlibabaCloud::Cms::Model; CreateMyGroupAlertBatchResult::CreateMyGroupAlertBatchResult() : ServiceResult() {} CreateMyGroupAlertBatchResult::CreateMyGroupAlertBatchResult(const std::string &payload) : ServiceResult() { parse(payload); } CreateMyGroupAlertBatchResult::~CreateMyGroupAlertBatchResult() {} void CreateMyGroupAlertBatchResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allResources = value["Resources"]["AlertResult"]; for (auto value : allResources) { AlertResult resourcesObject; if(!value["AlertName"].isNull()) resourcesObject.alertName = value["AlertName"].asString(); if(!value["DisplayName"].isNull()) resourcesObject.displayName = value["DisplayName"].asString(); if(!value["MetricNamespace"].isNull()) resourcesObject.metricNamespace = value["MetricNamespace"].asString(); if(!value["MetricName"].isNull()) resourcesObject.metricName = value["MetricName"].asString(); if(!value["Message"].isNull()) resourcesObject.message = value["Message"].asString(); if(!value["Code"].isNull()) resourcesObject.code = std::stoi(value["Code"].asString()); if(!value["Success"].isNull()) resourcesObject.success = value["Success"].asString() == "true"; if(!value["GroupId"].isNull()) resourcesObject.groupId = std::stol(value["GroupId"].asString()); resources_.push_back(resourcesObject); } if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["ErrorCode"].isNull()) errorCode_ = std::stoi(value["ErrorCode"].asString()); if(!value["ErrorMessage"].isNull()) errorMessage_ = value["ErrorMessage"].asString(); } std::vector<CreateMyGroupAlertBatchResult::AlertResult> CreateMyGroupAlertBatchResult::getResources()const { return resources_; } int CreateMyGroupAlertBatchResult::getErrorCode()const { return errorCode_; } std::string CreateMyGroupAlertBatchResult::getErrorMessage()const { return errorMessage_; } bool CreateMyGroupAlertBatchResult::getSuccess()const { return success_; }
30.765957
106
0.743084
sdk-team
f5e62da46a8c8e64f061e76cbf2b946a01371188
3,721
cpp
C++
aws-cpp-sdk-lambda/source/model/UpdateEventSourceMappingRequest.cpp
blinemedical/aws-sdk-cpp
c7c814b2d6862b4cb48f3fb3ac083a9e419674e8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-lambda/source/model/UpdateEventSourceMappingRequest.cpp
blinemedical/aws-sdk-cpp
c7c814b2d6862b4cb48f3fb3ac083a9e419674e8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-lambda/source/model/UpdateEventSourceMappingRequest.cpp
blinemedical/aws-sdk-cpp
c7c814b2d6862b4cb48f3fb3ac083a9e419674e8
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/lambda/model/UpdateEventSourceMappingRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Lambda::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateEventSourceMappingRequest::UpdateEventSourceMappingRequest() : m_uUIDHasBeenSet(false), m_functionNameHasBeenSet(false), m_enabled(false), m_enabledHasBeenSet(false), m_batchSize(0), m_batchSizeHasBeenSet(false), m_maximumBatchingWindowInSeconds(0), m_maximumBatchingWindowInSecondsHasBeenSet(false), m_destinationConfigHasBeenSet(false), m_maximumRecordAgeInSeconds(0), m_maximumRecordAgeInSecondsHasBeenSet(false), m_bisectBatchOnFunctionError(false), m_bisectBatchOnFunctionErrorHasBeenSet(false), m_maximumRetryAttempts(0), m_maximumRetryAttemptsHasBeenSet(false), m_parallelizationFactor(0), m_parallelizationFactorHasBeenSet(false), m_sourceAccessConfigurationsHasBeenSet(false), m_tumblingWindowInSeconds(0), m_tumblingWindowInSecondsHasBeenSet(false), m_functionResponseTypesHasBeenSet(false) { } Aws::String UpdateEventSourceMappingRequest::SerializePayload() const { JsonValue payload; if(m_functionNameHasBeenSet) { payload.WithString("FunctionName", m_functionName); } if(m_enabledHasBeenSet) { payload.WithBool("Enabled", m_enabled); } if(m_batchSizeHasBeenSet) { payload.WithInteger("BatchSize", m_batchSize); } if(m_maximumBatchingWindowInSecondsHasBeenSet) { payload.WithInteger("MaximumBatchingWindowInSeconds", m_maximumBatchingWindowInSeconds); } if(m_destinationConfigHasBeenSet) { payload.WithObject("DestinationConfig", m_destinationConfig.Jsonize()); } if(m_maximumRecordAgeInSecondsHasBeenSet) { payload.WithInteger("MaximumRecordAgeInSeconds", m_maximumRecordAgeInSeconds); } if(m_bisectBatchOnFunctionErrorHasBeenSet) { payload.WithBool("BisectBatchOnFunctionError", m_bisectBatchOnFunctionError); } if(m_maximumRetryAttemptsHasBeenSet) { payload.WithInteger("MaximumRetryAttempts", m_maximumRetryAttempts); } if(m_parallelizationFactorHasBeenSet) { payload.WithInteger("ParallelizationFactor", m_parallelizationFactor); } if(m_sourceAccessConfigurationsHasBeenSet) { Array<JsonValue> sourceAccessConfigurationsJsonList(m_sourceAccessConfigurations.size()); for(unsigned sourceAccessConfigurationsIndex = 0; sourceAccessConfigurationsIndex < sourceAccessConfigurationsJsonList.GetLength(); ++sourceAccessConfigurationsIndex) { sourceAccessConfigurationsJsonList[sourceAccessConfigurationsIndex].AsObject(m_sourceAccessConfigurations[sourceAccessConfigurationsIndex].Jsonize()); } payload.WithArray("SourceAccessConfigurations", std::move(sourceAccessConfigurationsJsonList)); } if(m_tumblingWindowInSecondsHasBeenSet) { payload.WithInteger("TumblingWindowInSeconds", m_tumblingWindowInSeconds); } if(m_functionResponseTypesHasBeenSet) { Array<JsonValue> functionResponseTypesJsonList(m_functionResponseTypes.size()); for(unsigned functionResponseTypesIndex = 0; functionResponseTypesIndex < functionResponseTypesJsonList.GetLength(); ++functionResponseTypesIndex) { functionResponseTypesJsonList[functionResponseTypesIndex].AsString(FunctionResponseTypeMapper::GetNameForFunctionResponseType(m_functionResponseTypes[functionResponseTypesIndex])); } payload.WithArray("FunctionResponseTypes", std::move(functionResponseTypesJsonList)); } return payload.View().WriteReadable(); }
28.189394
185
0.795485
blinemedical
f5e67ddfea3794f7837ab81c9d08149ef277c584
130,429
cpp
C++
diffy/src/utils/llvmUtils.cpp
divyeshunadkat/diffy-artifact
a3405c828b18696bdabf2cee994599a2d7573d0c
[ "MIT" ]
1
2021-06-09T06:34:06.000Z
2021-06-09T06:34:06.000Z
diffy/src/utils/llvmUtils.cpp
divyeshunadkat/diffy-artifact
a3405c828b18696bdabf2cee994599a2d7573d0c
[ "MIT" ]
null
null
null
diffy/src/utils/llvmUtils.cpp
divyeshunadkat/diffy-artifact
a3405c828b18696bdabf2cee994599a2d7573d0c
[ "MIT" ]
null
null
null
#include <limits> #include <random> #include "llvmUtils.h" #include "utils/graphUtils.h" #include "daikon-inst/comments.h" //todo: move to utils #include <boost/algorithm/string.hpp> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wstrict-aliasing" // pragam'ed to aviod warnings due to llvm included files #include "llvm/IR/DIBuilder.h" #include "llvm/IR/LegacyPassManager.h" // #include "llvm/IR/ConstantFold.h" // later versions of llvm will need this #include "llvm/Analysis/ConstantFolding.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Transforms/Utils/LoopSimplify.h" //clang related code #include <clang/CodeGen/CodeGenAction.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Frontend/CompilerInvocation.h> #include <clang/Basic/DiagnosticOptions.h> #include <clang/Basic/TargetInfo.h> #pragma GCC diagnostic pop #define CLANG_VERSION "6.0" void c2bc( const std::string& fileName, const std::string& outName ) { // make a system call std::ostringstream cmd; cmd << "clang-" << CLANG_VERSION << " -emit-llvm -fno-omit-frame-pointer -Xclang -disable-O0-optnone -gdwarf-2 " << fileName << " -o " << outName << " -c"; // std::cout << cmd.str() << "\n"; if( system( cmd.str().c_str() ) != 0 ) exit(1); } // best guess of location class estimate_loc_pass : public llvm::BasicBlockPass { src_loc ref; src_loc ref_end; src_loc low_est; src_loc up_est; llvm::Instruction* I_low = NULL; llvm::Instruction* I_up = NULL; public: static char ID; llvm::Instruction* get_I_low() { return I_low; } llvm::Instruction* get_I_up() { return I_up; } src_loc get_low_estimate() { return low_est; } src_loc get_up_estimate() { return up_est; } public: estimate_loc_pass( src_loc& loc_, src_loc& ref_end_) : llvm::BasicBlockPass(ID), ref(loc_),ref_end(ref_end_), low_est( 0,0, loc_.file), up_est( UINT_MAX, UINT_MAX, loc_.file) { }; ~estimate_loc_pass() {}; virtual bool runOnBasicBlock( llvm::BasicBlock &bb ) { for( llvm::Instruction& I : bb.getInstList() ) { const llvm::DebugLoc d = I.getDebugLoc(); if( d ) { unsigned l = d.getLine(); unsigned c = d.getCol(); std::string f =llvm::cast<llvm::DIScope>(d.getScope())->getFilename(); src_loc curr(l,c,f); if( f != curr.file ) continue; if( COMPARE_OBJ2(curr, low_est, line, col) || COMPARE_OBJ2(up_est, curr, line, col) ) continue; if( ref_end == curr || COMPARE_OBJ2(ref_end, curr, line, col) ) { up_est = curr; I_up = &I; } if( ref == curr || COMPARE_OBJ2(curr, ref, line, col) ) { low_est = curr; I_low = &I; } // { // std::cerr << "\n"; // dump_triple( low_est ); // dump_triple( ref ); // dump_triple( up_est ); // dump_triple( curr ); // std::cerr << "\n"; // } // auto curr = std::make_tuple(l,c,f); // if( f != std::get<2>(curr) ) continue; // if( COMPARE_TUPLE2(curr, low_est, 0, 1) || // COMPARE_TUPLE2(up_est, curr, 0, 1) ) // continue; // if( ref_end == curr || // COMPARE_TUPLE2(ref_end, curr, 0, 1) ) { // up_est = curr; // I_up = &I; // } // if( ref == curr || // COMPARE_TUPLE2(curr, ref, 0, 1) ) { // low_est = curr; // I_low = &I; // } } } return false; } virtual void getAnalysisUsage(llvm::AnalysisUsage &au) const { au.setPreservesAll(); } virtual llvm::StringRef getPassName() const { return "estimate location pass: finds estimate of a source location!!"; } }; char estimate_loc_pass::ID = 0; llvm::Instruction* estimate_comment_location( std::unique_ptr<llvm::Module>& module, src_loc start, src_loc end) { llvm::legacy::PassManager passMan; auto estimate_pass = new estimate_loc_pass( start, end ); passMan.add( estimate_pass ); passMan.run( *module.get() ); // { // estimate_pass->get_I_low()->dump(); // estimate_pass->get_I_up()->dump(); // dump_triple( estimate_pass->get_low_estimate() ); // dump_triple( estimate_pass->get_up_estimate() ); // } return estimate_pass->get_I_up(); // return estimate_pass->get_low_estimate(); } void estimate_comment_location(std::unique_ptr<llvm::Module>& module, std::vector< comment >& comments, std::map< const bb*, std::pair< std::vector<std::string>, std::vector<std::string> > >& bb_comment_map ) { // collect all the comments that are written at the same program point std::map< llvm::Instruction*, std::vector<std::string> > comment_map; std::vector< std::vector< llvm::Instruction* > > Is; for( auto comment : comments ) { auto start = comment.start; auto end = comment.end; auto comment_text = comment.text; llvm::Instruction* I = estimate_comment_location( module, start, end ); if( comment_map.find(I) != comment_map.end() ) { auto& c_vec = comment_map.at(I); c_vec.push_back(comment_text); }else{ comment_map[I].push_back(comment_text); bool done = false; for( auto& B_Is : Is ) { if( B_Is[0]->getParent() == I->getParent() ) { unsigned i = 0; for( auto& Io : B_Is[0]->getParent()->getInstList() ) { if( i == B_Is.size() || &Io == I ) break; if( &Io == B_Is[i] ) i++; } B_Is.insert( B_Is.begin() + i, I); done = true; } } if( !done ) Is.push_back({I}); } } for( auto& B_Is : Is ) { //intially all instructions in B_Is have same block for( llvm::Instruction* I : B_Is ) { llvm::BasicBlock* bb = I->getParent(); auto& pair = bb_comment_map[bb]; llvm::Instruction* first = &(*(bb->getInstList().begin())); if( bb->getTerminator() == I ) { pair.second = comment_map[I]; }else if( first == I ) { pair.first = comment_map[I]; }else{ pair.second = comment_map[I]; bb->splitBasicBlock(I); } } } } // // clang source to llvm soruce location // warning: the code is without several guards (check CGDebugInfo.cpp in clang) src_loc getLocFromClangSource( const clang::SourceLocation& loc, const clang::SourceManager& sm) { unsigned line = sm.getPresumedLoc(loc).getLine(); unsigned col = sm.getPresumedLoc(loc).getColumn(); std::string file = sm.getFilename(loc); return src_loc(line,col,file); } //this function is a copy from CompilerInstance::ExecuteActuib bool ExecuteAction( clang::CompilerInstance& CI, clang::FrontendAction &Act, std::vector< comment >& comments_found) { // FIXME: Take this as an argument, once all the APIs we used have moved to // taking it as an input instead of hard-coding llvm::errs. llvm::raw_ostream &OS = llvm::errs(); // Create the target instance. CI.setTarget(clang::TargetInfo::CreateTargetInfo(CI.getDiagnostics(), CI.getInvocation().TargetOpts)); if (!CI.hasTarget()) return false; CI.getTarget().adjust(CI.getLangOpts()); CI.getTarget().adjustTargetOptions(CI.getCodeGenOpts(), CI.getTargetOpts()); for (const clang::FrontendInputFile &FIF : CI.getFrontendOpts().Inputs) { // Reset the ID tables if we are reusing the SourceManager and parsing // regular files. if (CI.hasSourceManager() && !Act.isModelParsingAction()) CI.getSourceManager().clearIDTables(); if (Act.BeginSourceFile( CI, FIF)) { Act.Execute(); clang::ASTContext& ast_ctx = CI.getASTContext(); clang::SourceManager& sm = CI.getSourceManager(); clang::RawCommentList& comment_list = ast_ctx.getRawCommentList(); for( clang::RawComment* cmnt : comment_list.getComments() ) { // OS << comment->getRawText( sm ) << "\n"; //todo: check prefix of the comment std::string multi_cmt = cmnt->getRawText( sm ); std::vector<std::string> cmts; boost::split(cmts, multi_cmt, [](char c){return c == '\n';}); for( auto cmt : cmts ) { comment c; boost::algorithm::trim(cmt); if(COMMENT_PREFIX == cmt.substr(0, COMMENT_PREFIX_LEN) ) { c.text = cmt.substr(COMMENT_PREFIX_LEN, cmt.size()-COMMENT_PREFIX_LEN ); c.start = getLocFromClangSource(cmnt->getSourceRange().getBegin(), sm); c.end = getLocFromClangSource( cmnt->getSourceRange().getEnd(), sm); comments_found.push_back(c); } } } Act.EndSourceFile(); } } // Notify the diagnostic client that all files were processed. CI.getDiagnostics().getClient()->finish(); if ( CI.getDiagnosticOpts().ShowCarets) { // We can have multiple diagnostics sharing one diagnostic client. // Get the total number of warnings/errors from the client. unsigned NumWarnings = CI.getDiagnostics().getClient()->getNumWarnings(); unsigned NumErrors = CI.getDiagnostics().getClient()->getNumErrors(); if (NumWarnings) OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s"); if (NumWarnings && NumErrors) OS << " and "; if (NumErrors) OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s"); } return !CI.getDiagnostics().getClient()->getNumErrors(); } //Direct translation via API clang std::unique_ptr<llvm::Module> c2ir( std::string filename, llvm::LLVMContext& llvm_ctx, std::vector< comment >& comments ) { // return nullptr; // look in clang/include/clang/Driver/CC1Options.td // and clang/lib/Frontend/CompilerInvocation.cpp // to find right param names std::vector<const char *> args; args.push_back( "-emit-llvm" ); args.push_back( "-disable-llvm-passes" ); args.push_back( "-debug-info-kind=standalone" ); args.push_back( "-dwarf-version=2" ); args.push_back( "-dwarf-column-info" ); args.push_back( "-mdisable-fp-elim"); args.push_back( "-femit-all-decls" ); args.push_back( "-O1" ); args.push_back( "-disable-O0-optnone" ); args.push_back( filename.c_str() ); clang::CompilerInstance Clang; Clang.createDiagnostics(); std::shared_ptr<clang::CompilerInvocation> CI(new clang::CompilerInvocation()); clang::CompilerInvocation::CreateFromArgs( *CI.get(), &args[0], &args[0] + args.size(), Clang.getDiagnostics()); Clang.setInvocation(CI); clang::CodeGenAction *Act = new clang::EmitLLVMOnlyAction(&llvm_ctx); if (!ExecuteAction(Clang, *Act, comments)) // if (!Clang.ExecuteAction(*Act)) return nullptr; std::unique_ptr<llvm::Module> module = Act->takeModule(); return std::move(module); return nullptr; } std::unique_ptr<llvm::Module> c2ir( std::string filename, llvm::LLVMContext& llvm_ctx ) { std::vector< comment > comments_found; return move( c2ir( filename, llvm_ctx, comments_found ) ); } void setLLVMConfigViaCommandLineOptions( std::string strs ) { std::string n = "test"; const char* array[2]; array[0] = n.c_str(); array[1] = strs.c_str(); llvm::cl::ParseCommandLineOptions( 2, array ); } void printSegmentInfo(segment& s) { std::cout << "\nPrinting segment info for segment " << &s; std::cout << "\nPrinting entry blocks\n"; printBlockInfo(s.entryCutPoints); std::cout << "\nPrinting exit blocks\n"; printBlockInfo(s.exitCutPoints); std::cout << "\nPrinting body blocks\n"; printBlockInfo(s.bodyBlocks); } void printBlockInfo(std::vector<llvm::BasicBlock*>& blockList) { for(const llvm::BasicBlock* b : blockList) { b->printAsOperand(llvm::errs(), false); std::cout << "\n"; } } std::string getVarName(const llvm::DbgValueInst* dVal ) { // auto var = dVal->getValue(); auto md = dVal->getVariable(); llvm::DIVariable* diMd = llvm::dyn_cast<llvm::DIVariable>(md); return (std::string)( diMd->getName() ); } std::string getVarName(const llvm::DbgDeclareInst* dDecl ) { // auto var = dDecl->getAddress(); auto md = dDecl->getVariable(); llvm::DIVariable* diMd = llvm::dyn_cast<llvm::DIVariable>(md); auto str = (std::string)( diMd->getName() ); return str; } void buildNameMap( options& o, llvm::Function& f, name_map& localNameMap) { std::map<const llvm::Value*, std::set<std::string> > l_name_map_extra; // std::map<std::string, llvm::Value*>& nameValueMap) { // std::cout << "Inside buildNameMap\n"; // localNameMap.clear(); // nameValueMap.clear(); for( llvm::inst_iterator iter(f),end(f,true); iter != end; ++iter ) { llvm::Instruction* I = &*iter; llvm::Value* var = NULL; llvm::MDNode* md = NULL; std::string str; if( llvm::DbgDeclareInst* dDecl = llvm::dyn_cast<llvm::DbgDeclareInst>(I) ) { var = dDecl->getAddress(); md = dDecl->getVariable(); llvm::DIVariable* diMd = llvm::dyn_cast<llvm::DIVariable>(md); str = (std::string)( diMd->getName() ); // std::cout << "Got the name:" << str << "\n"; } else if( llvm::DbgValueInst* dVal = llvm::dyn_cast<llvm::DbgValueInst>(I)) { var = dVal->getValue(); md = dVal->getVariable(); llvm::DIVariable* diMd = llvm::dyn_cast<llvm::DIVariable>(md); str = (std::string)( diMd->getName() ); if( llvm::isa<llvm::ConstantInt>(var) ) { var = dVal; } // std::cout << "Got the name:" << str << "\n"; } if( var ) { // if var is non-null add the name to the map if( localNameMap.find(var) != localNameMap.end() ) { if( str != localNameMap.at( var ) ) l_name_map_extra[var].insert( str ); } localNameMap[var] = str; // nameValueMap[str] = var; //to look at the scope field // check if there has been a declaration with same name with different // line number // auto it = declarationLocationMap.find( str ); // if( it == declarationLocationMap.end() ) { // declarationLocationMap[str] = lineNum; // localNameMap[var] = str; // nameValueMap[str] = var; // }else if( it->second == lineNum ) { // localNameMap[var] = str; // nameValueMap[str] = var; // }else{ // localNameMap[var] = str + "_at_"+ std::to_string( lineNum ); // nameValueMap[str] = var; // } } } //Extend names to phiNodes // if phinode names are misssing, for( auto& b: f.getBasicBlockList() ) { for( llvm::BasicBlock::iterator I = b.begin(); llvm::isa<llvm::PHINode>(I); ++I) { llvm::PHINode *phi = llvm::cast<llvm::PHINode>(I); unsigned num = phi->getNumIncomingValues(); std::set<std::string> names; for ( unsigned i = 0 ; i < num ; i++ ) { llvm::Value *v = phi->getIncomingValue(i); if(llvm::Instruction *inI = llvm::dyn_cast<llvm::Instruction>(v)) { if( localNameMap.find(inI) != localNameMap.end() ) { auto back_name = localNameMap.at(inI); names.insert( back_name ); if( l_name_map_extra.find(inI) != l_name_map_extra.end() ) set_insert( l_name_map_extra.at(inI), names ); } } } bool found = ( localNameMap.find(phi) != localNameMap.end() ); if( names.size() == 1) { std::string name = *names.begin(); if( found && localNameMap.at(phi) != name ) { if( o.verbosity > 5 ) { tiler_warning("build name map::","multiple names found for a value!!"); } } localNameMap[phi] = name; }else if( found && l_name_map_extra.find( phi ) == l_name_map_extra.end() ) { // the name is already there std::string name = localNameMap.at(phi); if( names.find( name ) == names.end() && o.verbosity > 5 ) { tiler_warning("build name map::","multiple mismatching names found for a value!!"); } }else if( names.size() > 1 || l_name_map_extra.find( phi ) != l_name_map_extra.end() ) { if( o.verbosity > 5 ) { for( auto name : names ) { std::cout << name << "\n"; } if(found) std::cout << localNameMap.at(phi) << "\n" ; if( l_name_map_extra.find(phi) != l_name_map_extra.end() ) for( auto name : l_name_map_extra.at( phi ) ) { std::cout << name << "\n"; } tiler_warning( "build name map::","multiple names found!!"); } } // auto back_name = localNameMap.at(inI); // if( found && name != localNameMap.at(inI) ) // tiler_error("build name map::","phi node has multiple names!!"); // name = localNameMap.at(inI); // found = true; // if( !found ) { // // If this function fails, investigate to find the (correct) name // //tiler_error("build name map::","name of a phi node not found!!"); // } } } } bool isRemInBop(const llvm::BinaryOperator* bop) { unsigned op = bop->getOpcode(); switch( op ) { case llvm::Instruction::URem : return true; case llvm::Instruction::SRem: return true; case llvm::Instruction::FRem: return true; default: return false; } return false; } bool isRemInStore(const llvm::StoreInst* store) { auto val = store->getOperand(0); if( auto cast = llvm::dyn_cast<llvm::CastInst>(val) ) { val = cast->getOperand(0); } else {} if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(val) ) { unsigned op = bop->getOpcode(); switch( op ) { case llvm::Instruction::URem : return true; case llvm::Instruction::SRem: return true; case llvm::Instruction::FRem: return true; default: return false; } } else { return false; } } bool isAddInStore(const llvm::StoreInst* store) { auto val = store->getOperand(0); if( auto cast = llvm::dyn_cast<llvm::CastInst>(val) ) { val = cast->getOperand(0); } else {} if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(val) ) { unsigned op = bop->getOpcode(); switch( op ) { case llvm::Instruction::Add : return true; case llvm::Instruction::FAdd: return true; default: return false; } } else { return false; } } bool isSubInStore(const llvm::StoreInst* store) { auto val = store->getOperand(0); if( auto cast = llvm::dyn_cast<llvm::CastInst>(val) ) { val = cast->getOperand(0); } else {} if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(val) ) { unsigned op = bop->getOpcode(); switch( op ) { case llvm::Instruction::Sub : return true; case llvm::Instruction::FSub: return true; default: return false; } } else { return false; } } bool isMulInStore(const llvm::StoreInst* store) { auto val = store->getOperand(0); if( auto cast = llvm::dyn_cast<llvm::CastInst>(val) ) { val = cast->getOperand(0); } else {} if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(val) ) { unsigned op = bop->getOpcode(); switch( op ) { case llvm::Instruction::Mul : return true; case llvm::Instruction::FMul: return true; default: return false; } } else { return false; } } bool isDivInStore(const llvm::StoreInst* store) { auto val = store->getOperand(0); if( auto cast = llvm::dyn_cast<llvm::CastInst>(val) ) { val = cast->getOperand(0); } else {} if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(val) ) { unsigned op = bop->getOpcode(); switch( op ) { case llvm::Instruction::SDiv: return true; case llvm::Instruction::UDiv: return true; case llvm::Instruction::FDiv: return true; default: return false; } } else { return false; } } bool isValueInSubExpr(const llvm::Value* val, const llvm::Value* expr) { if(val == expr) return true; if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr) ) { bool res = isValueInSubExpr(val, bop->getOperand(0)); if(res) return true; res = isValueInSubExpr(val, bop->getOperand(1)); return res; } else if( llvm::isa<llvm::CallInst>(expr) ) { return false; // tiler_error( "llvmutils::", "Call instruction as sub-expression not supported"); } else if( auto store = llvm::dyn_cast<llvm::StoreInst>(expr) ) { return isValueInSubExpr(val, store->getOperand(0)); } else if( llvm::isa<llvm::GetElementPtrInst>(expr) ) { return false; // tiler_error( "llvmutils::", "GEP as sub-expression not supported"); } else if(auto load = llvm::dyn_cast<llvm::LoadInst>(expr) ) { return isValueInSubExpr(val, load->getOperand(0)); // return false; } else if( auto cast = llvm::dyn_cast<llvm::CastInst>(expr) ) { return isValueInSubExpr(val, cast->getOperand(0)); } else if( llvm::isa<llvm::AllocaInst>(expr) ) { return false; // tiler_error( "llvmutils::", "Alloca as sub-expression not supported"); // return isValueInExpr(val, alloca->getArraySize()); } else { return false; } } bool onlyValueInSubExpr(const llvm::Value* val, const llvm::Value* expr) { if( auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr) ) { bool res = true; if( ! llvm::isa<llvm::ConstantInt>(bop->getOperand(0)) ) res = onlyValueInSubExpr(val, bop->getOperand(0)); if( ! llvm::isa<llvm::ConstantInt>(bop->getOperand(1)) ) if(res) res = res && onlyValueInSubExpr(val, bop->getOperand(1)); return res; } else if( auto cast = llvm::dyn_cast<llvm::CastInst>(expr) ) { return onlyValueInSubExpr(val, cast->getOperand(0)); } else if( auto load = llvm::dyn_cast<llvm::LoadInst>(expr) ) { return onlyValueInSubExpr(val, load->getOperand(0)); /* } else if( llvm::isa<llvm::StoreInst>(expr) ) { return false; } else if( llvm::isa<llvm::GetElementPtrInst>(expr) ) { return false; } else if( llvm::isa<llvm::CallInst>(expr) ) { return false; } else if( llvm::isa<llvm::AllocaInst>(expr) ) { return false; */ } else { if(val == expr) return true; else return false; } } bool onlyValuesInSubExpr(std::list<const llvm::Value*>& val_l, const llvm::Value* expr) { if( auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr) ) { bool res = true; if( ! llvm::isa<llvm::ConstantInt>(bop->getOperand(0)) ) res = onlyValuesInSubExpr(val_l, bop->getOperand(0)); if( ! llvm::isa<llvm::ConstantInt>(bop->getOperand(1)) ) if(res) res = res && onlyValuesInSubExpr(val_l, bop->getOperand(1)); return res; } else if( auto cast = llvm::dyn_cast<llvm::CastInst>(expr) ) { return onlyValuesInSubExpr(val_l, cast->getOperand(0)); } else if( auto load = llvm::dyn_cast<llvm::LoadInst>(expr) ) { return onlyValuesInSubExpr(val_l, load->getOperand(0)); } else { for(auto v : val_l) if(v == expr) return true; return false; } } bool isLoadOrStoreInSubExpr(const llvm::Value* expr) { if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr) ) { bool res = isLoadOrStoreInSubExpr(bop->getOperand(0)); if(res) return true; return isLoadOrStoreInSubExpr(bop->getOperand(1)); } else if(auto call = llvm::dyn_cast<llvm::CallInst>(expr) ) { llvm::Function* fp = call->getCalledFunction(); if( llvm::dyn_cast<llvm::IntrinsicInst>(call) ) { return false; } else if( fp != NULL && fp->getName().startswith("__VERIFIER") ) { return false; } else { tiler_error( "llvmutils::", "Call instruction as sub-expression not supported"); } } else if( llvm::dyn_cast<llvm::StoreInst>(expr) ) { return true; } else if( llvm::dyn_cast<llvm::GetElementPtrInst>(expr) ) { return true; } else if( llvm::dyn_cast<llvm::LoadInst>(expr) ) { return true; } else if( auto cast = llvm::dyn_cast<llvm::CastInst>(expr) ) { return isLoadOrStoreInSubExpr(cast->getOperand(0)); } else if( llvm::dyn_cast<llvm::AllocaInst>(expr) ) { tiler_error( "llvmutils::", "Alloca as sub-expression not supported"); } else { return false; } } void getLoadsInSubExpr(llvm::Value* expr, std::list<llvm::Value*>& loads) { if( auto load = llvm::dyn_cast<llvm::LoadInst>(expr) ) { loads.push_back(load); } else if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr) ) { getLoadsInSubExpr(bop->getOperand(0), loads); getLoadsInSubExpr(bop->getOperand(1), loads); } else if( llvm::dyn_cast<llvm::CallInst>(expr) ) { tiler_error( "llvmutils::", "Call instruction as sub-expression not supported"); } else if( auto store = llvm::dyn_cast<llvm::StoreInst>(expr) ) { getLoadsInSubExpr(store->getOperand(0), loads); } else if( auto cast = llvm::dyn_cast<llvm::CastInst>(expr) ) { getLoadsInSubExpr(cast->getOperand(0), loads); } else if( llvm::dyn_cast<llvm::AllocaInst>(expr) ) { tiler_error( "llvmutils::", "Alloca as sub-expression not supported"); } else {} } bool isInHeader(llvm::Instruction *I, llvm::Loop *L) { // std::cout << "In isInHeader\n"; auto h = L->getHeader(); auto b = I->getParent(); if(h==b) { // std::cout << "In Header\n"; return true; } else { // std::cout << "Not in Header\n"; return false; } } bool isOutOfLoop(llvm::Instruction *I, llvm::Loop *L) { // std::cout << "In isOutOfLoop\n"; if(L==NULL) { return true; } auto bb = I->getParent(); for( auto b: L->getBlocks() ) { if(b == bb) { // std::cout << "Is in the loop\n"; return false; } } // std::cout << "Is out of the loop\n"; return true; } bool isMyLatch(llvm::BasicBlock *b, llvm::Loop *L) { // std::cout << "In isInLatch\n"; if(L==NULL) { return false; } auto h = L->getLoopLatch(); return h == b; } bool isInLatch(llvm::Instruction *I, llvm::Loop *L) { if(L==NULL) { return false; } auto b = I->getParent(); // return isMyLatch( b, L ); //todo: auto h = L->getLoopLatch(); if(h==b) { return true; } else { return false; } } unsigned valueIdxFromLatch( llvm::PHINode* phi, llvm::Loop * loop) { assert( phi->getNumIncomingValues() == 2 ); unsigned i =0; if( isMyLatch( phi->getIncomingBlock(0), loop) ) { i = 0; }else if( isMyLatch( phi->getIncomingBlock(1), loop) ) { i = 1; }else{ tiler_error( "llvmutils::", "header latch did not match!!"); } return i; } bool isLoopRotated( llvm::Loop * loop ) { auto t = loop->getLoopLatch()->getTerminator(); if( auto br = llvm::dyn_cast<llvm::BranchInst>(t) ) { return br->isConditional(); } tiler_error( "llvmutils::", "loops always end with conditionals!!"); return false; } // Check whether the loop can be analyzed by us. bool isSupported(llvm::Loop *L) { // Make sure the loop is in simplified form if (!L->isLoopSimplifyForm()) return false; // Only support loops that contain a single exit if (!L->getExitingBlock() || !L->getUniqueExitBlock()) return false; return true; } // Check if the given basic block is in sub loop of the current loop bool isInSubLoop(llvm::BasicBlock *BB, llvm::Loop *CurLoop, llvm::LoopInfo *LI) { if(!CurLoop->contains(BB)) { std::cout << "Check is valid only if the basic block is in the current loop or its sub loop"; } return LI->getLoopFor(BB) != CurLoop; } bool hasPhiNode(llvm::Value* v) { assert(v); if (llvm::isa<llvm::PHINode>(v)) { return true; } else if(llvm::isa<llvm::BinaryOperator>(v)) { llvm::BinaryOperator* bop = llvm::dyn_cast<llvm::BinaryOperator>(v); auto op0 = bop->getOperand( 0 ); auto op1 = bop->getOperand( 1 ); if(hasPhiNode(op0)) { return true; } if(hasPhiNode(op1)) { return true; } return false; } else { return false; } } llvm::Value* getPhiNode(llvm::Value* expr) { assert(expr); if (llvm::isa<llvm::PHINode>(expr)) { return expr; } else if(llvm::isa<const llvm::GlobalVariable>(expr)) { return NULL; // Global Variables are not phi and they don't have phi } else if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr)){ auto phi0 = getPhiNode(bop->getOperand( 0 )); if(phi0 != NULL) { return phi0; } auto phi1 = getPhiNode(bop->getOperand( 1 )); if(phi1 != NULL) { return phi1; } return NULL; } else { return NULL; } } // Return true of the block has atleast one successor bool hasSuccessor(const llvm::BasicBlock* b) { if(llvm::succ_begin(b) == llvm::succ_end(b)) { return false; } else { return true; } } // Return the first Basic Block in the Body of the Current Loop llvm::BasicBlock* getFirstBodyOfLoop(llvm::Loop *CurLoop){ llvm::BasicBlock* head = CurLoop->getHeader(); const llvm::TerminatorInst *TInst = head->getTerminator(); // const llvm::Instruction *TInst = head->getTerminator(); // LLVM 8 assert(TInst->isTerminator()); // unsigned nbSucc = TInst->getNumSuccessors(); bool found = false; unsigned i = 0; llvm::BasicBlock *next = TInst->getSuccessor(i); while(!found) { if(next!=CurLoop->getExitBlock()) found=true; else{ i++; next = TInst->getSuccessor(i); } } std::cout << "First body block in the current loop is :" << next->getName().str() << "\n"; return next; } std::string getFuncNameForDaikon(llvm::Loop *L) { std::string fName = "__TILER_Loop_"; auto loc = L->getStartLoc(); fName = fName + std::to_string(loc->getLine()); return fName; } llvm::Function *rand_prototype(llvm::Module *mod, llvm::LLVMContext& glbContext) { llvm::FunctionType *rand_type = llvm::FunctionType::get( llvm::Type::getInt32Ty(mod->getContext()), false); /* llvm::TypeBuilder<int(void), false>::get(glbContext); // TypeBuilder deprecated from 8.0.1 */ auto attr_list = llvm::AttributeList().addAttribute(mod->getContext(), 1U, llvm::Attribute::NoAlias); llvm::Constant *c = mod->getOrInsertFunction( "rand", rand_type, attr_list ); llvm::Function *func = NULL; if(llvm::isa<llvm::CastInst>(c)) { func = llvm::cast<llvm::Function>( c->getOperand(0)); } else { func = llvm::cast<llvm::Function>( c ); } return func; } llvm::Function *printf_prototype(llvm::Module *mod, llvm::LLVMContext& glbContext) { llvm::FunctionType *printf_type = llvm::FunctionType::get( llvm::Type::getInt32Ty(mod->getContext()), llvm::PointerType::get(llvm::Type::getInt8Ty(mod->getContext()), false), true); /* llvm::TypeBuilder<int(char *, ...), false>::get(glbContext); // TypeBuilder deprecated from 8.0.1 */ auto attr_list = llvm::AttributeList().addAttribute(mod->getContext(), 1U, llvm::Attribute::NoAlias); llvm::Function *func = llvm::cast<llvm::Function>(mod->getOrInsertFunction( "printf", printf_type, attr_list )); return func; } llvm::Function *assume_prototype(llvm::Module *mod, llvm::LLVMContext& glbContext) { llvm::FunctionType *assume_type = NULL; llvm::FunctionType::get( llvm::Type::getVoidTy(mod->getContext()), llvm::Type::getInt32Ty(mod->getContext()), false); // llvm::TypeBuilder<void(int), false>::get(glbContext); auto attr_list = llvm::AttributeList().addAttribute(mod->getContext(), 1U, llvm::Attribute::NoAlias); llvm::Function *func = llvm::cast<llvm::Function>(mod->getOrInsertFunction( "__llbmc_assume", assume_type, attr_list )); return func; } llvm::Function *assert_prototype(llvm::Module *mod, llvm::LLVMContext& glbContext) { llvm::FunctionType *assert_type = NULL; llvm::FunctionType::get( llvm::Type::getVoidTy(mod->getContext()), llvm::Type::getInt32Ty(mod->getContext()), false); // llvm::TypeBuilder<void(int), false>::get(glbContext); auto attr_list = llvm::AttributeList().addAttribute(mod->getContext(), 1U, llvm::Attribute::NoAlias); llvm::Function *func = llvm::cast<llvm::Function>(mod->getOrInsertFunction( "__llbmc_assert", assert_type, attr_list)); return func; } llvm::Constant* geti8StrVal(llvm::Module& M, char const* str, llvm::Twine const& name, llvm::LLVMContext& ctx) { // llvm::LLVMContext& ctx = llvm::getGlobalContext(); llvm::Constant* strConstant = llvm::ConstantDataArray::getString(ctx, str); llvm::GlobalVariable* GVStr = new llvm::GlobalVariable(M, strConstant->getType(), true, llvm::GlobalValue::InternalLinkage, strConstant, name); llvm::Constant* zero = llvm::Constant::getNullValue(llvm::IntegerType::getInt32Ty(ctx)); llvm::Constant* indices[] = {zero, zero}; llvm::Constant* strVal = llvm::ConstantExpr::getGetElementPtr(strConstant->getType(), GVStr, indices, true); return strVal; } void assertSingleNesting(llvm::Loop *L) { if(!L->empty()) { L = *L->begin(); auto it = L->begin(); it++; assert(it == L->end()); assert(L->empty()); } } void assertNonNesting(llvm::Loop *L) { assert(L->empty()); } bool isIncrOp(llvm::Value *V) { bool isAdd=true; if( llvm::Instruction *I = llvm::dyn_cast<llvm::Instruction>(V) ) { if( auto bop = llvm::dyn_cast<llvm::BinaryOperator>(I) ) { auto op0 = bop->getOperand(0); auto op1 = bop->getOperand(1); unsigned op = bop->getOpcode(); switch( op ) { case llvm::Instruction::Add : isAdd=true; break; case llvm::Instruction::Sub : isAdd=false; break; default: std::cout << "\n\nInvalid operation. Must be + or -\n\n"; exit(1); } if( llvm::ConstantInt *C = llvm::dyn_cast<llvm::ConstantInt>(op0) ) { if(isAdd && C->isNegative()) { return false; } else if(!isAdd && C->isNegative()) { return true; } } else if( llvm::ConstantInt *C = llvm::dyn_cast<llvm::ConstantInt>(op1) ) { if(isAdd && C->isNegative()) { return false; } else if(!isAdd && C->isNegative()) { return true; } } } } return true; } llvm::GetElementPtrInst* getGEP(llvm::LoadInst* load) { auto addr = load->getOperand(0); if( auto addr_bc = llvm::dyn_cast<llvm::BitCastInst>(addr) ) addr = addr_bc->getOperand(0); if( auto elemPtr = llvm::dyn_cast<llvm::GetElementPtrInst>(addr)) return elemPtr; else return NULL; // No GEP for global variables } llvm::GetElementPtrInst* getGEP(llvm::StoreInst* store) { auto addr = store->getOperand(1); if( auto addr_bc = llvm::dyn_cast<llvm::BitCastInst>(addr) ) addr = addr_bc->getOperand(0); if( auto elemPtr = llvm::dyn_cast<llvm::GetElementPtrInst>(addr) ) return elemPtr; else return NULL; // No GEP for global variables } llvm::Value* getIdx(llvm::LoadInst* load) { if(auto elemPtr = getGEP(load)) { auto idx = elemPtr->getOperand(1); if(elemPtr->getNumIndices() == 2) idx = elemPtr->getOperand(2); return idx; } else { return NULL; // No indices for global variables } } llvm::Value* getIdx(llvm::StoreInst* store) { if(auto elemPtr = getGEP(store)) { auto idx = elemPtr->getOperand(1); if(elemPtr->getNumIndices() == 2) idx = elemPtr->getOperand(2); return idx; } else { return NULL; // No indices for global variables } } llvm::AllocaInst* getAlloca(llvm::LoadInst* load) { if(auto elemPtr = getGEP(load)) { auto arry = elemPtr->getPointerOperand(); llvm::AllocaInst *arry_alloca = llvm::dyn_cast<llvm::AllocaInst>(arry); return arry_alloca; } else { return NULL; // No alloca inst for global variables } } llvm::AllocaInst* getAlloca(llvm::StoreInst* store) { if(auto elemPtr = getGEP(store)) { auto arry = elemPtr->getPointerOperand(); llvm::AllocaInst *arry_alloca = llvm::dyn_cast<llvm::AllocaInst>(arry); return arry_alloca; } else { return NULL; // No alloca inst for global variables } } llvm::Loop* getNextLoop(std::list<llvm::Loop*> lList, llvm::Loop* L) { bool flag = false; for(llvm::Loop* lo : lList) { if(flag) { return lo; } if(lo == L) { flag = true; } } return NULL; } llvm::Value* getArrValueFromZ3Expr(llvm::Value *V, z3::expr e, llvm::IRBuilder<> &irb, llvm::LLVMContext& c, std::map<std::string, llvm::Value*>& exprValMap, std::set<llvm::Value*>& arrSet) { llvm::Value *res = getValueFromZ3Expr(e, irb, c, exprValMap, arrSet); if(V != NULL ) { res = irb.CreateGEP(V, res); res = irb.CreateLoad(res); res = irb.CreateSExt(res, llvm::IntegerType::getInt64Ty(c)); assert(res); } return res; } llvm::Value* getValueFromZ3Expr(z3::expr e, llvm::IRBuilder<> &irb, llvm::LLVMContext& c, std::map<std::string, llvm::Value*>& exprValMap, std::set<llvm::Value*>& arrSet) { llvm::Value *res = NULL; if(e.is_numeral()) { int64_t num; if (Z3_get_numeral_int64(e.ctx(), e, &num)) { res = llvm::ConstantInt::get(llvm::IntegerType::getInt32Ty(c), num); assert(res); } } else if (e.is_var()) { std::string varName = e.decl().name().str(); // std::cout << "\n Getting Val for Expr: " << varName << "\n"; res = exprValMap.at(varName); assert(res); if(llvm::isa<llvm::GlobalVariable>(res)) { res = irb.CreateLoad(res); } else { // res = irb.CreateSExt(res, llvm::IntegerType::getInt64Ty(c)); } assert(res); } else if (e.is_app()) { // std::cout << "\n Getting val for subexpr \n"; res = getValueFromZ3SubExpr(e, irb, c, exprValMap, arrSet); assert(res); } else if (e.is_quantifier()) { tiler_error("llvmUtils", "encountered a quantifier"); } return res; } llvm::Value* getValueFromZ3SubExpr(z3::expr e, llvm::IRBuilder<> &irb, llvm::LLVMContext& c, std::map<std::string, llvm::Value*>& exprValMap, std::set<llvm::Value*>& arrSet) { std::list<llvm::Value*> argValList; unsigned args = e.num_args(); for (unsigned i = 0; i<args; i++) { z3::expr arg = e.arg(i); argValList.push_back(getValueFromZ3Expr(arg, irb, c, exprValMap, arrSet)); } Z3_decl_kind dk = e.decl().decl_kind(); std::list<llvm::Value*>::const_iterator argListIt; argListIt = argValList.begin(); if (dk == Z3_OP_MUL) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateMul(res, *argListIt); assert(res); } return res; } else if (dk == Z3_OP_ADD) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateAdd(res, *argListIt); assert(res); } return res; } else if (dk == Z3_OP_SUB) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateSub(res, *argListIt); assert(res); } return res; } else if (dk == Z3_OP_DIV || dk == Z3_OP_IDIV) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateSDiv(res, *argListIt); assert(res); } return res; } else if (dk == Z3_OP_REM) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateSRem(res, *argListIt); assert(res); } return res; } else if (dk == Z3_OP_UMINUS) { llvm::Value* res = irb.CreateNeg(*argListIt); assert(res); return res; } else if (dk == Z3_OP_SELECT) { // std::cout << "\n Found a select statement with " << args << " args \n"; llvm::Value* Arr = *argListIt; assert(Arr); argListIt++; llvm::Value* Ind = *argListIt; assert(Ind); llvm::Value* res = irb.CreateGEP(Arr, Ind); assert(res); res = irb.CreateLoad(res); assert(res); // res = irb.CreateSExt(res, llvm::IntegerType::getInt64Ty(c)); assert(res); return res; } else if (dk == Z3_OP_NOT) { llvm::Value* res = irb.CreateNot(*argListIt); assert(res); return res; } else if (dk == Z3_OP_AND) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateAnd(res, *argListIt); assert(res); } res = irb.CreateSExt(res, llvm::IntegerType::getInt32Ty(c)); assert(res); return res; } else if (dk == Z3_OP_OR) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateOr(res, *argListIt); assert(res); } res = irb.CreateSExt(res, llvm::IntegerType::getInt32Ty(c)); assert(res); return res; } else if (dk == Z3_OP_EQ) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateICmpEQ(res, *argListIt); assert(res); } res = irb.CreateSExt(res, llvm::IntegerType::getInt32Ty(c)); assert(res); return res; } else if (dk == Z3_OP_GE) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateICmpSGE(res, *argListIt); assert(res); } res = irb.CreateSExt(res, llvm::IntegerType::getInt32Ty(c)); assert(res); return res; } else if (dk == Z3_OP_GT) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateICmpSGT(res, *argListIt); assert(res); } res = irb.CreateSExt(res, llvm::IntegerType::getInt32Ty(c)); assert(res); return res; } else if (dk == Z3_OP_LE) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateICmpSLE(res, *argListIt); assert(res); } res = irb.CreateSExt(res, llvm::IntegerType::getInt32Ty(c)); assert(res); return res; } else if (dk == Z3_OP_LT) { llvm::Value* res = *argListIt; assert(res); argListIt++; for(;argListIt != argValList.end(); argListIt++) { assert(*argListIt); res = irb.CreateICmpSLT(res, *argListIt); assert(res); } res = irb.CreateSExt(res, llvm::IntegerType::getInt32Ty(c)); assert(res); return res; } else { std::string varName = e.decl().name().str(); llvm::Value* res = exprValMap.at(varName); assert(res); if(arrSet.count(res) == 0) { if(llvm::isa<llvm::GlobalVariable>(res)) { res = irb.CreateLoad(res); } else { // res = irb.CreateSExt(res, llvm::IntegerType::getInt64Ty(c)); } assert(res); } return res; } } bool checkRangeOverlap(z3::expr range1, z3::expr range2) { z3::context& z3_ctx = range1.ctx(); z3::expr_vector ipsrc(z3_ctx); z3::expr_vector ipdst(z3_ctx); std::string lbName = "__lb"; std::string ubName = "__ub"; z3::expr lb = z3_ctx.int_const(lbName.c_str()); z3::expr ub = z3_ctx.int_const(ubName.c_str()); std::string lbpName = lbName+"_p"; std::string ubpName = ubName+"_p"; z3::expr lbp = z3_ctx.int_const(lbpName.c_str()); z3::expr ubp = z3_ctx.int_const(ubpName.c_str()); ipsrc.push_back(ub); ipsrc.push_back(lb); ipdst.push_back(ubp); ipdst.push_back(lbp); z3::expr sub_range2 = range2.substitute(ipsrc, ipdst); z3::solver s(z3_ctx); s.add(range1); s.add(sub_range2); if (s.check() == z3::sat) { return true; } else { return false; } } void collect_fun_bb(llvm::Function* f, std::vector<llvm::BasicBlock*>& fun_bb_vec) { for( auto bbit = f->begin(), end = f->end(); bbit != end; bbit++ ) { llvm::BasicBlock* bb = &(*bbit); fun_bb_vec.push_back(bb); } } void get_topologically_sorted_bb(llvm::Function *f, std::vector<llvm::BasicBlock*>& fun_bb_vec) { llvm::ReversePostOrderTraversal<llvm::Function*> RPOT(f); for (llvm::ReversePostOrderTraversal<llvm::Function*>::rpo_iterator RI = RPOT.begin(), RE = RPOT.end(); RI != RE; ++RI) { llvm::BasicBlock* b = *RI; fun_bb_vec.push_back(b); // b->print( llvm::outs() ); llvm::outs() << "\n\n"; } } void collect_arr(llvm::Function &f, std::set<llvm::AllocaInst*>& arrSet) { arrSet.clear(); for( auto bbit = f.begin(), end = f.end(); bbit != end; bbit++ ) { llvm::BasicBlock* bb = &(*bbit); for( llvm::Instruction& Iobj : bb->getInstList() ) { llvm::Instruction* I = &(Iobj); if( auto alloc = llvm::dyn_cast<llvm::AllocaInst>(I) ) { if( alloc->isArrayAllocation() && !alloc->getType()->getElementType()->isIntegerTy() && !alloc->getType()->getElementType()->isFloatTy()) { tiler_error( "llvmUtils", "only pointers to intergers and floats is allowed!" ); } arrSet.insert( alloc ); } } } } bool is_assume_call(const llvm::CallInst* call) { assert( call ); llvm::Function* fp = call->getCalledFunction(); if( fp != NULL && (fp->getName() == "_Z6assumeb" || fp->getName() == "assume" || fp->getName() == "assume_abort_if_not" || fp->getName().startswith("__VERIFIER_assume") ) ) { return true; } else if (fp == NULL) { const llvm::Value * val = call->getCalledValue(); if( auto CE = llvm::dyn_cast<llvm::ConstantExpr>(val) ) { if(CE->isCast()) { if(CE->getOperand(0)->getName() == "assume" || CE->getOperand(0)->getName() == "assume_abort_if_not" || CE->getOperand(0)->getName() == "_Z6assumeb" || CE->getOperand(0)->getName().startswith("__VERIFIER_assume")) { return true; } } } } return false; } bool is_assert_call(const llvm::CallInst* call ) { assert( call ); llvm::Function* fp = call->getCalledFunction(); if( fp != NULL && (fp->getName() == "_Z6assertb" || fp->getName() == "assert" || fp->getName().startswith("__VERIFIER_assert") ) ) { return true; } else if (fp == NULL) { const llvm::Value * val = call->getCalledValue(); if( auto CE = llvm::dyn_cast<llvm::ConstantExpr>(val) ) { if(CE->isCast()) { if(CE->getOperand(0)->getName() == "assert" || CE->getOperand(0)->getName() == "_Z6assertb" || CE->getOperand(0)->getName().startswith("__VERIFIER_assert") ) { return true; } } } } return false; } bool is_assert_loop( llvm::Loop* L ) { bool assert_seen=false; for( auto bb: L->getBlocks() ) { for( auto it = bb->begin(), e = bb->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if( auto call = llvm::dyn_cast<llvm::CallInst>(I) ) { if(llvm::isa<llvm::DbgValueInst>(I) ||llvm::isa<llvm::DbgDeclareInst>(I)){ // Ignore debug instructions }else{ assert_seen = assert_seen || is_assert_call(call); } } } } return assert_seen; } class bb_succ_iter : public llvm::succ_const_iterator { public: bb_succ_iter( llvm::succ_const_iterator begin_, llvm::succ_const_iterator end_, std::set<const llvm::BasicBlock*>& back_edges ) : llvm::succ_const_iterator( begin_ ), end(end_), b_edges( back_edges ) { llvm::succ_const_iterator& it = (llvm::succ_const_iterator&)*this; while( it != end && exists( b_edges, (const llvm::BasicBlock*)*it) ) ++it; }; bb_succ_iter( llvm::succ_const_iterator begin_, llvm::succ_const_iterator end_ ) : llvm::succ_const_iterator( begin_ ), end(end_) {}; bb_succ_iter( llvm::succ_const_iterator end_ ) : llvm::succ_const_iterator( end_ ), end( end_ ) {}; llvm::succ_const_iterator end; std::set<const llvm::BasicBlock*> b_edges; bb_succ_iter& operator++() { llvm::succ_const_iterator& it = (llvm::succ_const_iterator&)*this; do{ ++it; }while( it != end && exists( b_edges, (const llvm::BasicBlock*)*it) ); return *this; } }; void computeTopologicalOrder( llvm::Function &F, std::map<const llvm::BasicBlock*,std::set<const llvm::BasicBlock*>>& bedges, std::vector<const llvm::BasicBlock*>& bs, std::map< const llvm::BasicBlock*, unsigned >& o_map) { auto f = [&bedges](const llvm::BasicBlock* b) { if( exists( bedges, b ) ) { return bb_succ_iter( llvm::succ_begin(b), llvm::succ_end(b),bedges.at(b)); }else{ return bb_succ_iter( llvm::succ_begin(b), llvm::succ_end(b)); } }; auto e = [](const llvm::BasicBlock* b) { return bb_succ_iter( llvm::succ_end(b) ); }; const llvm::BasicBlock* h = &F.getEntryBlock(); bs.clear(); o_map.clear(); topological_sort<const llvm::BasicBlock*, bb_succ_iter>( h, f, e, bs, o_map ); } // Pass p must declare it requires LoopInfoWrapperPass void collect_loop_backedges(llvm::Pass *p, std::map< const llvm::BasicBlock*, std::set<const llvm::BasicBlock*>>& loop_ignore_edge, std::map< const llvm::BasicBlock*, std::set<const llvm::BasicBlock*>>& rev_loop_ignore_edge) { //todo: llvm::FindFunctionBackedges could have done the job auto &LIWP = p->getAnalysis<llvm::LoopInfoWrapperPass>(); auto LI = &LIWP.getLoopInfo(); std::vector<llvm::Loop*> loops, stack; for(auto I = LI->rbegin(), E = LI->rend(); I != E; ++I) stack.push_back(*I); while( !stack.empty() ) { llvm::Loop *L = stack.back(); stack.pop_back(); loops.push_back( L ); for(auto I = L->begin(), E = L->end(); I != E; ++I) stack.push_back(*I); } loop_ignore_edge.clear(); rev_loop_ignore_edge.clear(); for( llvm::Loop *L : loops ) { auto h = L->getHeader(); llvm::SmallVector<llvm::BasicBlock*,10> LoopLatches; L->getLoopLatches( LoopLatches ); for( llvm::BasicBlock* bb : LoopLatches ) { loop_ignore_edge[h].insert( bb ); rev_loop_ignore_edge[bb].insert(h); } } } void collect_block_ancestors(llvm::BasicBlock* b, std::map<llvm::BasicBlock*, std::set<llvm::BasicBlock*>>& block_preds_map) { auto& preds = block_preds_map[b]; std::vector<llvm::BasicBlock*> stack; std::vector<llvm::BasicBlock*> processed; processed.push_back(b); for (llvm::BasicBlock *pb : llvm::predecessors(b)) { if(block_preds_map.find(pb) != block_preds_map.end()) { preds.insert( pb ); processed.push_back(pb); for(llvm::BasicBlock *ab : block_preds_map.at(pb)) { preds.insert( ab ); processed.push_back(ab); } } else { stack.push_back(pb); processed.push_back(pb); } } while( !stack.empty() ) { llvm::BasicBlock *pb = stack.back(); stack.pop_back(); preds.insert( pb ); for (llvm::BasicBlock *ppb : llvm::predecessors(pb)) { if(find(processed.begin(), processed.end(), ppb) == processed.end()) { stack.push_back(ppb); processed.push_back(ppb); } } } } llvm::Value* collect_loads_recs(llvm::Value* v, llvm::Value* N, std::list<llvm::Value*>& load_lst) { llvm::Value* rec_t = NULL; if(llvm::isa<llvm::LoadInst>(v)) { load_lst.push_back(v); } else if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(v)) { if(isRemInBop(bop)) return NULL; assert( bop ); llvm::Value* rec_t0 = NULL; llvm::Value* rec_t1 = NULL; auto op0 = bop->getOperand( 0 ); auto op1 = bop->getOperand( 1 ); if(llvm::isa<llvm::BinaryOperator>(op0)) { rec_t0 = collect_loads_recs(op0, N, load_lst); } else if(auto op0_l = llvm::dyn_cast<llvm::LoadInst>(op0)) { if(op0_l->getOperand(0) != N) load_lst.push_back(op0_l); else rec_t0 = op0_l; } else rec_t0 = op0; if(llvm::isa<llvm::BinaryOperator>(op1)) { rec_t1 = collect_loads_recs(op1, N, load_lst); } else if(auto op1_l = llvm::dyn_cast<llvm::LoadInst>(op1)) { if(op1_l->getOperand(0) != N) load_lst.push_back(op1_l); else rec_t1 = op1_l; } else rec_t1 = op1; if(rec_t0 != NULL) rec_t = rec_t0; if(rec_t1 != NULL) rec_t = rec_t1; if(rec_t0 != NULL && rec_t1 != NULL) rec_t = bop; } else { rec_t = v; } return rec_t; } // Pass p must declare it requires LoopInfoWrapperPass void find_cutpoints(llvm::Pass* P, llvm::Function &f, std::vector< llvm::BasicBlock* >& cutPoints) { cutPoints.clear(); cutPoints.push_back(&f.getEntryBlock()); std::vector<llvm::Loop*> stack; auto &LIWP = P->getAnalysis<llvm::LoopInfoWrapperPass>(); auto LI = &LIWP.getLoopInfo(); for(auto I = LI->rbegin(), E = LI->rend(); I != E; ++I) stack.push_back(*I); while( !stack.empty() ) { llvm::Loop *L = stack.back(); stack.pop_back(); cutPoints.push_back( L->getHeader() ); for(auto I = L->begin(), E = L->end(); I != E; ++I) stack.push_back(*I); } } void create_segments(llvm::Function &f, std::vector< llvm::BasicBlock* >& cutPoints, std::vector< segment >& segVec) { segVec.clear(); std::map< llvm::BasicBlock*, bool > bbVisited; std::vector< llvm::BasicBlock* > stack; for (auto fi = f.begin(), fe = f.end(); fi != fe; ++fi) bbVisited[&(*fi)] = false; for(llvm::BasicBlock* bb : cutPoints) { for (llvm::succ_iterator sit = succ_begin(bb), set = succ_end(bb); sit != set; ++sit) { llvm::BasicBlock* b = *sit; segment s; s.entryCutPoints.push_back(bb); bbVisited[bb] = true; std::map<std::string, llvm::Value*> nameValueMap; buildBlockMap(bb, nameValueMap); s.assuMapCPs[bb] = nameValueMap; if(exists(cutPoints, b)) { if(!exists(s.exitCutPoints, b)) { s.exitCutPoints.push_back(b); } std::map<std::string, llvm::Value*> nameValueMap; buildBlockMap(b, nameValueMap); s.assertMapCPs[b] = nameValueMap; } else if(!bbVisited.at(b)) { stack.push_back(b); while(!stack.empty()) { llvm::BasicBlock* sbb = stack.back(); if(bbVisited.at(sbb)) { stack.pop_back(); } else { s.bodyBlocks.push_back(sbb); bbVisited[sbb] = true; stack.pop_back(); for (llvm::succ_iterator sit = succ_begin(sbb), set = succ_end(sbb); sit != set; ++sit) { llvm::BasicBlock* b = *sit; if(exists(cutPoints, b)) { if(!exists(s.exitCutPoints, b)) { s.exitCutPoints.push_back(b); } std::map<std::string, llvm::Value*> nameValueMap; buildBlockMap(b, nameValueMap); s.assertMapCPs[b] = nameValueMap; } else if(!bbVisited.at(b)) { stack.push_back(b); } } for (llvm::pred_iterator pit = pred_begin(sbb), pet = pred_end(sbb); pit != pet; ++pit) { llvm::BasicBlock* b = *pit; if(exists(cutPoints, b)) { if(!exists(s.entryCutPoints, b)) { s.entryCutPoints.push_back(b); } std::map<std::string, llvm::Value*> nameValueMap; buildBlockMap(b, nameValueMap); s.assuMapCPs[b] = nameValueMap; } else if(!bbVisited.at(b)) { stack.push_back(b); } } } } if(!s.bodyBlocks.empty()) { segVec.push_back(s); } } } } } void buildBlockMap(llvm::BasicBlock* bb, std::map<std::string, llvm::Value*>& nameValueMap) { for (llvm::Instruction &II : *bb){ llvm::Instruction* I = &II; llvm::Value* var = NULL; llvm::MDNode* md = NULL; std::string str; if( llvm::DbgDeclareInst* dDecl = llvm::dyn_cast<llvm::DbgDeclareInst>(I) ) { var = dDecl->getAddress(); md = dDecl->getVariable(); llvm::DIVariable* diMd = llvm::dyn_cast<llvm::DIVariable>(md); str = (std::string)( diMd->getName() ); } else if( llvm::DbgValueInst* dVal = llvm::dyn_cast<llvm::DbgValueInst>(I)) { var = dVal->getValue(); md = dVal->getVariable(); llvm::DIVariable* diMd = llvm::dyn_cast<llvm::DIVariable>(md); str = (std::string)( diMd->getName() ); } if( var ) { nameValueMap[str] = var; } } } int readInt( const llvm::ConstantInt* c ) { const llvm::APInt& n = c->getUniqueInteger(); unsigned len = n.getNumWords(); if( len > 1 ) tiler_error("llvmUtils", "long integers not supported!!" ); const uint64_t *v = n.getRawData(); return *v; } // Remove a loop bool deleteLoop(llvm::Loop *L, llvm::DominatorTree &DT, llvm::ScalarEvolution &SE, llvm::LoopInfo &LI) { llvm::SmallPtrSet<llvm::BasicBlock *, 8> blocks; blocks.insert(L->block_begin(), L->block_end()); llvm::BasicBlock *preheader = L->getLoopPreheader(); if (!preheader) return false; llvm::SmallVector<llvm::BasicBlock *, 4> exitingBlocks; L->getExitingBlocks(exitingBlocks); llvm::SmallVector<llvm::BasicBlock *, 4> exitBlocks; L->getUniqueExitBlocks(exitBlocks); // Single exit block to branch to if (exitBlocks.size() != 1) return false; // Tell ScalarEvolution that the loop is deleted SE.forgetLoop(L); // Connect the preheader directly to the exit block llvm::TerminatorInst *TI = preheader->getTerminator(); // llvm::Instruction *TI = preheader->getTerminator(); // LLVM 8 assert(TI && TI->isTerminator()); llvm::BasicBlock *exitBlock = exitBlocks[0]; TI->replaceUsesOfWith(L->getHeader(), exitBlock); // Rewrite phis in the exit block to get their inputs from // the preheader instead of the exiting block llvm::BasicBlock *exitingBlock = exitingBlocks[0]; llvm::BasicBlock::iterator BI = exitBlock->begin(); while (llvm::PHINode *P = llvm::dyn_cast<llvm::PHINode>(BI)) { int j = P->getBasicBlockIndex(exitingBlock); assert(j >= 0 && "Can't find exiting block in exit block's phi node!"); P->setIncomingBlock(j, preheader); for (unsigned i = 1; i < exitingBlocks.size(); ++i) P->removeIncomingValue(exitingBlocks[i]); ++BI; } std::cout << "Updated the Phi nodes of the exit block\n"; // Update the dominator tree // Remove blocks that will be deleted from the reference counting scheme llvm::SmallVector<llvm::DomTreeNode*, 8> ChildNodes; for (llvm::Loop::block_iterator LBI = L->block_begin(), LE = L->block_end(); LBI != LE; ++LBI) { // Move all of the block's children to be children of the preheader in DT // Remove DT entry for the block ChildNodes.insert(ChildNodes.begin(), DT[*LBI]->begin(), DT[*LBI]->end()); for (llvm::DomTreeNode *ChildNode : ChildNodes) { DT.changeImmediateDominator(ChildNode, DT[preheader]); } ChildNodes.clear(); DT.eraseNode(*LBI); // Remove the block from the reference counting (*LBI)->dropAllReferences(); } // std::cout << "Erase the blocks from the loop"; for (llvm::BasicBlock *BB : blocks) BB->eraseFromParent(); // Remove the blocks from loopinfo for (llvm::BasicBlock *BB : blocks) LI.removeBlock(BB); // Update LoopInfo // #ifndef LLVM_SVN // LI.markAsRemoved(L); // #endif return true; } //todo: streamline getLoc and getLocation src_loc getLoc( const llvm::Instruction* I ) { if( auto dbg = llvm::dyn_cast<llvm::DbgInfoIntrinsic>(I) ) { // if( auto dbg = llvm::dyn_cast<llvm::DbgVariableIntrinsic>(dbgi) ) { auto loc = dbg->getVariableLocation(); if( auto I_val = llvm::dyn_cast<llvm::Instruction>(loc) ) { if( I_val ) I = I_val; }else if( llvm::dyn_cast<llvm::Constant>(loc) ) { // what to do?? } else { tiler_error("llvmUtils", "Unknown type"); } // } else { // tiler_error("llvmUtils", "Not handled type of Info Intrinsic Inst"); // } } const llvm::DebugLoc d = I->getDebugLoc(); if( d ) { unsigned l = d.getLine(); unsigned c = d.getCol(); std::string f =llvm::cast<llvm::DIScope>(d.getScope())->getFilename(); return src_loc(l,c,f); } return src_loc(); } std::string getLocation(const llvm::Instruction* I ) { const llvm::DebugLoc d = I->getDebugLoc(); if( d ) { unsigned line = d.getLine(); unsigned col = d.getCol(); auto *Scope = llvm::cast<llvm::DIScope>(d.getScope()); std::string fname = Scope->getFilename(); std::string l_name = fname + ":" + std::to_string(line) + ":" + std::to_string(col); return l_name; }else{ return ""; } } std::string getLocation(const llvm::BasicBlock* b ) { auto I = b->getFirstNonPHIOrDbg(); return getLocation(I); } std::string getLocRange(const llvm::BasicBlock* b ) { unsigned minLine = std::numeric_limits<unsigned>::max(); unsigned minCol = std::numeric_limits<unsigned>::max(); unsigned maxLine = 0; unsigned maxCol = 0; std::string fname = ""; for( const llvm::Instruction& Iobj : b->getInstList() ) { const llvm::Instruction* I = &(Iobj); const llvm::DebugLoc d = I->getDebugLoc(); if( d ) { unsigned line = d.getLine(); unsigned col = d.getCol(); auto *Scope = llvm::cast<llvm::DIScope>(d.getScope()); if( fname.empty() ) fname = Scope->getFilename(); if( line < minLine ) { minLine = line; minCol = col; }else if( line == minLine ) { if( col < minCol ) minCol = col; } if( line > maxLine ) { maxLine = line; maxCol = col; }else if( line == maxLine ) { if( col > maxCol ) maxCol = col; } } } std::string l_name = fname + ":" + std::to_string(minLine) + ":"+ std::to_string(minCol) + "-" + std::to_string(maxLine) + ":"+ std::to_string(maxCol); return l_name; } z3::sort llvm_to_z3_sort( z3::context& c, llvm::Type* t ) { if( t->isIntegerTy() ) { if( t->isIntegerTy( 16 ) ) return c.int_sort(); if( t->isIntegerTy( 32 ) ) return c.int_sort(); if( t->isIntegerTy( 64 ) ) return c.int_sort(); if( t->isIntegerTy( 8 ) ) return c.bool_sort(); if( t->isIntegerTy( 1 ) ) return c.bool_sort(); } if( t->isArrayTy() ) { llvm::Type* te = t->getArrayElementType(); z3::sort z_te = llvm_to_z3_sort(c, te); return c.array_sort( c.int_sort(), z_te ); } if( t->isFloatTy() ) { return c.real_sort(); } tiler_error("llvmUtils", "only int and bool sorts are supported"); // return c.bv_sort(32); // needs to be added // return c.bv_sort(16); // return c.bv_sort(64); // return c.bool_sort(); // return c.real_sort(); return c.int_sort(); // dummy return } z3::expr read_const( const llvm::Value* op, z3::context& ctx ) { assert( op ); if( const llvm::ConstantInt* c = llvm::dyn_cast<llvm::ConstantInt>(op) ) { unsigned bw = c->getBitWidth(); if(bw == 16 || bw == 32 || bw == 64 ) { int i = readInt( c ); return ctx.int_val(i); }else if(bw == 1 || bw == 8) { int i = readInt( c ); assert( i == 0 || i == 1 ); if( i == 1 ) return ctx.bool_val(true); else return ctx.bool_val(false); }else tiler_error("llvmUtils", "unrecognized constant!" ); }else if( llvm::isa<llvm::ConstantPointerNull>(op) ) { tiler_error("llvmUtils", "Constant pointer are not implemented!!" ); // }else if( LLCAST( llvm::ConstantPointerNull, c, op) ) { return ctx.int_val(0); }else if( llvm::isa<llvm::UndefValue>(op) ) { llvm::Type* ty = op->getType(); if( auto i_ty = llvm::dyn_cast<llvm::IntegerType>(ty) ) { int bw = i_ty->getBitWidth(); if(bw == 16 || bw == 32 || bw == 64 ) { return get_fresh_int(ctx); }else if( bw == 1 ) { return get_fresh_bool(ctx); } } tiler_error("llvmUtils", "unsupported type: "<< ty << "!!"); }else if(const llvm::ConstantFP* c = llvm::dyn_cast<llvm::ConstantFP>(op) ) { const llvm::APFloat& n = c->getValueAPF(); double v = n.convertToDouble(); return ctx.real_val(std::to_string(v).c_str()); //tiler_error("llvmUtils", "Floating point constant not implemented!!" ); }else if( llvm::isa<llvm::Constant>(op) ) { tiler_error("llvmUtils", "non int constants are not implemented!!" ); std::cerr << "un recognized constant!"; // // int i = readInt(c); // // return eHandler->mkIntVal( i ); }else if( llvm::isa<llvm::ConstantExpr>(op) ) { tiler_error("llvmUtils", "case for constant not implemented!!" ); }else if( llvm::isa<llvm::ConstantArray>(op) ) { // const llvm::ArrayType* n = c->getType(); // unsigned len = n->getNumElements(); //return ctx.arraysort(); tiler_error("llvmUtils", "case for constant not implemented!!" ); }else if( llvm::isa<llvm::ConstantStruct>(op) ) { // const llvm::StructType* n = c->getType(); tiler_error("llvmUtils", "case for constant not implemented!!" ); }else if( llvm::isa<llvm::ConstantVector>(op) ) { // const llvm::VectorType* n = c->getType(); tiler_error("llvmUtils", "vector constant not implemented!!" ); } z3::expr e(ctx); return e; // contains no expression; } std::vector<llvm::BasicBlock*> to_std_vec(llvm::SmallVector<llvm::BasicBlock*, 20>& bb_sv) { std::vector<llvm::BasicBlock*> bb_stdv; for(bb* b : bb_sv) { bb_stdv.push_back(b); } return bb_stdv; } llvm::SmallVector<llvm::BasicBlock*, 40> to_small_vec(std::vector<llvm::BasicBlock*>& bb_vec) { llvm::SmallVector<llvm::BasicBlock*, 40> bb_sv; for(bb* b : bb_vec) { bb_sv.push_back(b); } return bb_sv; } bool cmp_loop_by_line_num (llvm::Loop* l1, llvm::Loop* l2) { assert(l1); assert(l2); const llvm::DebugLoc d1 = l1->getStartLoc(); const llvm::DebugLoc d2 = l2->getStartLoc(); if(d1.getLine() < d2.getLine()) { return true; } else { return false; } } void remove_loop_back_edge (llvm::Loop* L) { bb* exit_block = NULL; bb* header = L->getHeader(); bb* latch = L->getLoopLatch(); llvm::Instruction* term = latch->getTerminator(); if (llvm::BranchInst* bi = llvm::dyn_cast<llvm::BranchInst>(term)) { const int NumS = bi->getNumSuccessors(); for(int i=0; i<NumS; i++) { bb* s = bi->getSuccessor(i); if(s != header) { exit_block = s; } } // Remove the conditional branch and add a unconditional branch llvm::IRBuilder<> b(term); b.CreateBr(exit_block); llvm::Value *loopCond = bi->getCondition(); bi->eraseFromParent(); if( auto icmp = llvm::dyn_cast<llvm::ICmpInst>(loopCond) ) { icmp->eraseFromParent(); } } /* // Doing this generates bmc formula where the // needed path gets sliced off for(int i=0; i<NumS; i++) { bb* s = bi->getSuccessor(i); if(s == header) { bi->setSuccessor(i, exit_block); } } */ } void populate_arr_rd_wr(llvm::BasicBlock* bb, std::map<llvm::Value*, std::list<llvm::Value*>>& arrRead, std::map<llvm::Value*, std::list<llvm::Value*>>& arrWrite) { arrRead.clear(); arrWrite.clear(); for( auto it = bb->begin(), e = bb->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if( auto store = llvm::dyn_cast<llvm::StoreInst>(I) ) { auto addr = store->getOperand(1); if( auto addr_bc = llvm::dyn_cast<llvm::BitCastInst>(addr) ) addr = addr_bc->getOperand(0); if( auto elemPtr = llvm::dyn_cast<llvm::GetElementPtrInst>(addr) ) { auto arry = elemPtr->getPointerOperand(); arrWrite[arry].push_back(store); } else {} // Do nothing } else if( auto load = llvm::dyn_cast<llvm::LoadInst>(I) ) { auto addr = load->getOperand(0); if( auto addr_bc = llvm::dyn_cast<llvm::BitCastInst>(addr) ) addr = addr_bc->getOperand(0); if(auto elemPtr = llvm::dyn_cast<llvm::GetElementPtrInst>(addr) ) { auto arry = elemPtr->getPointerOperand(); arrRead[arry].push_back(load); } else{} // Do nothing } else {} // Do nothing for inst other than store and load } } // Following function is taken from the llvm class lib/Transform/Scalar/LoopInterchange // We require that the PHINode must be only of the integer type. llvm::PHINode* getInductionVariable(llvm::Loop *L, llvm::ScalarEvolution *SE) { llvm::PHINode* InnerIndexVar = L->getCanonicalInductionVariable(); if (InnerIndexVar) return InnerIndexVar; if (L->getLoopLatch() == nullptr || L->getLoopPredecessor() == nullptr) return nullptr; for (llvm::BasicBlock::iterator I = L->getHeader()->begin(); llvm::isa<llvm::PHINode>(I); ++I) { llvm::PHINode *PhiVar = llvm::cast<llvm::PHINode>(I); llvm::Type *PhiTy = PhiVar->getType(); if (!PhiTy->isIntegerTy()) return nullptr; const llvm::SCEVAddRecExpr *AddRec = llvm::dyn_cast<llvm::SCEVAddRecExpr>(SE->getSCEV(PhiVar)); if (!AddRec || !AddRec->isAffine()) continue; const llvm::SCEV *Step = AddRec->getStepRecurrence(*SE); if (!llvm::isa<llvm::SCEVConstant>(Step)) continue; // Found the induction variable. // FIXME: Handle loops with more than one induction variable. Note that, // currently, legality makes sure we have only one induction variable. return PhiVar; } return nullptr; } llvm::Value* find_ind_param_N(std::unique_ptr<llvm::Module>& module, llvm::Function* f, llvm::BasicBlock* entry_bb) { llvm::Value* N = NULL; bool checkAssignment = false; if(f->arg_size() == 1 ) { // Use the only param to the function as the program parameter N = &(*f->arg_begin()); } else if(!module->global_empty()) { // Use the only global variable as the program parameter int glbCntr = 0; for( auto iter_glb= module->global_begin(),end_glb = module->global_end(); iter_glb != end_glb; ++iter_glb ) { glbCntr ++; N = &*iter_glb; //3.8 } // if(glbCntr != 1) // tiler_error("llvmUtils", "Unable to find the program variable N for induction"); checkAssignment = true; } else { for( auto it = entry_bb->begin(), e = entry_bb->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if( auto alloc = llvm::dyn_cast<llvm::AllocaInst>(I) ) { if(alloc->isStaticAlloca()) continue; if( auto zext = llvm::dyn_cast<llvm::ZExtInst>(alloc->getArraySize()) ) { if(llvm::isa<llvm::BinaryOperator>(zext->getOperand(0)) ) break; N = zext->getOperand(0); checkAssignment=true; break; } } } } if(N == NULL) { tiler_error("llvmUtils", "Unable to find a program variable to induct on"); } // If N is not a function parameter check that there is only one non-det assignment // to N in the first block of the program. // Otherwise, report error due to inability to find the full-program induction vairable. if(checkAssignment) { int storeToNCntr = 0; for( auto it = entry_bb->begin(), e = entry_bb->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if( auto store = llvm::dyn_cast<llvm::StoreInst>(I) ) { if(N == store->getOperand(1)) { if( auto call = llvm::dyn_cast<llvm::CallInst>(store->getOperand(0)) ) { llvm::Function* fp = call->getCalledFunction(); if( fp != NULL && fp->getName().startswith("__VERIFIER_nondet_") ) { storeToNCntr++; } } } } } if(storeToNCntr > 1) tiler_error("llvmUtils", "Unable to find the program variable N for induction"); int intermediateCnt = storeToNCntr; for( auto bbit = f->begin(), end = f->end(); bbit != end; bbit++ ) { llvm::BasicBlock* bb = &(*bbit); if(bb == entry_bb) continue; for( auto it = bb->begin(), e = bb->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if( auto store = llvm::dyn_cast<llvm::StoreInst>(I) ) { if(N == store->getOperand(1)) storeToNCntr++; } } } if(intermediateCnt != storeToNCntr) tiler_error("llvmUtils", "Unable to find the program variable N for induction"); } return N; } bool check_conditional_in_loopbody(llvm::Loop *L) { for( auto b: L->getBlocks() ) { if(b == L->getLoopLatch()) continue; for( auto it = b->begin(), e = b->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if (llvm::BranchInst* bi = llvm::dyn_cast<llvm::BranchInst>(I)) { if(bi->isUnconditional()) continue; if( llvm::isa<llvm::ICmpInst>(bi->getCondition()) ) { return true; } else {} } else {} } } return false; } // Pass p must declare it requires LoopInfoWrapperPass void check_conditional_in_loopbody(llvm::Pass* p, llvm::Value* N, int& unsupported) { auto &LIWP = p->getAnalysis<llvm::LoopInfoWrapperPass>(); auto LI = &LIWP.getLoopInfo(); for (auto I = LI->rbegin(), E = LI->rend(); I != E; ++I) { llvm::Loop *L = *I; for( auto b: L->getBlocks() ) { if(b == L->getLoopLatch()) continue; for( auto it = b->begin(), e = b->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if (llvm::BranchInst* bi = llvm::dyn_cast<llvm::BranchInst>(I)) { if(bi->isUnconditional()) continue; if( auto icmp = llvm::dyn_cast<llvm::ICmpInst>(bi->getCondition()) ) { if(isValueInSubExpr(N, icmp->getOperand( 0 ))) unsupported = 2; if(isValueInSubExpr(N, icmp->getOperand( 1 ))) unsupported = 2; } else { tiler_error("llvmUtils", "Non integer comparision is currently not supported"); } } else {} } } } } void check_indu_param_in_index(llvm::Function *f, llvm::Value* N, int& unsupported) { for( auto bbit = f->begin(), end = f->end(); bbit != end; bbit++ ) { llvm::BasicBlock* bb = &(*bbit); for( llvm::Instruction& Iobj : bb->getInstList() ) { llvm::Instruction* I = &(Iobj); if( auto load = llvm::dyn_cast<llvm::LoadInst>(I) ) { auto addr = load->getOperand(0); if(auto elemPtr = llvm::dyn_cast<llvm::GetElementPtrInst>(addr) ) { auto idx = elemPtr->getOperand(1); if(elemPtr->getNumIndices() == 2) idx = elemPtr->getOperand(2); if(isValueInSubExpr(N, idx)) unsupported = 3; } } } } } bool checkDependence(llvm::Value* expr, llvm::Value* val) { if(val == expr) return true; if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr) ) { bool res = checkDependence(bop->getOperand(0), val); if(res) return true; return checkDependence(bop->getOperand(1), val); } else if(llvm::ICmpInst* icmp = llvm::dyn_cast<llvm::ICmpInst>(expr)) { bool res = checkDependence(icmp->getOperand(0), val); if(res) return true; return checkDependence(icmp->getOperand(1), val); } else if( llvm::isa<llvm::CallInst>(expr) ) { // In general, need to check the parameters of the call I think return false; } else if( auto gep = llvm::dyn_cast<llvm::GetElementPtrInst>(expr) ) { return checkDependence(gep->getOperand(1), val); } else if(auto load = llvm::dyn_cast<llvm::LoadInst>(expr) ) { return checkDependence(load->getOperand(0), val); } else if(auto store = llvm::dyn_cast<llvm::StoreInst>(expr) ) { bool res = checkDependence(store->getOperand(0), val); if(res) return true; return checkDependence(store->getOperand(1), val); } else if( auto cast = llvm::dyn_cast<llvm::CastInst>(expr) ) { checkDependence(cast->getOperand(0), val); } else if( llvm::isa<llvm::AllocaInst>(expr) ) { return false; } else { return false; } } llvm::Instruction* cloneExpr(llvm::Instruction* expr, llvm::Instruction* insert_pos, llvm::Instruction* skip, llvm::Instruction* phi) { if(expr == skip) return NULL; if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr)) { auto* bopcl = bop->clone(); bopcl->insertBefore(insert_pos); llvm::ValueToValueMapTy VMap; if(llvm::Instruction* op1 = llvm::dyn_cast<llvm::Instruction>(bopcl->getOperand(0))) { auto* clOp1 = cloneExpr(op1, bopcl, skip, phi); if(clOp1 != NULL) VMap[op1] = clOp1; } if(llvm::Instruction* op2 = llvm::dyn_cast<llvm::Instruction>(bopcl->getOperand(1))) { auto* clOp2 = cloneExpr(op2, bopcl, skip, phi); if(clOp2 != NULL) VMap[op2] = clOp2; } llvm::RemapInstruction(bopcl, VMap, llvm::RF_IgnoreMissingLocals | llvm::RF_NoModuleLevelChanges); return bopcl; } else if(auto gep = llvm::dyn_cast<llvm::GetElementPtrInst>(expr)) { auto* g = gep ->clone(); g->insertBefore(insert_pos); llvm::ValueToValueMapTy VMap; if(llvm::Instruction* idx1 = llvm::dyn_cast<llvm::Instruction>(gep->getOperand(1))) { llvm::Instruction* clIdx1 = cloneExpr(idx1, g, skip, phi); if(clIdx1 != NULL) VMap[idx1] = clIdx1; } if(gep->getNumIndices() == 2) { if(llvm::Instruction* idx2 = llvm::dyn_cast<llvm::Instruction>(gep->getOperand(2))) { llvm::Instruction* clIdx2 = cloneExpr(idx2, g, skip, phi); if(clIdx2 != NULL) VMap[idx2] = clIdx2; } } llvm::RemapInstruction(g, VMap, llvm::RF_IgnoreMissingLocals | llvm::RF_NoModuleLevelChanges); return g; } else if(auto load = llvm::dyn_cast<llvm::LoadInst>(expr) ) { auto* l = load->clone(); l->insertBefore(insert_pos); llvm::ValueToValueMapTy VMap; if(llvm::Instruction* op = llvm::dyn_cast<llvm::Instruction>(l->getOperand(0))) { llvm::Instruction* v = cloneExpr(op, l, skip, phi); if(v != NULL) VMap[op] = v; } llvm::RemapInstruction(l, VMap, llvm::RF_IgnoreMissingLocals | llvm::RF_NoModuleLevelChanges); return l; } else if(auto cast = llvm::dyn_cast<llvm::CastInst>(expr)) { auto* c = cast->clone(); c->insertBefore(insert_pos); llvm::ValueToValueMapTy VMap; if(llvm::Instruction* op = llvm::cast<llvm::Instruction>(c->getOperand(0))) { auto* v = cloneExpr(op, c, skip, phi); if(v != NULL) VMap[op] = v; } llvm::RemapInstruction(c, VMap, llvm::RF_IgnoreMissingLocals | llvm::RF_NoModuleLevelChanges); return c; } else if(llvm::isa<llvm::PHINode>(expr)) { return phi; // tiler_error("Cloning", "Cloning a PHI node is a very very tricky thing!"); } else if(llvm::isa<llvm::CallInst>(expr)) { // Parameters to be cloned ? tiler_error("Cloning", "Call Instruciton currently not supported as a sub-expression"); } else if(llvm::isa<llvm::StoreInst>(expr)) { tiler_error("Cloning", "Store cannot be a part of the sub-expression"); } else if(llvm::isa<llvm::AllocaInst>(expr)) { return NULL; // Dont clone or remap } else if(llvm::isa<const llvm::GlobalVariable>(expr)) { return NULL; // Dont clone or remap } else { tiler_error("Cloning", "Case undefined for this expression"); } return NULL; } void eraseExpr(llvm::Instruction* expr, llvm::Instruction* skip) { if(expr == NULL) return; if(expr == skip) return; if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(expr)) { auto op0 = bop->getOperand(0); auto op1 = bop->getOperand(1); bop->eraseFromParent(); if(auto op0Inst = llvm::dyn_cast<llvm::Instruction>(op0)) eraseExpr(op0Inst, skip); if(auto op1Inst = llvm::dyn_cast<llvm::Instruction>(op1)) eraseExpr(op1Inst, skip); } else if(auto gep = llvm::dyn_cast<llvm::GetElementPtrInst>(expr)) { auto idx = gep->getOperand(1); if(gep->getNumIndices() == 2) idx = gep->getOperand(2); gep->eraseFromParent(); if(auto idxInst = llvm::dyn_cast<llvm::Instruction>(idx)) eraseExpr(idxInst, skip); } else if(auto load = llvm::dyn_cast<llvm::LoadInst>(expr) ) { auto op0 = load->getOperand(0); load->eraseFromParent(); if(auto op0Inst = llvm::dyn_cast<llvm::Instruction>(op0)) eraseExpr(op0Inst, skip); } else if(auto cast = llvm::dyn_cast<llvm::CastInst>(expr)) { auto op0 = cast->getOperand(0); cast->eraseFromParent(); if(auto op0Inst = llvm::dyn_cast<llvm::Instruction>(op0)) eraseExpr(op0Inst, skip); } else if(llvm::isa<llvm::PHINode>(expr)) { // Don't erase //tiler_error("Erasing", "Erasing a PHI node is a very bad idea!"); } else if(llvm::isa<llvm::CallInst>(expr)) { tiler_error("Erasing", "Erasing call Instrucitons currently not supported"); } else if(auto store = llvm::dyn_cast<llvm::StoreInst>(expr)) { auto op0 = store->getOperand(0); auto op1 = store->getOperand(1); store->eraseFromParent(); if(auto op1Inst = llvm::dyn_cast<llvm::Instruction>(op1)) eraseExpr(op1Inst, skip); if(auto op0Inst = llvm::dyn_cast<llvm::Instruction>(op0)) eraseExpr(op0Inst, skip); } else if(llvm::isa<llvm::AllocaInst>(expr)) { // Don't erase } else if(llvm::isa<const llvm::GlobalVariable>(expr)) { // Don't erase } else { tiler_error("Erasing", "Erasing undefined for the given expression"); } } /// Following function is inspired from lib/Transforms/Utils/LoopUnrollPeel.cpp /// /// \brief Clones the body of the loop L, putting it between \p InsertTop and \p /// InsertBot. FinalBot is the block to totally exit from all iterations. /// \param IterNumber The serial number of the iteration currently being /// peeled off. /// \param[out] NewBlocks A list of the the blocks in the newly created clone. /// \param[out] VMap The value map between the loop and the new clone. /// \param LoopBlocks A helper for DFS-traversal of the loop. /// \param LVMap A value-map that maps instructions from the original loop to /// instructions in the last peeled-off iteration. void cloneLoopBlocksAtEnd(llvm::Loop *L, unsigned IterNumber, llvm::BasicBlock *InsertTop, llvm::BasicBlock *InsertBot, llvm::BasicBlock *FinalBot, llvm::SmallVectorImpl<llvm::BasicBlock *> &NewBlocks, llvm::LoopBlocksDFS &LoopBlocks, llvm::ValueToValueMapTy &VMap, llvm::ValueToValueMapTy &LVMap, llvm::DominatorTree *DT, llvm::LoopInfo *LI) { llvm::BasicBlock *Header = L->getHeader(); llvm::BasicBlock *Latch = L->getLoopLatch(); llvm::Function *F = Header->getParent(); llvm::LoopBlocksDFS::RPOIterator BlockBegin = LoopBlocks.beginRPO(); llvm::LoopBlocksDFS::RPOIterator BlockEnd = LoopBlocks.endRPO(); llvm::Loop *ParentLoop = L->getParentLoop(); /* llvm::BasicBlock *PreHeader = L->getLoopPreheader(); llvm::errs() << "\nPreHeader Block\n\n"; PreHeader->print( llvm::errs() ); llvm::errs() << "\nTop Anchor\n\n"; InsertTop->print( llvm::errs() ); */ // For each block in the original loop, create a new copy, // and update the value map with the newly created values. for (llvm::LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { llvm::BasicBlock *NewBB = CloneBasicBlock(*BB, VMap, ".peel", F); NewBlocks.push_back(NewBB); if (ParentLoop) ParentLoop->addBasicBlockToLoop(NewBB, *LI); VMap[*BB] = NewBB; // If dominator tree is available, insert nodes to represent cloned blocks. if (DT) { if (Header == *BB) DT->addNewBlock(NewBB, InsertTop); else { llvm::DomTreeNode *IDom = DT->getNode(*BB)->getIDom(); // VMap must contain entry for IDom, as the iteration order is RPO. DT->addNewBlock(NewBB, llvm::cast<llvm::BasicBlock>(VMap[IDom->getBlock()])); } } /* llvm::errs() << "\n\n"; llvm::cast<llvm::BasicBlock>(*BB)->print( llvm::errs() ); llvm::errs() << "\n\n"; NewBB->print( llvm::errs() ); llvm::errs() << "\n\n"; */ } /* llvm::errs() << "\nBottom Anchor\n"; InsertBot->print( llvm::errs() ); llvm::errs() << "\nFinal Exit\n"; FinalBot->print( llvm::errs() ); */ // Hook-up the control flow for the newly inserted blocks. // The new header is hooked up directly to the "newexit", which is either // the original loop exit (for the first iteration) or the previous // iteration's exit block (for every other iteration) InsertTop->getTerminator()->setSuccessor(0, llvm::cast<llvm::BasicBlock>(VMap[Header])); // Similarly, for the latch: // The original exiting edge is still hooked up to the loop exit. // The backedge now goes to the "newexittop", which is either the copied exit // of the loop (for the last peeled iteration) or the copied exit of the next // iteration (for every other iteration) llvm::BasicBlock *NewLatch = llvm::cast<llvm::BasicBlock>(VMap[Latch]); llvm::BranchInst *NewLatchBR = llvm::cast<llvm::BranchInst>(NewLatch->getTerminator()); // llvm::errs() << "\nBranch Inst in Latch before setting successor\n"; // NewLatchBR->print( llvm::errs() ); unsigned HeaderIdx = (NewLatchBR->getSuccessor(0) == Header ? 0 : 1); NewLatchBR->setSuccessor(HeaderIdx, InsertBot); NewLatchBR->setSuccessor(1 - HeaderIdx, FinalBot); if (DT) DT->changeImmediateDominator(InsertBot, NewLatch); // llvm::errs() << "\nBranch Inst in Latch after setting successor\n"; // NewLatchBR->print( llvm::errs() ); // The new copy of the loop body starts with a bunch of PHI nodes // that pick an incoming value from the previous loop iteration. // Since this copy is no longer part of the loop, we resolve this statically: // For the first iteration, we use the value from the latch of the loop. // For any other iteration, we replace the phi with the value generated by // the immediately preceding clone of the loop body (which represents // the previous iteration). llvm::BasicBlock::iterator I = Header->begin(); for ( ; llvm::isa<llvm::PHINode>(I); ++I) { llvm::PHINode *NewPHI = llvm::cast<llvm::PHINode>(VMap[&*I]); llvm::Value *LatchVal = NewPHI->getIncomingValueForBlock(Latch); llvm::Instruction *LatchInst = llvm::dyn_cast<llvm::Instruction>(LatchVal); if (IterNumber == 0) { VMap[&*I] = LatchVal; // To be mapped to NS later } else { VMap[&*I] = LVMap[LatchInst]; // To be mapped to NS later } llvm::cast<llvm::BasicBlock>(VMap[Header])->getInstList().erase(NewPHI); } // Fix up the outgoing values - we need to add a value for the iteration // we've just created. Note that this must happen *after* the incoming // values are adjusted, since the value going out of the latch may also be // a value coming into the header. for (llvm::BasicBlock::iterator I = FinalBot->begin(); llvm::isa<llvm::PHINode>(I); ++I) { llvm::PHINode *PHI = llvm::cast<llvm::PHINode>(I); llvm::Value *LatchVal = PHI->getIncomingValueForBlock(Latch); llvm::Instruction *LatchInst = llvm::dyn_cast<llvm::Instruction>(LatchVal); if (LatchInst && L->contains(LatchInst)) LatchVal = VMap[LatchVal]; PHI->addIncoming(LatchVal, llvm::cast<llvm::BasicBlock>(VMap[Latch])); } // LastValueMap is updated with the values for the current loop // which are used the next time this function is called. for (const auto &KV : VMap) LVMap[KV.first] = KV.second; } /// Following function is inspired from lib/Transforms/Utils/LoopUnrollPeel.cpp /// /// \brief Peel off the last \p PeelCount iterations of loop \p L. /// /// Note that this does not peel them off as a single straight-line block. /// Rather, each iteration is peeled off separately, and needs to check the /// exit condition. bool myPeelLoop(llvm::Loop *L, unsigned PeelCount, llvm::LoopInfo *LI, llvm::ScalarEvolution *SE, llvm::DominatorTree *DT, llvm::AssumptionCache *AC, bool PreserveLCSSA, llvm::Value *N, llvm::Value *NS, llvm::Value *exitVal, int stepCnt, llvm::ValueToValueMapTy &LVMap, std::vector<llvm::BasicBlock*>& peeledBlocks) { // Only peeling single iteration is currently supported specifically for Advanced FPI if(PeelCount != 1) return false; // Make sure the loop is in simplified form if (!L->isLoopSimplifyForm()) return false; // Only peel loops that contain a single exit if (!L->getExitingBlock() || !L->getUniqueExitBlock()) return false; // Don't try to peel loops where the latch is not the exiting block. // This can be an indication of two different things: // 1) The loop is not rotated. // 2) The loop contains irreducible control flow that involves the latch. if (L->getLoopLatch() != L->getExitingBlock()) return false; llvm::LoopBlocksDFS LoopBlocks(L); LoopBlocks.perform(LI); llvm::BasicBlock *Header = L->getHeader(); llvm::BasicBlock *Latch = L->getLoopLatch(); llvm::BasicBlock *Exit = L->getUniqueExitBlock(); llvm::BranchInst *ExitBR = llvm::cast<llvm::BranchInst>(Exit->getTerminator()); llvm::BasicBlock *ExitSucc = ExitBR->getSuccessor(0); llvm::Function *F = Header->getParent(); /* llvm::BasicBlock *PreHeader = L->getLoopPreheader(); llvm::errs() << "\n\nPreHeader Block\n\n"; PreHeader->print( llvm::errs() ); llvm::errs() << "\n\nHeader Block\n\n"; Header->print( llvm::errs() ); llvm::errs() << "\n\nLatch Block\n\n"; Latch->print( llvm::errs() ); llvm::errs() << "\n\nExit Block\n\n"; Exit->print( llvm::errs() ); llvm::errs() << "\n\nExit Succcessor Block\n\n"; ExitSucc->print( llvm::errs() ); */ // Set up all the necessary basic blocks. It is convenient to split the // Exit into 3 parts - two blocks to anchor the peeled copy of the loop // body, and the final exit to skip subsequent iterations. // Peeling the last iteration transforms. // // PreHeader: // ... // Header: // LoopBody // If (cond) goto Header // Exit: // // into // // PreHeader: // ... // Header: // LoopBody // If (cond') goto Header // Exit: // InsertTop: // LoopBody // If (!cond) goto FinalBot // InsertBot: // FinalBot: // // Each following iteration will split the current bottom anchor "bottom" // in two, and put the new copy of the loop body between these two blocks. // That is, after peeling another iteration from the example above, we'll split // InsertBot, and get: // // PreHeader: // ... // Header: // LoopBody // If (cond') goto Header // Exit: // InsertTop: // LoopBody // If (!cond) goto FinalBot // InsertBot: // LoopBody // If (!cond) goto FinalBot // InsertBot.next: // FinalBot: llvm::BasicBlock *InsertTop = llvm::SplitEdge(Exit, ExitSucc, DT, LI); llvm::BasicBlock *InsertBot = llvm::SplitBlock(InsertTop, InsertTop->getTerminator(), DT, LI); llvm::BasicBlock *FinalBot = llvm::SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI); InsertTop->setName(Exit->getName() + ".peel.begin"); InsertBot->setName(Exit->getName() + ".peel.next"); FinalBot->setName(Exit->getName() + ".peel.final"); // Collect all the newly created blocks for future use llvm::SmallVector<llvm::BasicBlock *, 20> AllNewBlocks; AllNewBlocks.push_back(InsertTop); AllNewBlocks.push_back(InsertBot); AllNewBlocks.push_back(FinalBot); // For each peeled-off iteration, make a copy of the loop. for (unsigned Iter = 0; Iter < PeelCount; ++Iter) { llvm::SmallVector<llvm::BasicBlock *, 8> NewBlocks; llvm::ValueToValueMapTy VMap; // Clone the blocks in the loop and attach them after the loop cloneLoopBlocksAtEnd(L, Iter, InsertTop, InsertBot, FinalBot, NewBlocks, LoopBlocks, VMap, LVMap, DT, LI); if(NewBlocks.empty()) tiler_error("Cloning", "List of cloned blocks is empty"); // Remap to use values from the current iteration instead of the loop // iteration. VMap populated in above function call of cloneLoopBlocksAtEnd. llvm::remapInstructionsInBlocks(NewBlocks, VMap); // Collect all the newly created blocks for future use for(llvm::BasicBlock* b : NewBlocks) AllNewBlocks.push_back(b); InsertTop = InsertBot; if(PeelCount > 1) { // Subsequent splits only if more iterations are to be peeled InsertBot = llvm::SplitBlock(InsertBot, InsertBot->getTerminator(), DT, LI); InsertBot->setName(InsertTop->getName() + ".next"); AllNewBlocks.push_back(InsertBot); } else { /* llvm::BasicBlock *IBPred = InsertBot->getUniquePredecessor(); if(IBPred != NULL) { llvm::Instruction* term = IBPred->getTerminator(); if (llvm::BranchInst* bi = llvm::dyn_cast<llvm::BranchInst>(term)) { if(bi->isConditional()) { // Remove the conditional branch and add a unconditional branch llvm::IRBuilder<> b(term); b.CreateBr(FinalBot); llvm::Value *loopCond = bi->getCondition(); bi->eraseFromParent(); if( auto icmp = llvm::dyn_cast<llvm::ICmpInst>(loopCond) ) icmp->eraseFromParent(); // Detach the InsertBot Block InsertBot->getTerminator()->setSuccessor(0, NULL); } else {} } else {} } else {} auto position = std::find(AllNewBlocks.begin(), AllNewBlocks.end(), InsertBot); if (position != AllNewBlocks.end()) // == myVector.end() means the element was not found AllNewBlocks.erase(position); */ } // Attach the new cloned blocks in the basicblock list of the function F->getBasicBlockList().splice(InsertTop->getIterator(), F->getBasicBlockList(), NewBlocks[0]->getIterator(), F->end()); // Replace the loop counter in the peeled blocks with the approprite value llvm::PHINode *PHI = getInductionVariable(L, SE); llvm::Value *LatchVal = PHI->getIncomingValueForBlock(Latch); llvm::Instruction *LatchInst = llvm::dyn_cast<llvm::Instruction>(LatchVal); if (Iter > 0) { LatchVal = LVMap[LatchInst]; // To be mapped to NS later } llvm::ValueToValueMapTy VVMap; llvm::BranchInst *LatchBR = llvm::cast<llvm::BranchInst>(Latch->getTerminator()); if(!LatchBR) tiler_error("llvmUtils", "Latch block does not have unique term inst"); llvm::Value *loopCond = LatchBR->getCondition(); if( llvm::ICmpInst* icmp = llvm::dyn_cast<llvm::ICmpInst>(loopCond) ) { llvm::ValueToValueMapTy ExitVMap; if( PeelCount == 1 && llvm::isa<llvm::LoadInst>(exitVal) ) { llvm::LoadInst* load = llvm::dyn_cast<llvm::LoadInst>(exitVal); if(N == load->getOperand(0)) VVMap[LatchVal] = NS; } else if (N == exitVal && PeelCount == 1) { VVMap[LatchVal] = NS; } else { llvm::ValueToValueMapTy::iterator I; I = LVMap.find(icmp); if (I == LVMap.end()) tiler_error("Cloning","Value not in map"); llvm::ICmpInst* clIcmp = llvm::dyn_cast<llvm::ICmpInst>(I->second); llvm::Instruction* clExitVal = llvm::dyn_cast<llvm::Instruction>(exitVal); if (L->contains(clExitVal->getParent())) { I = LVMap.find(exitVal); if (I == LVMap.end()) tiler_error("Cloning","Value not in map"); if((clExitVal = llvm::dyn_cast<llvm::Instruction>(I->second))) { } else { assert(clExitVal && "Clone of exit value is not a instruction"); } } llvm::Instruction* clExitValp = NULL; llvm::Type *constValTy = clExitVal->getType(); if(constValTy->isPointerTy()) constValTy = constValTy->getPointerElementType(); llvm::Value* constVal = llvm::ConstantInt::get(constValTy, PeelCount-Iter); if(stepCnt > 0) clExitValp = llvm::BinaryOperator::Create(llvm::Instruction::Sub, clExitVal, constVal, "NewBound.peel"); else clExitValp = llvm::BinaryOperator::Create(llvm::Instruction::Add, clExitVal, constVal, "NewBound.peel"); clExitValp->insertBefore(clIcmp); VVMap[LatchVal] = clExitValp; } } else {} llvm::remapInstructionsInBlocks(AllNewBlocks, VVMap); } // Change the loop terminating condition in accordance with the peel count llvm::BranchInst *LatchBR = llvm::cast<llvm::BranchInst>(Latch->getTerminator()); if(!LatchBR) tiler_error("llvmUtils", "Latch block does not have unique term inst"); llvm::Value *loopCond = LatchBR->getCondition(); if( llvm::ICmpInst* icmp = llvm::dyn_cast<llvm::ICmpInst>(loopCond) ) { llvm::ValueToValueMapTy ExitVMap; if( llvm::LoadInst* load = llvm::dyn_cast<llvm::LoadInst>(exitVal) ) { if(N == load->getOperand(0)) ExitVMap[load] = NS; } else if (N == exitVal) { ExitVMap[N] = NS; } else { llvm::Type *constValTy = exitVal->getType(); if(constValTy->isPointerTy()) constValTy = constValTy->getPointerElementType(); llvm::Value* constVal = llvm::ConstantInt::get(constValTy, PeelCount); llvm::Instruction* exitValp = NULL; if(stepCnt > 0) exitValp = llvm::BinaryOperator::Create(llvm::Instruction::Sub, exitVal, constVal, "NewBound"); else exitValp = llvm::BinaryOperator::Create(llvm::Instruction::Add, exitVal, constVal, "NewBound"); exitValp->insertBefore(icmp); ExitVMap[exitVal] = exitValp; } llvm::RemapInstruction(icmp, ExitVMap, llvm::RF_IgnoreMissingLocals | llvm::RF_NoModuleLevelChanges); } else {} /* // Replace the loop counter in the peeled blocks with the approprite value // Multiple nodes will have to be mapped if PeelCount > 1 and not all such // nodes use the latch value but the value coming from the previous peel llvm::PHINode *PHI = getInductionVariable(L, SE); llvm::Value *LatchVal = PHI->getIncomingValueForBlock(Latch); llvm::ValueToValueMapTy VVMap; VVMap[LatchVal] = NS; // LatchVal will not work if PeelCount > 1 llvm::remapInstructionsInBlocks(AllNewBlocks, VVMap); */ // If the loop is nested, we changed the parent loop, update SE. if (llvm::Loop *ParentLoop = L->getParentLoop()) { SE->forgetLoop(ParentLoop); // FIXME: Incrementally update loop-simplify llvm::simplifyLoop(ParentLoop, DT, LI, SE, AC, PreserveLCSSA); } else { // FIXME: Incrementally update loop-simplify llvm::simplifyLoop(L, DT, LI, SE, AC, PreserveLCSSA); } // Collect all the newly created blocks for future use for(llvm::BasicBlock* b : AllNewBlocks) peeledBlocks.push_back(b); if(peeledBlocks.empty()) tiler_error("Cloning", "List of cloned blocks is empty"); return true; } // Following function is adapted from the llvm code since // llvm v 6.0 does not have this function in the LoopInfo.cpp llvm::BranchInst *getLoopGuardBR(llvm::Loop *L, bool isPeeled) { if (!L->isLoopSimplifyForm()) return NULL; llvm::BasicBlock *Preheader = L->getLoopPreheader(); assert(Preheader && L->getLoopLatch() && "Expecting a loop with valid preheader and latch"); // Loop should be in rotate form. // if (!L->isRotatedForm()) return NULL; // Above line commented since the call is not available in llvm v 6.0 // Disallow loops with more than one unique exit block, as we do not verify // that GuardOtherSucc post dominates all exit blocks. llvm::BasicBlock *ExitFromLatch = L->getUniqueExitBlock(); if (!ExitFromLatch) return NULL; llvm::BasicBlock *ExitFromLatchSucc = ExitFromLatch->getUniqueSuccessor(); if (!ExitFromLatchSucc) return NULL; llvm::BasicBlock *GuardBB = Preheader->getUniquePredecessor(); if (!GuardBB) return NULL; assert(GuardBB->getTerminator() && "Expecting valid guard terminator"); llvm::BranchInst *GuardBI = llvm::dyn_cast<llvm::BranchInst>(GuardBB->getTerminator()); if (!GuardBI || GuardBI->isUnconditional()) return NULL; llvm::BasicBlock *GuardOtherSucc = (GuardBI->getSuccessor(0) == Preheader) ? GuardBI->getSuccessor(1) : GuardBI->getSuccessor(0); // The following condition will not hold when loops are peeled if(isPeeled) return GuardBI; else return (GuardOtherSucc == ExitFromLatchSucc) ? GuardBI : NULL; } llvm::Value* getSingularNRef(llvm::Value* N, llvm::BasicBlock* entry_bb) { if(N == NULL || entry_bb == NULL) return NULL; llvm::Value* SingularNRef = NULL; if(llvm::isa<llvm::GlobalVariable>(N)) { for(auto it = entry_bb->begin(), e = entry_bb->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if(llvm::LoadInst *load = llvm::dyn_cast<llvm::LoadInst>(I) ) { if(N == load->getOperand(0)) { SingularNRef = load; break; } else {} } else {} } } else { SingularNRef = N; } if(SingularNRef == NULL) tiler_error("llvmUtils","Program Parameter is NULL"); return SingularNRef; } llvm::Instruction* generateNSVal(llvm::Value* N, llvm::Value* SingularNRef, llvm::BasicBlock* entry_bb) { if(N==NULL) return NULL; if(llvm::isa<llvm::GlobalVariable>(N)) { llvm::Type *oneTy = N->getType(); oneTy = oneTy->getPointerElementType(); llvm::Value *one = llvm::ConstantInt::get(oneTy, 1); if(SingularNRef == NULL) return NULL; llvm::LoadInst *Nload = llvm::dyn_cast<llvm::LoadInst>(SingularNRef); llvm::Instruction *NS = llvm::BinaryOperator::Create(llvm::Instruction::Sub, Nload, one, "NS"); NS->insertAfter(Nload); return NS; } else { if(entry_bb == NULL) return NULL; llvm::Type *oneTy = N->getType(); llvm::Value *one = llvm::ConstantInt::get(oneTy, 1); llvm::Instruction *NS = llvm::BinaryOperator::Create(llvm::Instruction::Sub, N, one, "NS"); NS->insertBefore(entry_bb->getFirstNonPHI()); return NS; } return NULL; } //---------------------------------------------------------------- // Cloning APIs llvm::BasicBlock* create_cloned_remapped_bb( const llvm::BasicBlock* basicBlock, const llvm::Twine& Name = "_aggr", llvm::Function* F = 0) { llvm::ValueToValueMapTy VMap; bb * clonedBB = llvm::CloneBasicBlock(basicBlock, VMap, Name, F); llvm::SmallVector<llvm::BasicBlock*,2> bbVec; bbVec.push_back(clonedBB); llvm::remapInstructionsInBlocks(bbVec, VMap); // remaps instructions return clonedBB; } // Pass p must declare it requires LoopInfoWrapperPass and // DominatorTreeWrapperPass std::vector<llvm::BasicBlock*> collect_cloned_loop_blocks(llvm::Pass *p, llvm::Loop *L, loopdata *ld) { if (!L->getExitingBlock() || !L->getUniqueExitBlock() || L->getLoopLatch() != L->getExitingBlock()) tiler_error("llvmUtils", "Loop does not have a unique exiting latch"); bb* preheader = L->getLoopPreheader(); bb* header = L->getHeader(); bb* latch = L->getLoopLatch(); bb* block_after_exit = NULL; llvm::Instruction* term = latch->getTerminator(); if(!term) tiler_error("llvmUtils", "Loop does not have unique term inst"); if (llvm::BranchInst *bi = llvm::dyn_cast<llvm::BranchInst>(term)) { const int NS = bi->getNumSuccessors(); for(int i=0; i<NS; i++) { bb* s = bi->getSuccessor(i); if(s != header) block_after_exit = s; } } else tiler_error("llvmUtils", "Cast of term inst to branch inst failed"); if(!block_after_exit) tiler_error("llvmUtils", "Block after the exiting loop not found"); llvm::ValueToValueMapTy VMap; auto &LIWP = p->getAnalysis<llvm::LoopInfoWrapperPass>(); auto LI = &LIWP.getLoopInfo(); auto &DTWP = p->getAnalysis<llvm::DominatorTreeWrapperPass>(); llvm::DominatorTree* DT = &DTWP.getDomTree(); llvm::SmallVector<llvm::BasicBlock *, 20> cloned_blocks; llvm::Loop* cl = cloneLoopWithPreheader(block_after_exit, preheader, L, VMap, "_clone", LI, DT, cloned_blocks); if(!cl) tiler_error("llvmUtils", "Unable to clone the preheader of the loop"); return to_std_vec(cloned_blocks); } llvm::AllocaInst* create_new_alloca(llvm::AllocaInst* arry_alloca) { llvm::IRBuilder<> alloca_builder(arry_alloca); llvm::AllocaInst* new_arry_alloca = alloca_builder.CreateAlloca(arry_alloca->getAllocatedType(), arry_alloca ->getArraySize()); return new_arry_alloca; } void remap_store(llvm::StoreInst* store, llvm::AllocaInst* arry_alloca, llvm::AllocaInst* new_arry_alloca) { auto addr = store->getOperand(1); llvm::BitCastInst* addr_bc = NULL; if( (addr_bc = llvm::dyn_cast<llvm::BitCastInst>(addr)) ) addr = addr_bc->getOperand(0); if( auto elemPtr = llvm::dyn_cast<llvm::GetElementPtrInst>(addr) ) { elemPtr->setOperand(0, new_arry_alloca); // llvm::ValueToValueMapTy VMap; // VMap[arry_alloca] = new_arry_alloca; /* auto idx = elemPtr->getOperand(1); if(elemPtr->getNumIndices() == 2) idx = elemPtr->getOperand(2); llvm::IRBuilder<> builder(elemPtr); llvm::GetElementPtrInst* new_elem_ptr = llvm::dyn_cast<llvm::GetElementPtrInst>(builder.CreateGEP(new_arry_alloca, idx)); elemPtr->removeFromParent(); */ } } void remap_load(llvm::LoadInst* load, llvm::AllocaInst* arry_alloca, llvm::AllocaInst* new_arry_alloca) { auto addr = load->getOperand(0); llvm::BitCastInst* addr_bc = NULL; if( (addr_bc = llvm::dyn_cast<llvm::BitCastInst>(addr)) ) addr = addr_bc->getOperand(0); if( auto elemPtr = llvm::dyn_cast<llvm::GetElementPtrInst>(addr) ) { elemPtr->setOperand(0, new_arry_alloca); /* llvm::ValueToValueMapTy VMap; VMap[arry_alloca] = new_arry_alloca; RemapInstruction(elemPtr, VMap); auto idx = elemPtr->getOperand(1); if(elemPtr->getNumIndices() == 2) idx = elemPtr->getOperand(2); llvm::IRBuilder<> builder(elemPtr); builder.CreateGEP(new_arry_alloca, idx); elemPtr->removeFromParent(); */ } } void add_equality_stmt(llvm::BasicBlock* bb, llvm::AllocaInst* prev_arry_alloca, llvm::AllocaInst* new_arry_alloca, llvm::LLVMContext& globalContext) { llvm::Instruction* term = bb->getTerminator(); if(!term) tiler_error("llvmUtils", "Preheader block does not have unique term inst"); llvm::IRBuilder<> b(term); llvm::Type *i32_ptr_type = llvm::IntegerType::getInt32PtrTy(globalContext); llvm::Value* constZero = llvm::ConstantInt::get(globalContext, llvm::APInt(64, 0, true)); llvm::GetElementPtrInst* prev_elem_ptr = llvm::dyn_cast<llvm::GetElementPtrInst>(b.CreateInBoundsGEP(prev_arry_alloca, constZero)); auto prev_elem_ptr_bc = b.CreateBitCast(prev_elem_ptr, i32_ptr_type); llvm::LoadInst* load = llvm::dyn_cast<llvm::LoadInst>(b.CreateLoad(prev_elem_ptr_bc)); llvm::GetElementPtrInst* new_elem_ptr = llvm::dyn_cast<llvm::GetElementPtrInst>(b.CreateInBoundsGEP(new_arry_alloca, constZero)); auto new_elem_ptr_bc = b.CreateBitCast(new_elem_ptr, i32_ptr_type); b.CreateStore(load, new_elem_ptr_bc); } //---------------------------------------------------------------------- // value_expr_map void value_expr_map::insert_term_map( const llvm::Value* op, z3::expr e ) { auto it = versions.find(op); if( it == versions.end() ) { insert_term_map( op, 0, e ); }else{ insert_term_map( op, (it->second).back() + 1, e ); } } void value_expr_map::insert_term_map( const llvm::Value* op, unsigned c_count, z3::expr e ) { auto it = versions.find(op); if( it == versions.end() ) { // assert( c_count == 0 ); }else{ assert( (it->second).back() < c_count); } versions[op].push_back( c_count ); auto pair = std::make_pair( std::make_pair( op, c_count ), e ); vmap.insert( pair ); } //insert_new_def with 2 param is alias of get_term z3::expr value_expr_map::insert_new_def( const llvm::Value* op, unsigned c_count ) { return get_term( op, c_count ); } z3::expr value_expr_map::insert_new_def( const llvm::Value* op ) { unsigned count = versions.find(op) == versions.end() ? 0 : versions[op].back() + 1; return insert_new_def( op, count ); } z3::expr value_expr_map::get_term( const llvm::Value* op, std::string op_name ) { z3::expr c = read_constant( op ); if( c ) return c; auto it = versions.find(op); if( it == versions.end() ) { // tiler_error("bmc", "call insert_new_def instead of get_term !!"); return get_term( op, 0, op_name ); }else{ return get_term(op, (it->second).back(), op_name ); } } z3::expr value_expr_map::get_term( const llvm::Value* op ) { z3::expr c = read_constant( op ); if( c ) return c; auto it = versions.find(op); if( it == versions.end() ) { // tiler_error("bmc", "call insert_new_def instead of get_term !!"); return get_term( op, 0 ); }else{ return get_term(op, (it->second).back() ); } } z3::expr value_expr_map::get_term( const llvm::Value* op, unsigned c_count, std::string op_name ) { z3::expr e = read_term( op, c_count ); if( e ) return e; // create new name z3::expr name = create_fresh_name( op, op_name ); insert_term_map( op, c_count, name ); return name; } z3::expr value_expr_map::get_term( const llvm::Value* op, unsigned c_count ) { z3::expr e = read_term( op, c_count ); if( e ) return e; // create new name z3::expr name = create_fresh_name( op ); insert_term_map( op, c_count, name ); return name; } z3::expr value_expr_map::get_earlier_term( const llvm::Value* op, unsigned c_count ) { z3::expr c = read_constant( op ); if( c ) return c; auto it = versions.find(op); if( it != versions.end() ) { auto vs = it->second; unsigned i = vs.size(); while( i > 0 ) { i--; if( vs[i] <= c_count ) { c_count = vs[i]; break; } } return read_term( op, c_count); } tiler_error( "llvmUtils", "versions of an LLVM value not found !!"); } z3::expr value_expr_map::create_fresh_name( const llvm::Value* op, std::string op_name ) { llvm::Type* ty = op->getType(); if( auto i_ty = llvm::dyn_cast<llvm::IntegerType>(ty) ) { int bw = i_ty->getBitWidth(); if(bw == 16 || bw == 32 || bw == 64 ) { z3::expr i = get_fresh_int(ctx, op_name, true); return i; }else if(bw == 1 || bw == 8) { z3::expr bit = get_fresh_bool(ctx, op_name, true); return bit; } } ty->print( llvm::errs() ); llvm::errs() << "\n"; tiler_error("llvmUtils", "unsupported type!!"); z3::expr e(ctx); return e; } z3::expr value_expr_map::create_fresh_name( const llvm::Value* op ) { llvm::Type* ty = op->getType(); if( auto i_ty = llvm::dyn_cast<llvm::IntegerType>(ty) ) { int bw = i_ty->getBitWidth(); if(bw == 16 || bw == 32 || bw == 64 ) { z3::expr i = get_fresh_int(ctx, op->getName().str()); return i; }else if(bw == 1 || bw == 8) { z3::expr bit = get_fresh_bool(ctx, op->getName().str()); return bit; } } ty->print( llvm::errs() ); llvm::errs() << "\n"; tiler_error("llvmUtils", "unsupported type!!"); z3::expr e(ctx); return e; } z3::expr value_expr_map::read_term( const llvm::Value* op, unsigned c_count ) { auto it = vmap.find( {op,c_count} ); if( it != vmap.end() ) { return it->second; }else{ z3::expr e(ctx); return e; // contains no expression; } } z3::expr value_expr_map::read_constant( const llvm::Value* op ) { return read_const(op, ctx); } unsigned value_expr_map::get_max_version( const llvm::Value* op ) { z3::expr c = read_constant( op ); if( c ) return 0; auto it = versions.find(op); if( it == versions.end() ) { // tiler_error("bmc", "call insert_new_def instead of get_term !!"); return 0; }else{ return (it->second).back(); } } const std::vector<unsigned>& value_expr_map::get_versions( const llvm::Value* op ) { z3::expr c = read_constant( op ); if( c ) return dummy_empty_versions; auto it = versions.find(op); if( it == versions.end() ) { // tiler_error("bmc", "call insert_new_def instead of get_term !!"); return dummy_empty_versions; }else{ return (it->second); } } // todo: violates invaiant of the system of multiple copies void value_expr_map::copy_values(value_expr_map& m) { for(auto it = vmap.begin(); it != vmap.end(); ++it) { m.insert_term_map(it->first.first, it->first.second, it->second); } } void value_expr_map::print( std::ostream& o ) { for(auto it = vmap.begin(); it != vmap.end(); ++it) { const llvm::Value* I = it->first.first; unsigned version = it->first.second; z3::expr val = it->second; LLVM_DUMP(I); o << I << " " << version << "~~>" << val << "\n"; } } inline void value_expr_map::dump() { print( std::cout ); } std::list<z3::expr> value_expr_map::get_expr_list() { std::list<z3::expr> l; for(auto it = vmap.begin(); it != vmap.end(); ++it) { l.push_back(it->second); } return l; } //---------------------------------------------------------------------- char fun_clonner_mod_pass::ID = 0; fun_clonner_mod_pass:: fun_clonner_mod_pass(options& o_, std::string ns, std::map<llvm::Function*, std::string>& fn_h_map, std::map<std::string, llvm::ValueToValueMapTy>& fwd_v2v_map, std::map<llvm::Function*, std::map<const llvm::Value*, const llvm::Value*>>& rev_v2v_map, std::map<const bb*, std::pair<std::vector<std::string>, std::vector<std::string> > >& bb_cmt_map_, bool mk_tgt ) : llvm::ModulePass(ID) , o(o_) , fn_hash_map(fn_h_map) , fwd_fn_v2v_map(fwd_v2v_map) , rev_fn_v2v_map(rev_v2v_map) , bb_cmt_map(bb_cmt_map_) { name_suffix = ns; make_target = mk_tgt; } bool fun_clonner_mod_pass::runOnModule(llvm::Module &M) { llvm::Function *F = M.getFunction(o.funcName); if(!F) { tiler_error("Cloning", "Function under analysis not present in the module"); } std::string hash_str = random_string(); llvm::ValueToValueMapTy& VMap = fwd_fn_v2v_map[hash_str]; llvm::Function* C_F = llvm::CloneFunction(F, VMap); assert(C_F); /* // Copy all pairs from the the temporary vmap to the permanent one for (auto &KV : VMap) fwd_fn_v2v_map[C_F][KV.first] = KV.second; */ fn_hash_map[C_F] = hash_str; C_F->setName(F->getName().str() + name_suffix); if(make_target) { // Clone is the new function under analysis o.funcName = F->getName().str() + name_suffix; } else {} // Clone is not immediately under analysis create_alloca_map(F, VMap, rev_fn_v2v_map[C_F]); if(make_target) { adjust_bb_cmt_map(VMap); } else {} // Pointers to blocks with comments are not shifted return true; } void fun_clonner_mod_pass:: create_alloca_map(llvm::Function* F, llvm::ValueToValueMapTy& fn_vmap, std::map<const llvm::Value*, const llvm::Value*>& alloca_map) { std::set<llvm::AllocaInst*> arr_set; collect_arr(*F, arr_set); for(auto arr_alloc : arr_set) { llvm::Value* mapped_alloc = fn_vmap[arr_alloc]; alloca_map[mapped_alloc] = arr_alloc; // arr_alloc->print( llvm::outs() ); // mapped_alloc->print( llvm::outs() ); } } void fun_clonner_mod_pass:: adjust_bb_cmt_map(llvm::ValueToValueMapTy& fn_vmap) { std::map<const bb*, std::pair<std::vector<std::string>, std::vector<std::string> > > cmt_map; for(auto it = bb_cmt_map.begin(); it!= bb_cmt_map.end(); it++) { llvm::WeakTrackingVH &c_b = fn_vmap[it->first]; bb* clonedBB; if ((clonedBB = llvm::dyn_cast<llvm::BasicBlock>(c_b))) { cmt_map[clonedBB] = it->second; bb_cmt_map.erase(it->first); } else { tiler_error("llvmUtils", "Casting of the block failed"); } } assert(bb_cmt_map.empty()); bb_cmt_map.insert(cmt_map.begin(), cmt_map.end()); } std::string fun_clonner_mod_pass::random_string() { std::string str("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); std::random_device rd; std::mt19937 generator(rd()); std::shuffle(str.begin(), str.end(), generator); return str.substr(0, 32); } llvm::StringRef fun_clonner_mod_pass::getPassName() const { return "Create a clone of the function with given name. Attach the suffix \ to the name of clone. Make this name as the target function name."; } //---------------------------------------------------------------------- char preprocess::ID = 0; preprocess::preprocess(std::unique_ptr<llvm::Module>& m, options& o_) : llvm::FunctionPass(ID) , module(m) , o(o_) {} preprocess::~preprocess() {} bool preprocess::runOnFunction( llvm::Function &f ) { if(f.getName() != o.funcName) return false; target_f = &f; // Get entry block entry_bb = &target_f->getEntryBlock(); // Identify the program parameter, error if a suitable value is not found N = find_ind_param_N(module, target_f, entry_bb); assert(N); // Global N create multiple load instruction, we remove those // and map thier uses to the load instruction in the entry block if(llvm::isa<llvm::GlobalVariable>(N)) { remove_glb_N_loads(); remove_unwanted_assume(); } check_nesting_depth(); return true; } void preprocess::remove_glb_N_loads() { for( auto it = entry_bb->begin(), e = entry_bb->end(); it != e; ++it) { llvm::Instruction *I = &(*it); if( llvm::LoadInst* load = llvm::dyn_cast<llvm::LoadInst>(I) ) { if(N == load->getOperand(0)) { N_load = load; } else {} } else {} } assert(N_load); if(N_load == NULL) tiler_error("preprocess", "First load of program parameter not found"); llvm::ValueToValueMapTy VMap; llvm::SmallVector<llvm::BasicBlock*, 20> blocks; llvm::SmallVector<llvm::LoadInst*, 20> removeLoads; for( auto& b : target_f->getBasicBlockList() ) { if( &b == entry_bb) continue; for( auto it = b.begin(), e = b.end(); it != e; ++it) { llvm::Instruction *I = &(*it); if( llvm::LoadInst* load = llvm::dyn_cast<llvm::LoadInst>(I) ) { if(N == load->getOperand(0)) { VMap[load] = N_load; blocks.push_back(&b); removeLoads.push_back(load); } else {} } else {} } } llvm::remapInstructionsInBlocks(blocks, VMap); for(auto load : removeLoads) load->eraseFromParent(); } void preprocess::remove_unwanted_assume() { llvm::Value* SingularNRef = NULL; if(llvm::isa<llvm::GlobalVariable>(N)) SingularNRef = N_load; else SingularNRef = N; for( auto& b : target_f->getBasicBlockList() ) { for( auto it = b.begin(), e = b.end(); it != e; ++it) { llvm::Instruction *I = &(*it); if(llvm::CallInst* call = llvm::dyn_cast<llvm::CallInst>(I)) { if( llvm::isa<llvm::IntrinsicInst>(call) ) continue; if( call->getNumArgOperands() <= 0 ) continue; if( is_assume_call(call) ) { auto op = llvm::dyn_cast<llvm::Instruction>(call->getArgOperand(0)); llvm::Instruction* cast1 = NULL; llvm::Instruction* cast2 = NULL; if( (cast1 = llvm::dyn_cast<llvm::CastInst>(op)) ) op = cast1; if(llvm::ICmpInst* icmp = llvm::dyn_cast<llvm::ICmpInst>(op->getOperand(0))) { bool erase = false; if(llvm::isa<llvm::Constant>(icmp->getOperand(1))) { auto icmpop = llvm::dyn_cast<llvm::Instruction>(icmp->getOperand(0)); if( (cast2 = llvm::dyn_cast<llvm::CastInst>(icmpop)) ) icmpop = llvm::dyn_cast<llvm::Instruction>(cast2->getOperand(0)); if(icmpop == SingularNRef) erase = true; } if(llvm::isa<llvm::Constant>(icmp->getOperand(0))) { auto icmpop = llvm::dyn_cast<llvm::Instruction>(icmp->getOperand(1)); if( (cast2 = llvm::dyn_cast<llvm::CastInst>(icmpop)) ) icmpop = llvm::dyn_cast<llvm::Instruction>(cast2->getOperand(0)); if(icmpop == SingularNRef) erase = true; } if(erase) { call->eraseFromParent(); cast1->eraseFromParent(); icmp->eraseFromParent(); cast2->eraseFromParent(); return; } } else {} } else {} } else {} } } } void preprocess::check_nesting_depth() { llvm::LoopInfo &LI = getAnalysis<llvm::LoopInfoWrapperPass>().getLoopInfo(); for (auto L = LI.rbegin(), E = LI.rend(); L != E; ++L) { // llvm::Loop *Lp = *L; for (llvm::Loop *SL : (*L)->getSubLoops()) { for (llvm::Loop *SSL : SL->getSubLoops()) { if(SSL) tiler_error("Preprocess", "Nesting depth greater than 2 is not supported"); } } } } llvm::StringRef preprocess::getPassName() const { return "Identify the program parameter, check input program \ sanity, remove unnecessary stmts, and so on"; } void preprocess::getAnalysisUsage(llvm::AnalysisUsage &au) const { au.addRequired<llvm::LoopInfoWrapperPass>(); } //-------------------------------------------------------------------------- char count_loops::ID = 0; count_loops::count_loops(std::unique_ptr<llvm::Module>& m, options& o_) : llvm::FunctionPass(ID) , module(m) , o(o_) {} count_loops::~count_loops() {} bool count_loops::runOnFunction( llvm::Function &f ) { if(f.getName() != o.funcName) return false; llvm::LoopInfo &LI = getAnalysis<llvm::LoopInfoWrapperPass>().getLoopInfo(); for (auto L = LI.rbegin(), E = LI.rend(); L != E; ++L) loop_count++; return false; } llvm::StringRef count_loops::getPassName() const { return "Counts the number of top level loops in the program"; } void count_loops::getAnalysisUsage(llvm::AnalysisUsage &au) const { au.addRequired<llvm::LoopInfoWrapperPass>(); } //-------------------------------------------------------------------------- void merge_mono( const llvm_mono& m1, const llvm_mono& m2, llvm_mono& m ) { auto it1 = m1.begin(); auto it2 = m2.begin(); while( it1 != m1.end() && it2 != m2.end() ) { const auto& v1 = it1->first; const auto& v2 = it2->first; if( v1 == v2 ) { int c = it1->second + it2->second; if( c ) m[v1] = c; it1++; it2++; }else if( v1 < v2 ) { m[v1] = it1->second; it2++; }else{ m[v2] = it2->second; it1++; } } while( it1 != m1.end() ) { m.insert( *it1 ); it1++; } while( it2 != m2.end() ) { m.insert( *it2 ); it2++; } } const llvm::DataLayout& getDataLayout( llvm::Instruction* I ) { return I->getParent()->getModule()->getDataLayout(); } llvm::Constant* make_one_constant( llvm::LLVMContext& ctx ) { auto* intType = llvm::IntegerType::get (ctx, 32); return llvm::ConstantInt::getSigned( intType , 1); } llvm::Constant* add_constants( llvm::Constant* c1, llvm::Constant* c2 , const llvm::DataLayout& DL ) { return llvm::ConstantFoldBinaryOpOperands( llvm::Instruction::Add, c1,c2,DL); } llvm::Constant* sub_constants( llvm::Constant* c1, llvm::Constant* c2 , const llvm::DataLayout& DL ) { return llvm::ConstantFoldBinaryOpOperands( llvm::Instruction::Sub, c1,c2,DL); } llvm::Constant* mul_constants( llvm::Constant* c1, llvm::Constant* c2 , const llvm::DataLayout& DL ) { return llvm::ConstantFoldBinaryOpOperands( llvm::Instruction::Mul, c1,c2,DL); } llvm::Constant* min_constant( llvm::Constant* c1, const llvm::DataLayout& DL) { auto* intType = llvm::IntegerType::get (c1->getContext(), 32); llvm::Constant* m1 = llvm::ConstantInt::getSigned( intType , -1); return llvm::ConstantFoldBinaryOpOperands( llvm::Instruction::Mul, m1,c1,DL); } bool is_zero( llvm::Constant* c1 ) { assert(c1); return c1->isZeroValue(); } bool is_eq( const llvm_mono& lhs, const llvm_mono& rhs ) { auto it1 = lhs.begin(); auto it2 = rhs.begin(); while( it1 != lhs.end() && it2 != rhs.end() ) { llvm::Value* i1 = it1->first; llvm::Value* i2 = it2->first; int c1 = it1->second; int c2 = it2->second; if( i1 == i2 && c1 == c2 ) { it1++; it2++; }else return false; } if( it1 != lhs.end() ) return false; if( it2 != rhs.end() ) return false; return true; } void sum_poly( llvm_poly& poly1, llvm_poly& poly2, llvm_poly& poly, const llvm::DataLayout& DL) { auto it1 = poly1.begin(); auto it2 = poly2.begin(); while( it1 != poly1.end() && it2 != poly2.end() ) { const llvm_mono& m1 = it1->first; const llvm_mono& m2 = it2->first; if( is_eq( m1, m2 ) ) { llvm::Constant* c = add_constants( it1->second, it2->second, DL); if( !is_zero(c) ) poly[m1] = c; it1++; it2++; }else if( compare_mono()(m1,m2) ) { poly[m1] = it1->second; it2++; }else{ poly[m2] = it2->second; it1++; } } while( it1 != poly1.end() ) { poly.insert( *it1 ); it1++; } while( it2 != poly2.end() ) { poly.insert( *it2 ); it2++; } } void sub_poly( llvm_poly& poly1, llvm_poly& poly2, llvm_poly& poly, const llvm::DataLayout& DL ) { auto it1 = poly1.begin(); auto it2 = poly2.begin(); while( it1 != poly1.end() && it2 != poly2.end() ) { const llvm_mono& m1 = it1->first; const llvm_mono& m2 = it2->first; if( is_eq( m1, m2 ) ) { llvm::Constant* c = sub_constants( it1->second, it2->second, DL); if( !is_zero(c) ) poly[m1] = c; it1++; it2++; }else if( compare_mono()(m1,m2) ) { poly[m1] = it1->second; it2++; }else{ poly[m2] = min_constant( it2->second, DL); it1++; } } while( it1 != poly1.end() ) { poly.insert( *it1 ); it1++; } while( it2 != poly2.end() ) { const llvm_mono& m2 = it2->first; poly[m2] = min_constant( it2->second, DL ); it2++; } } void mul_poly( llvm_poly& poly1, llvm_poly& poly2, llvm_poly& poly , const llvm::DataLayout& DL ) { for( auto it1 = poly1.begin(); it1 != poly1.end(); it1++ ) { const llvm_mono& m1 = it1->first; for( auto it2 = poly2.begin(); it2 != poly2.end(); it2++ ) { const llvm_mono& m2 = it2->first; llvm_mono m; merge_mono(m1,m2,m); llvm::Constant* c = mul_constants( it1->second, it2->second, DL); if( exists( poly, m) ) { llvm::Constant* c1 = add_constants( c, poly[m], DL ); if( is_zero(c1) ) { poly.erase(m); }else{ poly[m] = c1; } }else{ poly[m] = c; } } } } llvm_poly& get_simplified_polynomial( llvm::Value* I, std::map<llvm::Value*,llvm_poly>& poly_map, const llvm::DataLayout& DL ) { if( exists( poly_map, I ) ) return poly_map[I]; if(auto bop = llvm::dyn_cast<llvm::BinaryOperator>(I) ) { assert( bop ); auto op0 = bop->getOperand( 0 ); auto op1 = bop->getOperand( 1 ); llvm_poly& poly1 = get_simplified_polynomial( op0, poly_map, DL ); llvm_poly& poly2 = get_simplified_polynomial( op1, poly_map, DL ); llvm_poly& poly = poly_map[I];// construct the empty poly map unsigned op = bop->getOpcode(); switch( op ) { case llvm::Instruction::Add : sum_poly( poly1, poly2, poly, DL ); break; case llvm::Instruction::Sub : sub_poly( poly1, poly2, poly, DL ); break; case llvm::Instruction::Mul : mul_poly( poly1, poly2, poly, DL ); break; // case llvm::Instruction::And : // case llvm::Instruction::Or : // case llvm::Instruction::Xor : // case llvm::Instruction::SDiv: // case llvm::Instruction::UDiv: // case llvm::Instruction::SRem: // case llvm::Instruction::URem: // case llvm::Instruction::FAdd: // case llvm::Instruction::FSub: // case llvm::Instruction::FMul: // case llvm::Instruction::FDiv: // case llvm::Instruction::FRem: default: { const char* opName = bop->getOpcodeName(); tiler_error("simplfy polynomial", "unsupported instruction \"" << opName << "\" occurred!!"); } } }else if(auto cint = llvm::dyn_cast<llvm::ConstantInt>(I) ) { llvm_poly& p = poly_map[I]; llvm_mono m; p[m] = cint; } else if(auto load = llvm::dyn_cast<llvm::LoadInst>(I) ) { auto addr = load->getOperand(0); if( auto addr_bc = llvm::dyn_cast<llvm::BitCastInst>(addr) ) addr = addr_bc->getOperand(0); if( llvm::isa<llvm::GetElementPtrInst>(addr) ) tiler_error("simplfy polynomial", "array instructions unsupporetd supported in polys!!"); llvm_poly& p = poly_map[addr]; llvm_mono m; p[m] = make_one_constant( I->getContext() ); } else { LLVM_DUMP_MARKED( I ); tiler_error("simplfy polynomial", "unsupported instruction!!"); } return poly_map[I]; } // llvm_poly void get_simplified_polynomial( llvm::Value* I, const std::vector<llvm::Value*>& vars, const llvm::DataLayout& DL, llvm_poly& p ) { // const llvm::DataLayout& DL = getDataLayout(I); std::map<llvm::Value*,llvm_poly> poly_map; for( llvm::Value* v : vars ) { llvm_mono m; m[v] = 1; llvm_poly& poly = poly_map[v]; poly[m] = make_one_constant( I->getContext() ); } p = get_simplified_polynomial( I, poly_map, DL ); dump( p ); // return p; } void dump( const llvm_mono& m ) { for( auto pair : m ) { auto& v = pair.first; auto& power = pair.second; v->print( llvm::errs() );; std::cerr << power << "\n"; } } void dump( const llvm_poly& p ) { for( auto& pair : p ) { auto& m = pair.first; auto& coeff = pair.second; dump( m ); std::cerr << "\n"; coeff->print( llvm::errs() ); std::cerr << "\n"; } }
34.827503
191
0.612118
divyeshunadkat
f5e7fb6b5b4a64f49bd06875a5235830160f3ff3
46,697
cpp
C++
cmdstan/stan/lib/stan_math/test/unit/math/mix/mat/fun/operator_subtraction_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/test/unit/math/mix/mat/fun/operator_subtraction_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/test/unit/math/mix/mat/fun/operator_subtraction_test.cpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
#include <stan/math/mix/mat.hpp> #include <gtest/gtest.h> #include <test/unit/math/rev/mat/fun/util.hpp> using stan::math::fvar; TEST(AgradMixMatrixOperatorSubtraction,fv_scalar_matrix_1stDeriv) { using stan::math::subtract; using stan::math::matrix_fv; matrix_fv v(2,2); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; matrix_fv result; result = subtract(2.0,v); EXPECT_FLOAT_EQ(1.0,result(0,0).val_.val()); EXPECT_FLOAT_EQ(0.0,result(0,1).val_.val()); EXPECT_FLOAT_EQ(-1.0,result(1,0).val_.val()); EXPECT_FLOAT_EQ(-2.0,result(1,1).val_.val()); EXPECT_FLOAT_EQ(-1.0,result(0,0).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(0,1).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(1,0).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(1,1).d_.val()); result = subtract(v,2.0); EXPECT_FLOAT_EQ(-1.0,result(0,0).val_.val()); EXPECT_FLOAT_EQ(0.0,result(0,1).val_.val()); EXPECT_FLOAT_EQ(1.0,result(1,0).val_.val()); EXPECT_FLOAT_EQ(2.0,result(1,1).val_.val()); EXPECT_FLOAT_EQ(1.0,result(0,0).d_.val()); EXPECT_FLOAT_EQ(1.0,result(0,1).d_.val()); EXPECT_FLOAT_EQ(1.0,result(1,0).d_.val()); EXPECT_FLOAT_EQ(1.0,result(1,1).d_.val()); AVEC q = createAVEC(v(0,0).val(),v(0,1).val(),v(1,0).val(),v(1,1).val()); VEC h; result(0,0).val_.grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_scalar_matrix_2ndDeriv) { using stan::math::subtract; using stan::math::matrix_fv; matrix_fv v(2,2); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; matrix_fv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0,0).val(),v(0,1).val(),v(1,0).val(),v(1,1).val()); VEC h; result(0,0).d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_scalar_vector_1stDeriv) { using stan::math::subtract; using stan::math::vector_fv; vector_fv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; vector_fv result; result = subtract(2.0,v); EXPECT_FLOAT_EQ(1.0,result(0).val_.val()); EXPECT_FLOAT_EQ(0.0,result(1).val_.val()); EXPECT_FLOAT_EQ(-1.0,result(2).val_.val()); EXPECT_FLOAT_EQ(-2.0,result(3).val_.val()); EXPECT_FLOAT_EQ(-1.0,result(0).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(1).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(3).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(3).d_.val()); result = subtract(v,2.0); EXPECT_FLOAT_EQ(-1.0,result(0).val_.val()); EXPECT_FLOAT_EQ(0.0,result(1).val_.val()); EXPECT_FLOAT_EQ(1.0,result(2).val_.val()); EXPECT_FLOAT_EQ(2.0,result(3).val_.val()); EXPECT_FLOAT_EQ(1.0,result(0).d_.val()); EXPECT_FLOAT_EQ(1.0,result(1).d_.val()); EXPECT_FLOAT_EQ(1.0,result(3).d_.val()); EXPECT_FLOAT_EQ(1.0,result(3).d_.val()); AVEC q = createAVEC(v(0).val(),v(1).val(),v(2).val(),v(3).val()); VEC h; result(0).val_.grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_scalar_vector_2ndDeriv) { using stan::math::subtract; using stan::math::vector_fv; vector_fv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; vector_fv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0).val(),v(1).val(),v(2).val(),v(3).val()); VEC h; result(0).d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_scalar_rowvector_1stDeriv) { using stan::math::subtract; using stan::math::row_vector_fv; row_vector_fv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; row_vector_fv result; result = subtract(2.0,v); EXPECT_FLOAT_EQ(1.0,result(0).val_.val()); EXPECT_FLOAT_EQ(0.0,result(1).val_.val()); EXPECT_FLOAT_EQ(-1.0,result(2).val_.val()); EXPECT_FLOAT_EQ(-2.0,result(3).val_.val()); EXPECT_FLOAT_EQ(-1.0,result(0).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(1).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(3).d_.val()); EXPECT_FLOAT_EQ(-1.0,result(3).d_.val()); result = subtract(v,2.0); EXPECT_FLOAT_EQ(-1.0,result(0).val_.val()); EXPECT_FLOAT_EQ(0.0,result(1).val_.val()); EXPECT_FLOAT_EQ(1.0,result(2).val_.val()); EXPECT_FLOAT_EQ(2.0,result(3).val_.val()); EXPECT_FLOAT_EQ(1.0,result(0).d_.val()); EXPECT_FLOAT_EQ(1.0,result(1).d_.val()); EXPECT_FLOAT_EQ(1.0,result(3).d_.val()); EXPECT_FLOAT_EQ(1.0,result(3).d_.val()); AVEC q = createAVEC(v(0).val(),v(1).val(),v(2).val(),v(3).val()); VEC h; result(0).val_.grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_scalar_rowvector_2ndDeriv) { using stan::math::subtract; using stan::math::row_vector_fv; row_vector_fv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; row_vector_fv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0).val(),v(1).val(),v(2).val(),v(3).val()); VEC h; result(0).d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_vector_vector_1stDeriv) { using stan::math::subtract; using stan::math::vector_d; using stan::math::vector_fv; vector_d expected_output(5); vector_fv output; vector_d output_d; vector_d vd_1(5), vd_2(5); vector_fv vv_1(5), vv_2(5); vd_1 << 0, 2, -6, 10, 6; vv_1 << 0, 2, -6, 10, 6; vv_1(0).d_ = 1.0; vv_1(1).d_ = 1.0; vv_1(2).d_ = 1.0; vv_1(3).d_ = 1.0; vv_1(4).d_ = 1.0; vd_2 << 2, 3, 4, 5, 6; vv_2 << 2, 3, 4, 5, 6; vv_2(0).d_ = 1.0; vv_2(1).d_ = 1.0; vv_2(2).d_ = 1.0; vv_2(3).d_ = 1.0; vv_2(4).d_ = 1.0; expected_output << -2, -1, -10, 5, 0; output_d = subtract(vd_1, vd_2); EXPECT_FLOAT_EQ(expected_output(0), output_d(0)); EXPECT_FLOAT_EQ(expected_output(1), output_d(1)); EXPECT_FLOAT_EQ(expected_output(2), output_d(2)); EXPECT_FLOAT_EQ(expected_output(3), output_d(3)); EXPECT_FLOAT_EQ(expected_output(4), output_d(4)); output = subtract(vv_1, vd_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val()); EXPECT_FLOAT_EQ(1, output(0).d_.val()); EXPECT_FLOAT_EQ(1, output(1).d_.val()); EXPECT_FLOAT_EQ(1, output(2).d_.val()); EXPECT_FLOAT_EQ(1, output(3).d_.val()); EXPECT_FLOAT_EQ(1, output(4).d_.val()); output = subtract(vd_1, vv_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val()); EXPECT_FLOAT_EQ(-1.0, output(0).d_.val()); EXPECT_FLOAT_EQ(-1.0, output(1).d_.val()); EXPECT_FLOAT_EQ(-1.0, output(2).d_.val()); EXPECT_FLOAT_EQ(-1.0, output(3).d_.val()); EXPECT_FLOAT_EQ(-1.0, output(4).d_.val()); output = subtract(vv_1, vv_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val()); EXPECT_FLOAT_EQ(0, output(0).d_.val()); EXPECT_FLOAT_EQ(0, output(1).d_.val()); EXPECT_FLOAT_EQ(0, output(2).d_.val()); EXPECT_FLOAT_EQ(0, output(3).d_.val()); EXPECT_FLOAT_EQ(0, output(4).d_.val()); AVEC q = createAVEC(vv_1(0).val(),vv_1(1).val(),vv_1(2).val(),vv_1(3).val()); VEC h; output(0).val_.grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_vector_vector_2ndDeriv) { using stan::math::subtract; using stan::math::vector_d; using stan::math::vector_fv; vector_d expected_output(5); vector_fv output; vector_d output_d; vector_d vd_1(5), vd_2(5); vector_fv vv_1(5), vv_2(5); vd_1 << 0, 2, -6, 10, 6; vv_1 << 0, 2, -6, 10, 6; vv_1(0).d_ = 1.0; vv_1(1).d_ = 1.0; vv_1(2).d_ = 1.0; vv_1(3).d_ = 1.0; vv_1(4).d_ = 1.0; vd_2 << 2, 3, 4, 5, 6; vv_2 << 2, 3, 4, 5, 6; vv_2(0).d_ = 1.0; vv_2(1).d_ = 1.0; vv_2(2).d_ = 1.0; vv_2(3).d_ = 1.0; vv_2(4).d_ = 1.0; output = subtract(vv_1, vv_2); AVEC q = createAVEC(vv_1(0).val(),vv_1(1).val(),vv_1(2).val(),vv_1(3).val()); VEC h; output(0).d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_vector_vector_exception) { using stan::math::subtract; using stan::math::vector_d; using stan::math::vector_fv; vector_d d1(5), d2(1); vector_fv v1(5), v2(1); vector_fv output; EXPECT_THROW(subtract(d1, d2), std::invalid_argument); EXPECT_THROW(subtract(v1, d2), std::invalid_argument); EXPECT_THROW(subtract(d1, v2), std::invalid_argument); EXPECT_THROW(subtract(v1, v2), std::invalid_argument); } TEST(AgradMixMatrixOperatorSubtraction,fv_rowvector_rowvector_1stDeriv) { using stan::math::subtract; using stan::math::row_vector_d; using stan::math::row_vector_fv; row_vector_d expected_output(5); row_vector_d output_d; row_vector_fv output; row_vector_d rvd_1(5), rvd_2(5); row_vector_fv rvv_1(5), rvv_2(5); rvd_1 << 0, 2, -6, 10, 6; rvv_1 << 0, 2, -6, 10, 6; rvv_1(0).d_ = 1.0; rvv_1(1).d_ = 1.0; rvv_1(2).d_ = 1.0; rvv_1(3).d_ = 1.0; rvv_1(4).d_ = 1.0; rvd_2 << 2, 3, 4, 5, 6; rvv_2 << 2, 3, 4, 5, 6; rvv_2(0).d_ = 1.0; rvv_2(1).d_ = 1.0; rvv_2(2).d_ = 1.0; rvv_2(3).d_ = 1.0; rvv_2(4).d_ = 1.0; expected_output << -2, -1, -10, 5, 0; output_d = subtract(rvd_1, rvd_2); EXPECT_FLOAT_EQ(expected_output(0), output_d(0)); EXPECT_FLOAT_EQ(expected_output(1), output_d(1)); EXPECT_FLOAT_EQ(expected_output(2), output_d(2)); EXPECT_FLOAT_EQ(expected_output(3), output_d(3)); EXPECT_FLOAT_EQ(expected_output(4), output_d(4)); output = subtract(rvv_1, rvd_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val()); EXPECT_FLOAT_EQ(1, output(0).d_.val()); EXPECT_FLOAT_EQ(1, output(1).d_.val()); EXPECT_FLOAT_EQ(1, output(2).d_.val()); EXPECT_FLOAT_EQ(1, output(3).d_.val()); EXPECT_FLOAT_EQ(1, output(4).d_.val()); output = subtract(rvd_1, rvv_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val()); EXPECT_FLOAT_EQ(-1, output(0).d_.val()); EXPECT_FLOAT_EQ(-1, output(1).d_.val()); EXPECT_FLOAT_EQ(-1, output(2).d_.val()); EXPECT_FLOAT_EQ(-1, output(3).d_.val()); EXPECT_FLOAT_EQ(-1, output(4).d_.val()); output = subtract(rvv_1, rvv_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val()); EXPECT_FLOAT_EQ(0, output(0).d_.val()); EXPECT_FLOAT_EQ(0, output(1).d_.val()); EXPECT_FLOAT_EQ(0, output(2).d_.val()); EXPECT_FLOAT_EQ(0, output(3).d_.val()); EXPECT_FLOAT_EQ(0, output(4).d_.val()); AVEC q = createAVEC(rvv_1(0).val(),rvv_1(1).val(),rvv_1(2).val(),rvv_1(3).val()); VEC h; output(0).val_.grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_rowvector_rowvector_2ndDeriv) { using stan::math::subtract; using stan::math::row_vector_d; using stan::math::row_vector_fv; row_vector_d expected_output(5); row_vector_d output_d; row_vector_fv output; row_vector_d rvd_1(5), rvd_2(5); row_vector_fv rvv_1(5), rvv_2(5); rvd_1 << 0, 2, -6, 10, 6; rvv_1 << 0, 2, -6, 10, 6; rvv_1(0).d_ = 1.0; rvv_1(1).d_ = 1.0; rvv_1(2).d_ = 1.0; rvv_1(3).d_ = 1.0; rvv_1(4).d_ = 1.0; rvd_2 << 2, 3, 4, 5, 6; rvv_2 << 2, 3, 4, 5, 6; rvv_2(0).d_ = 1.0; rvv_2(1).d_ = 1.0; rvv_2(2).d_ = 1.0; rvv_2(3).d_ = 1.0; rvv_2(4).d_ = 1.0; output = subtract(rvv_1, rvv_2); AVEC q = createAVEC(rvv_1(0).val(),rvv_1(1).val(),rvv_1(2).val(),rvv_1(3).val()); VEC h; output(0).d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_rowvector_rowvector_exception) { using stan::math::subtract; using stan::math::row_vector_d; using stan::math::row_vector_fv; row_vector_d d1(5), d2(2); row_vector_fv v1(5), v2(2); row_vector_fv output; EXPECT_THROW(subtract(d1, d2), std::invalid_argument); EXPECT_THROW(subtract(d1, v2), std::invalid_argument); EXPECT_THROW(subtract(v1, d2), std::invalid_argument); EXPECT_THROW(subtract(v1, v2), std::invalid_argument); } TEST(AgradMixMatrixOperatorSubtraction,fv_matrix_matrix_1stDeriv) { using stan::math::subtract; using stan::math::matrix_d; using stan::math::matrix_fv; matrix_d expected_output(2,2); matrix_fv output; matrix_d md_1(2,2), md_2(2,2); matrix_fv mv_1(2,2), mv_2(2,2); matrix_d md_mis (2, 3); matrix_fv mv_mis (1, 1); md_1 << -10, 1, 10, 0; mv_1 << -10, 1, 10, 0; mv_1(0,0).d_ = 1.0; mv_1(0,1).d_ = 1.0; mv_1(1,0).d_ = 1.0; mv_1(1,1).d_ = 1.0; md_2 << 10, -10, 1, 2; mv_2 << 10, -10, 1, 2; mv_2(0,0).d_ = 1.0; mv_2(0,1).d_ = 1.0; mv_2(1,0).d_ = 1.0; mv_2(1,1).d_ = 1.0; expected_output << -20, 11, 9, -2; matrix_d output_d = subtract(md_1, md_2); EXPECT_FLOAT_EQ(expected_output(0,0), output_d(0,0)); EXPECT_FLOAT_EQ(expected_output(0,1), output_d(0,1)); EXPECT_FLOAT_EQ(expected_output(1,0), output_d(1,0)); EXPECT_FLOAT_EQ(expected_output(1,1), output_d(1,1)); output = subtract(mv_1, md_2); EXPECT_FLOAT_EQ(expected_output(0,0), output(0,0).val_.val()); EXPECT_FLOAT_EQ(expected_output(0,1), output(0,1).val_.val()); EXPECT_FLOAT_EQ(expected_output(1,0), output(1,0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1,1), output(1,1).val_.val()); EXPECT_FLOAT_EQ(1, output(0,0).d_.val()); EXPECT_FLOAT_EQ(1, output(0,1).d_.val()); EXPECT_FLOAT_EQ(1, output(1,0).d_.val()); EXPECT_FLOAT_EQ(1, output(1,1).d_.val()); output = subtract(md_1, mv_2); EXPECT_FLOAT_EQ(expected_output(0,0), output(0,0).val_.val()); EXPECT_FLOAT_EQ(expected_output(0,1), output(0,1).val_.val()); EXPECT_FLOAT_EQ(expected_output(1,0), output(1,0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1,1), output(1,1).val_.val()); EXPECT_FLOAT_EQ(-1, output(0,0).d_.val()); EXPECT_FLOAT_EQ(-1, output(0,1).d_.val()); EXPECT_FLOAT_EQ(-1, output(1,0).d_.val()); EXPECT_FLOAT_EQ(-1, output(1,1).d_.val()); output = subtract(mv_1, mv_2); EXPECT_FLOAT_EQ(expected_output(0,0), output(0,0).val_.val()); EXPECT_FLOAT_EQ(expected_output(0,1), output(0,1).val_.val()); EXPECT_FLOAT_EQ(expected_output(1,0), output(1,0).val_.val()); EXPECT_FLOAT_EQ(expected_output(1,1), output(1,1).val_.val()); EXPECT_FLOAT_EQ(0, output(0,0).d_.val()); EXPECT_FLOAT_EQ(0, output(0,1).d_.val()); EXPECT_FLOAT_EQ(0, output(1,0).d_.val()); EXPECT_FLOAT_EQ(0, output(1,1).d_.val()); AVEC q = createAVEC(mv_1(0,0).val(),mv_1(0,1).val(),mv_1(1,0).val(),mv_1(1,1).val()); VEC h; output(0,0).val_.grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_matrix_matrix_2ndDeriv) { using stan::math::subtract; using stan::math::matrix_d; using stan::math::matrix_fv; matrix_d expected_output(2,2); matrix_fv output; matrix_d md_1(2,2), md_2(2,2); matrix_fv mv_1(2,2), mv_2(2,2); matrix_d md_mis (2, 3); matrix_fv mv_mis (1, 1); md_1 << -10, 1, 10, 0; mv_1 << -10, 1, 10, 0; mv_1(0,0).d_ = 1.0; mv_1(0,1).d_ = 1.0; mv_1(1,0).d_ = 1.0; mv_1(1,1).d_ = 1.0; md_2 << 10, -10, 1, 2; mv_2 << 10, -10, 1, 2; mv_2(0,0).d_ = 1.0; mv_2(0,1).d_ = 1.0; mv_2(1,0).d_ = 1.0; mv_2(1,1).d_ = 1.0; output = subtract(mv_1, mv_2); AVEC q = createAVEC(mv_1(0,0).val(),mv_1(0,1).val(),mv_1(1,0).val(),mv_1(1,1).val()); VEC h; output(0,0).d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,fv_matrix_matrix_exception) { using stan::math::subtract; using stan::math::matrix_d; using stan::math::matrix_fv; matrix_d d1(2,2), d2(1,2); matrix_fv v1(2,2), v2(1,2); EXPECT_THROW(subtract(d1, d2), std::invalid_argument); EXPECT_THROW(subtract(d1, v2), std::invalid_argument); EXPECT_THROW(subtract(v1, d2), std::invalid_argument); EXPECT_THROW(subtract(v1, v2), std::invalid_argument); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_matrix_1stDeriv) { using stan::math::subtract; using stan::math::matrix_ffv; matrix_ffv v(2,2); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; matrix_ffv result; result = subtract(2.0,v); EXPECT_FLOAT_EQ(1.0,result(0,0).val_.val().val()); EXPECT_FLOAT_EQ(0.0,result(0,1).val_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(1,0).val_.val().val()); EXPECT_FLOAT_EQ(-2.0,result(1,1).val_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(0,0).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(0,1).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(1,0).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(1,1).d_.val().val()); result = subtract(v,2.0); EXPECT_FLOAT_EQ(-1.0,result(0,0).val_.val().val()); EXPECT_FLOAT_EQ(0.0,result(0,1).val_.val().val()); EXPECT_FLOAT_EQ(1.0,result(1,0).val_.val().val()); EXPECT_FLOAT_EQ(2.0,result(1,1).val_.val().val()); EXPECT_FLOAT_EQ(1.0,result(0,0).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(0,1).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(1,0).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(1,1).d_.val().val()); AVEC q = createAVEC(v(0,0).val().val(),v(0,1).val().val(),v(1,0).val().val(),v(1,1).val().val()); VEC h; result(0,0).val_.val().grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_matrix_2ndDeriv_1) { using stan::math::subtract; using stan::math::matrix_ffv; matrix_ffv v(2,2); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; matrix_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0,0).val().val(),v(0,1).val().val(),v(1,0).val().val(),v(1,1).val().val()); VEC h; result(0,0).val().d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_matrix_2ndDeriv_2) { using stan::math::subtract; using stan::math::matrix_ffv; matrix_ffv v(2,2); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; matrix_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0,0).val().val(),v(0,1).val().val(),v(1,0).val().val(),v(1,1).val().val()); VEC h; result(0,0).d_.val().grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_matrix_3rdDeriv) { using stan::math::subtract; using stan::math::matrix_ffv; matrix_ffv v(2,2); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; v(0).val_.d_ = 1.0; v(1).val_.d_ = 1.0; v(2).val_.d_ = 1.0; v(3).val_.d_ = 1.0; matrix_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0,0).val().val(),v(0,1).val().val(),v(1,0).val().val(),v(1,1).val().val()); VEC h; result(0,0).d_.d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_vector_1stDeriv) { using stan::math::subtract; using stan::math::vector_ffv; vector_ffv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; vector_ffv result; result = subtract(2.0,v); EXPECT_FLOAT_EQ(1.0,result(0).val_.val().val()); EXPECT_FLOAT_EQ(0.0,result(1).val_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(2).val_.val().val()); EXPECT_FLOAT_EQ(-2.0,result(3).val_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(0).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(1).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(3).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(3).d_.val().val()); result = subtract(v,2.0); EXPECT_FLOAT_EQ(-1.0,result(0).val_.val().val()); EXPECT_FLOAT_EQ(0.0,result(1).val_.val().val()); EXPECT_FLOAT_EQ(1.0,result(2).val_.val().val()); EXPECT_FLOAT_EQ(2.0,result(3).val_.val().val()); EXPECT_FLOAT_EQ(1.0,result(0).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(1).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(3).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(3).d_.val().val()); AVEC q = createAVEC(v(0).val().val(),v(1).val().val(),v(2).val().val(),v(3).val().val()); VEC h; result(0).val_.val().grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_vector_2ndDeriv_1) { using stan::math::subtract; using stan::math::vector_ffv; vector_ffv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; vector_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0).val().val(),v(1).val().val(),v(2).val().val(),v(3).val().val()); VEC h; result(0).val().d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_vector_2ndDeriv_2) { using stan::math::subtract; using stan::math::vector_ffv; vector_ffv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; vector_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0).val().val(),v(1).val().val(),v(2).val().val(),v(3).val().val()); VEC h; result(0).d_.val().grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_vector_3rdDeriv) { using stan::math::subtract; using stan::math::vector_ffv; vector_ffv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; v(0).val_.d_ = 1.0; v(1).val_.d_ = 1.0; v(2).val_.d_ = 1.0; v(3).val_.d_ = 1.0; vector_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0).val().val(),v(1).val().val(),v(2).val().val(),v(3).val().val()); VEC h; result(0).d_.d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_rowvector_1stDeriv) { using stan::math::subtract; using stan::math::row_vector_ffv; row_vector_ffv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; row_vector_ffv result; result = subtract(2.0,v); EXPECT_FLOAT_EQ(1.0,result(0).val_.val().val()); EXPECT_FLOAT_EQ(0.0,result(1).val_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(2).val_.val().val()); EXPECT_FLOAT_EQ(-2.0,result(3).val_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(0).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(1).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(3).d_.val().val()); EXPECT_FLOAT_EQ(-1.0,result(3).d_.val().val()); result = subtract(v,2.0); EXPECT_FLOAT_EQ(-1.0,result(0).val_.val().val()); EXPECT_FLOAT_EQ(0.0,result(1).val_.val().val()); EXPECT_FLOAT_EQ(1.0,result(2).val_.val().val()); EXPECT_FLOAT_EQ(2.0,result(3).val_.val().val()); EXPECT_FLOAT_EQ(1.0,result(0).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(1).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(3).d_.val().val()); EXPECT_FLOAT_EQ(1.0,result(3).d_.val().val()); AVEC q = createAVEC(v(0).val().val(),v(1).val().val(),v(2).val().val(),v(3).val().val()); VEC h; result(0).val_.val().grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_rowvector_2ndDeriv_1) { using stan::math::subtract; using stan::math::row_vector_ffv; row_vector_ffv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; row_vector_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0).val().val(),v(1).val().val(),v(2).val().val(),v(3).val().val()); VEC h; result(0).val().d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_rowvector_2ndDeriv_2) { using stan::math::subtract; using stan::math::row_vector_ffv; row_vector_ffv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; row_vector_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0).val().val(),v(1).val().val(),v(2).val().val(),v(3).val().val()); VEC h; result(0).d_.val().grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_scalar_rowvector_3rdDeriv) { using stan::math::subtract; using stan::math::row_vector_ffv; row_vector_ffv v(4); v << 1, 2, 3, 4; v(0).d_ = 1.0; v(1).d_ = 1.0; v(2).d_ = 1.0; v(3).d_ = 1.0; v(0).val_.d_ = 1.0; v(1).val_.d_ = 1.0; v(2).val_.d_ = 1.0; v(3).val_.d_ = 1.0; row_vector_ffv result; result = subtract(v,2.0); AVEC q = createAVEC(v(0).val().val(),v(1).val().val(),v(2).val().val(),v(3).val().val()); VEC h; result(0).d_.d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_vector_vector_1stDeriv) { using stan::math::subtract; using stan::math::vector_d; using stan::math::vector_ffv; vector_d expected_output(5); vector_ffv output; vector_d output_d; vector_d vd_1(5), vd_2(5); vector_ffv vv_1(5), vv_2(5); vd_1 << 0, 2, -6, 10, 6; vv_1 << 0, 2, -6, 10, 6; vv_1(0).d_ = 1.0; vv_1(1).d_ = 1.0; vv_1(2).d_ = 1.0; vv_1(3).d_ = 1.0; vv_1(4).d_ = 1.0; vd_2 << 2, 3, 4, 5, 6; vv_2 << 2, 3, 4, 5, 6; vv_2(0).d_ = 1.0; vv_2(1).d_ = 1.0; vv_2(2).d_ = 1.0; vv_2(3).d_ = 1.0; vv_2(4).d_ = 1.0; expected_output << -2, -1, -10, 5, 0; output_d = subtract(vd_1, vd_2); EXPECT_FLOAT_EQ(expected_output(0), output_d(0)); EXPECT_FLOAT_EQ(expected_output(1), output_d(1)); EXPECT_FLOAT_EQ(expected_output(2), output_d(2)); EXPECT_FLOAT_EQ(expected_output(3), output_d(3)); EXPECT_FLOAT_EQ(expected_output(4), output_d(4)); output = subtract(vv_1, vd_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val().val()); EXPECT_FLOAT_EQ(1, output(0).d_.val().val()); EXPECT_FLOAT_EQ(1, output(1).d_.val().val()); EXPECT_FLOAT_EQ(1, output(2).d_.val().val()); EXPECT_FLOAT_EQ(1, output(3).d_.val().val()); EXPECT_FLOAT_EQ(1, output(4).d_.val().val()); output = subtract(vd_1, vv_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val().val()); EXPECT_FLOAT_EQ(-1.0, output(0).d_.val().val()); EXPECT_FLOAT_EQ(-1.0, output(1).d_.val().val()); EXPECT_FLOAT_EQ(-1.0, output(2).d_.val().val()); EXPECT_FLOAT_EQ(-1.0, output(3).d_.val().val()); EXPECT_FLOAT_EQ(-1.0, output(4).d_.val().val()); output = subtract(vv_1, vv_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val().val()); EXPECT_FLOAT_EQ(0, output(0).d_.val().val()); EXPECT_FLOAT_EQ(0, output(1).d_.val().val()); EXPECT_FLOAT_EQ(0, output(2).d_.val().val()); EXPECT_FLOAT_EQ(0, output(3).d_.val().val()); EXPECT_FLOAT_EQ(0, output(4).d_.val().val()); AVEC q = createAVEC(vv_1(0).val().val(),vv_1(1).val().val(),vv_1(2).val().val(),vv_1(3).val().val()); VEC h; output(0).val_.val().grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_vector_vector_2ndDeriv_1) { using stan::math::subtract; using stan::math::vector_d; using stan::math::vector_ffv; vector_d expected_output(5); vector_ffv output; vector_d output_d; vector_d vd_1(5), vd_2(5); vector_ffv vv_1(5), vv_2(5); vd_1 << 0, 2, -6, 10, 6; vv_1 << 0, 2, -6, 10, 6; vv_1(0).d_ = 1.0; vv_1(1).d_ = 1.0; vv_1(2).d_ = 1.0; vv_1(3).d_ = 1.0; vv_1(4).d_ = 1.0; vd_2 << 2, 3, 4, 5, 6; vv_2 << 2, 3, 4, 5, 6; vv_2(0).d_ = 1.0; vv_2(1).d_ = 1.0; vv_2(2).d_ = 1.0; vv_2(3).d_ = 1.0; vv_2(4).d_ = 1.0; output = subtract(vv_1, vv_2); AVEC q = createAVEC(vv_1(0).val().val(),vv_1(1).val().val(),vv_1(2).val().val(),vv_1(3).val().val()); VEC h; output(0).val().d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_vector_vector_2ndDeriv_2) { using stan::math::subtract; using stan::math::vector_d; using stan::math::vector_ffv; vector_d expected_output(5); vector_ffv output; vector_d output_d; vector_d vd_1(5), vd_2(5); vector_ffv vv_1(5), vv_2(5); vd_1 << 0, 2, -6, 10, 6; vv_1 << 0, 2, -6, 10, 6; vv_1(0).d_ = 1.0; vv_1(1).d_ = 1.0; vv_1(2).d_ = 1.0; vv_1(3).d_ = 1.0; vv_1(4).d_ = 1.0; vd_2 << 2, 3, 4, 5, 6; vv_2 << 2, 3, 4, 5, 6; vv_2(0).d_ = 1.0; vv_2(1).d_ = 1.0; vv_2(2).d_ = 1.0; vv_2(3).d_ = 1.0; vv_2(4).d_ = 1.0; output = subtract(vv_1, vv_2); AVEC q = createAVEC(vv_1(0).val().val(),vv_1(1).val().val(),vv_1(2).val().val(),vv_1(3).val().val()); VEC h; output(0).d_.val().grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_vector_vector_3rdDeriv) { using stan::math::subtract; using stan::math::vector_d; using stan::math::vector_ffv; vector_d expected_output(5); vector_ffv output; vector_d output_d; vector_d vd_1(5), vd_2(5); vector_ffv vv_1(5), vv_2(5); vd_1 << 0, 2, -6, 10, 6; vv_1 << 0, 2, -6, 10, 6; vv_1(0).d_ = 1.0; vv_1(1).d_ = 1.0; vv_1(2).d_ = 1.0; vv_1(3).d_ = 1.0; vv_1(4).d_ = 1.0; vv_1(0).val_.d_ = 1.0; vv_1(1).val_.d_ = 1.0; vv_1(2).val_.d_ = 1.0; vv_1(3).val_.d_ = 1.0; vv_1(4).val_.d_ = 1.0; vd_2 << 2, 3, 4, 5, 6; vv_2 << 2, 3, 4, 5, 6; vv_2(0).d_ = 1.0; vv_2(1).d_ = 1.0; vv_2(2).d_ = 1.0; vv_2(3).d_ = 1.0; vv_2(4).d_ = 1.0; vv_2(0).val_.d_ = 1.0; vv_2(1).val_.d_ = 1.0; vv_2(2).val_.d_ = 1.0; vv_2(3).val_.d_ = 1.0; vv_2(4).val_.d_ = 1.0; output = subtract(vv_1, vv_2); AVEC q = createAVEC(vv_1(0).val().val(),vv_1(1).val().val(),vv_1(2).val().val(),vv_1(3).val().val()); VEC h; output(0).d_.d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_vector_vector_exception) { using stan::math::subtract; using stan::math::vector_d; using stan::math::vector_ffv; vector_d d1(5), d2(1); vector_ffv v1(5), v2(1); vector_ffv output; EXPECT_THROW(subtract(d1, d2), std::invalid_argument); EXPECT_THROW(subtract(v1, d2), std::invalid_argument); EXPECT_THROW(subtract(d1, v2), std::invalid_argument); EXPECT_THROW(subtract(v1, v2), std::invalid_argument); } TEST(AgradMixMatrixOperatorSubtraction,ffv_rowvector_rowvector_1stDeriv) { using stan::math::subtract; using stan::math::row_vector_d; using stan::math::row_vector_ffv; row_vector_d expected_output(5); row_vector_d output_d; row_vector_ffv output; row_vector_d rvd_1(5), rvd_2(5); row_vector_ffv rvv_1(5), rvv_2(5); rvd_1 << 0, 2, -6, 10, 6; rvv_1 << 0, 2, -6, 10, 6; rvv_1(0).d_ = 1.0; rvv_1(1).d_ = 1.0; rvv_1(2).d_ = 1.0; rvv_1(3).d_ = 1.0; rvv_1(4).d_ = 1.0; rvd_2 << 2, 3, 4, 5, 6; rvv_2 << 2, 3, 4, 5, 6; rvv_2(0).d_ = 1.0; rvv_2(1).d_ = 1.0; rvv_2(2).d_ = 1.0; rvv_2(3).d_ = 1.0; rvv_2(4).d_ = 1.0; expected_output << -2, -1, -10, 5, 0; output_d = subtract(rvd_1, rvd_2); EXPECT_FLOAT_EQ(expected_output(0), output_d(0)); EXPECT_FLOAT_EQ(expected_output(1), output_d(1)); EXPECT_FLOAT_EQ(expected_output(2), output_d(2)); EXPECT_FLOAT_EQ(expected_output(3), output_d(3)); EXPECT_FLOAT_EQ(expected_output(4), output_d(4)); output = subtract(rvv_1, rvd_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val().val()); EXPECT_FLOAT_EQ(1, output(0).d_.val().val()); EXPECT_FLOAT_EQ(1, output(1).d_.val().val()); EXPECT_FLOAT_EQ(1, output(2).d_.val().val()); EXPECT_FLOAT_EQ(1, output(3).d_.val().val()); EXPECT_FLOAT_EQ(1, output(4).d_.val().val()); output = subtract(rvd_1, rvv_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val().val()); EXPECT_FLOAT_EQ(-1, output(0).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(1).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(2).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(3).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(4).d_.val().val()); output = subtract(rvv_1, rvv_2); EXPECT_FLOAT_EQ(expected_output(0), output(0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1), output(1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(2), output(2).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(3), output(3).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(4), output(4).val_.val().val()); EXPECT_FLOAT_EQ(0, output(0).d_.val().val()); EXPECT_FLOAT_EQ(0, output(1).d_.val().val()); EXPECT_FLOAT_EQ(0, output(2).d_.val().val()); EXPECT_FLOAT_EQ(0, output(3).d_.val().val()); EXPECT_FLOAT_EQ(0, output(4).d_.val().val()); AVEC q = createAVEC(rvv_1(0).val().val(),rvv_1(1).val().val(),rvv_1(2).val().val(),rvv_1(3).val().val()); VEC h; output(0).val_.val().grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_rowvector_rowvector_2ndDeriv_1) { using stan::math::subtract; using stan::math::row_vector_d; using stan::math::row_vector_ffv; row_vector_d expected_output(5); row_vector_d output_d; row_vector_ffv output; row_vector_d rvd_1(5), rvd_2(5); row_vector_ffv rvv_1(5), rvv_2(5); rvd_1 << 0, 2, -6, 10, 6; rvv_1 << 0, 2, -6, 10, 6; rvv_1(0).d_ = 1.0; rvv_1(1).d_ = 1.0; rvv_1(2).d_ = 1.0; rvv_1(3).d_ = 1.0; rvv_1(4).d_ = 1.0; rvd_2 << 2, 3, 4, 5, 6; rvv_2 << 2, 3, 4, 5, 6; rvv_2(0).d_ = 1.0; rvv_2(1).d_ = 1.0; rvv_2(2).d_ = 1.0; rvv_2(3).d_ = 1.0; rvv_2(4).d_ = 1.0; output = subtract(rvv_1, rvv_2); AVEC q = createAVEC(rvv_1(0).val().val(),rvv_1(1).val().val(),rvv_1(2).val().val(),rvv_1(3).val().val()); VEC h; output(0).val().d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_rowvector_rowvector_2ndDeriv_2) { using stan::math::subtract; using stan::math::row_vector_d; using stan::math::row_vector_ffv; row_vector_d expected_output(5); row_vector_d output_d; row_vector_ffv output; row_vector_d rvd_1(5), rvd_2(5); row_vector_ffv rvv_1(5), rvv_2(5); rvd_1 << 0, 2, -6, 10, 6; rvv_1 << 0, 2, -6, 10, 6; rvv_1(0).d_ = 1.0; rvv_1(1).d_ = 1.0; rvv_1(2).d_ = 1.0; rvv_1(3).d_ = 1.0; rvv_1(4).d_ = 1.0; rvd_2 << 2, 3, 4, 5, 6; rvv_2 << 2, 3, 4, 5, 6; rvv_2(0).d_ = 1.0; rvv_2(1).d_ = 1.0; rvv_2(2).d_ = 1.0; rvv_2(3).d_ = 1.0; rvv_2(4).d_ = 1.0; output = subtract(rvv_1, rvv_2); AVEC q = createAVEC(rvv_1(0).val().val(),rvv_1(1).val().val(),rvv_1(2).val().val(),rvv_1(3).val().val()); VEC h; output(0).d_.val().grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_rowvector_rowvector_3rdDeriv) { using stan::math::subtract; using stan::math::row_vector_d; using stan::math::row_vector_ffv; row_vector_d expected_output(5); row_vector_d output_d; row_vector_ffv output; row_vector_d rvd_1(5), rvd_2(5); row_vector_ffv rvv_1(5), rvv_2(5); rvd_1 << 0, 2, -6, 10, 6; rvv_1 << 0, 2, -6, 10, 6; rvv_1(0).d_ = 1.0; rvv_1(1).d_ = 1.0; rvv_1(2).d_ = 1.0; rvv_1(3).d_ = 1.0; rvv_1(4).d_ = 1.0; rvv_1(0).val_.d_ = 1.0; rvv_1(1).val_.d_ = 1.0; rvv_1(2).val_.d_ = 1.0; rvv_1(3).val_.d_ = 1.0; rvv_1(4).val_.d_ = 1.0; rvd_2 << 2, 3, 4, 5, 6; rvv_2 << 2, 3, 4, 5, 6; rvv_2(0).d_ = 1.0; rvv_2(1).d_ = 1.0; rvv_2(2).d_ = 1.0; rvv_2(3).d_ = 1.0; rvv_2(4).d_ = 1.0; rvv_2(0).val_.d_ = 1.0; rvv_2(1).val_.d_ = 1.0; rvv_2(2).val_.d_ = 1.0; rvv_2(3).val_.d_ = 1.0; rvv_2(4).val_.d_ = 1.0; output = subtract(rvv_1, rvv_2); AVEC q = createAVEC(rvv_1(0).val().val(),rvv_1(1).val().val(),rvv_1(2).val().val(),rvv_1(3).val().val()); VEC h; output(0).d_.d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_rowvector_rowvector_exception) { using stan::math::subtract; using stan::math::row_vector_d; using stan::math::row_vector_ffv; row_vector_d d1(5), d2(2); row_vector_ffv v1(5), v2(2); row_vector_ffv output; EXPECT_THROW(subtract(d1, d2), std::invalid_argument); EXPECT_THROW(subtract(d1, v2), std::invalid_argument); EXPECT_THROW(subtract(v1, d2), std::invalid_argument); EXPECT_THROW(subtract(v1, v2), std::invalid_argument); } TEST(AgradMixMatrixOperatorSubtraction,ffv_matrix_matrix_1stDeriv) { using stan::math::subtract; using stan::math::matrix_d; using stan::math::matrix_ffv; matrix_d expected_output(2,2); matrix_ffv output; matrix_d md_1(2,2), md_2(2,2); matrix_ffv mv_1(2,2), mv_2(2,2); matrix_d md_mis (2, 3); matrix_ffv mv_mis (1, 1); md_1 << -10, 1, 10, 0; mv_1 << -10, 1, 10, 0; mv_1(0,0).d_ = 1.0; mv_1(0,1).d_ = 1.0; mv_1(1,0).d_ = 1.0; mv_1(1,1).d_ = 1.0; md_2 << 10, -10, 1, 2; mv_2 << 10, -10, 1, 2; mv_2(0,0).d_ = 1.0; mv_2(0,1).d_ = 1.0; mv_2(1,0).d_ = 1.0; mv_2(1,1).d_ = 1.0; expected_output << -20, 11, 9, -2; matrix_d output_d = subtract(md_1, md_2); EXPECT_FLOAT_EQ(expected_output(0,0), output_d(0,0)); EXPECT_FLOAT_EQ(expected_output(0,1), output_d(0,1)); EXPECT_FLOAT_EQ(expected_output(1,0), output_d(1,0)); EXPECT_FLOAT_EQ(expected_output(1,1), output_d(1,1)); output = subtract(mv_1, md_2); EXPECT_FLOAT_EQ(expected_output(0,0), output(0,0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(0,1), output(0,1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1,0), output(1,0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1,1), output(1,1).val_.val().val()); EXPECT_FLOAT_EQ(1, output(0,0).d_.val().val()); EXPECT_FLOAT_EQ(1, output(0,1).d_.val().val()); EXPECT_FLOAT_EQ(1, output(1,0).d_.val().val()); EXPECT_FLOAT_EQ(1, output(1,1).d_.val().val()); output = subtract(md_1, mv_2); EXPECT_FLOAT_EQ(expected_output(0,0), output(0,0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(0,1), output(0,1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1,0), output(1,0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1,1), output(1,1).val_.val().val()); EXPECT_FLOAT_EQ(-1, output(0,0).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(0,1).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(1,0).d_.val().val()); EXPECT_FLOAT_EQ(-1, output(1,1).d_.val().val()); output = subtract(mv_1, mv_2); EXPECT_FLOAT_EQ(expected_output(0,0), output(0,0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(0,1), output(0,1).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1,0), output(1,0).val_.val().val()); EXPECT_FLOAT_EQ(expected_output(1,1), output(1,1).val_.val().val()); EXPECT_FLOAT_EQ(0, output(0,0).d_.val().val()); EXPECT_FLOAT_EQ(0, output(0,1).d_.val().val()); EXPECT_FLOAT_EQ(0, output(1,0).d_.val().val()); EXPECT_FLOAT_EQ(0, output(1,1).d_.val().val()); AVEC q = createAVEC(mv_1(0,0).val().val(),mv_1(0,1).val().val(),mv_1(1,0).val().val(),mv_1(1,1).val().val()); VEC h; output(0,0).val_.val().grad(q,h); EXPECT_FLOAT_EQ(1,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_matrix_matrix_2ndDeriv_1) { using stan::math::subtract; using stan::math::matrix_d; using stan::math::matrix_ffv; matrix_d expected_output(2,2); matrix_ffv output; matrix_d md_1(2,2), md_2(2,2); matrix_ffv mv_1(2,2), mv_2(2,2); matrix_d md_mis (2, 3); matrix_ffv mv_mis (1, 1); md_1 << -10, 1, 10, 0; mv_1 << -10, 1, 10, 0; mv_1(0,0).d_ = 1.0; mv_1(0,1).d_ = 1.0; mv_1(1,0).d_ = 1.0; mv_1(1,1).d_ = 1.0; md_2 << 10, -10, 1, 2; mv_2 << 10, -10, 1, 2; mv_2(0,0).d_ = 1.0; mv_2(0,1).d_ = 1.0; mv_2(1,0).d_ = 1.0; mv_2(1,1).d_ = 1.0; output = subtract(mv_1, mv_2); AVEC q = createAVEC(mv_1(0,0).val().val(),mv_1(0,1).val().val(),mv_1(1,0).val().val(),mv_1(1,1).val().val()); VEC h; output(0,0).val().d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_matrix_matrix_2ndDeriv_2) { using stan::math::subtract; using stan::math::matrix_d; using stan::math::matrix_ffv; matrix_d expected_output(2,2); matrix_ffv output; matrix_d md_1(2,2), md_2(2,2); matrix_ffv mv_1(2,2), mv_2(2,2); matrix_d md_mis (2, 3); matrix_ffv mv_mis (1, 1); md_1 << -10, 1, 10, 0; mv_1 << -10, 1, 10, 0; mv_1(0,0).d_ = 1.0; mv_1(0,1).d_ = 1.0; mv_1(1,0).d_ = 1.0; mv_1(1,1).d_ = 1.0; md_2 << 10, -10, 1, 2; mv_2 << 10, -10, 1, 2; mv_2(0,0).d_ = 1.0; mv_2(0,1).d_ = 1.0; mv_2(1,0).d_ = 1.0; mv_2(1,1).d_ = 1.0; output = subtract(mv_1, mv_2); AVEC q = createAVEC(mv_1(0,0).val().val(),mv_1(0,1).val().val(),mv_1(1,0).val().val(),mv_1(1,1).val().val()); VEC h; output(0,0).d_.val().grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_matrix_matrix_3rdDeriv) { using stan::math::subtract; using stan::math::matrix_d; using stan::math::matrix_ffv; matrix_d expected_output(2,2); matrix_ffv output; matrix_d md_1(2,2), md_2(2,2); matrix_ffv mv_1(2,2), mv_2(2,2); matrix_d md_mis (2, 3); matrix_ffv mv_mis (1, 1); md_1 << -10, 1, 10, 0; mv_1 << -10, 1, 10, 0; mv_1(0,0).d_ = 1.0; mv_1(0,1).d_ = 1.0; mv_1(1,0).d_ = 1.0; mv_1(1,1).d_ = 1.0; mv_1(0,0).val_.d_ = 1.0; mv_1(0,1).val_.d_ = 1.0; mv_1(1,0).val_.d_ = 1.0; mv_1(1,1).val_.d_ = 1.0; md_2 << 10, -10, 1, 2; mv_2 << 10, -10, 1, 2; mv_2(0,0).d_ = 1.0; mv_2(0,1).d_ = 1.0; mv_2(1,0).d_ = 1.0; mv_2(1,1).d_ = 1.0; mv_2(0,0).val_.d_ = 1.0; mv_2(0,1).val_.d_ = 1.0; mv_2(1,0).val_.d_ = 1.0; mv_2(1,1).val_.d_ = 1.0; output = subtract(mv_1, mv_2); AVEC q = createAVEC(mv_1(0,0).val().val(),mv_1(0,1).val().val(),mv_1(1,0).val().val(),mv_1(1,1).val().val()); VEC h; output(0,0).d_.d_.grad(q,h); EXPECT_FLOAT_EQ(0,h[0]); EXPECT_FLOAT_EQ(0,h[1]); EXPECT_FLOAT_EQ(0,h[2]); EXPECT_FLOAT_EQ(0,h[3]); } TEST(AgradMixMatrixOperatorSubtraction,ffv_matrix_matrix_exception) { using stan::math::subtract; using stan::math::matrix_d; using stan::math::matrix_ffv; matrix_d d1(2,2), d2(1,2); matrix_ffv v1(2,2), v2(1,2); EXPECT_THROW(subtract(d1, d2), std::invalid_argument); EXPECT_THROW(subtract(d1, v2), std::invalid_argument); EXPECT_THROW(subtract(v1, d2), std::invalid_argument); EXPECT_THROW(subtract(v1, v2), std::invalid_argument); }
31.172897
111
0.635351
yizhang-cae
f5e93bcb204cd48c4caf9678743afabfb222b03d
3,331
cpp
C++
3rdparty/GPSTk/ext/lib/Vdraw/Palette.cpp
mfkiwl/ICE
e660d031bb1bcea664db1de4946fd8781be5b627
[ "MIT" ]
50
2019-10-12T01:22:20.000Z
2022-02-15T23:28:26.000Z
3rdparty/GPSTk/ext/lib/Vdraw/Palette.cpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
null
null
null
3rdparty/GPSTk/ext/lib/Vdraw/Palette.cpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
14
2019-11-05T01:50:29.000Z
2021-08-06T06:23:44.000Z
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 3.0 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= /// @file Palette.cpp Defines a color palette. Class defintions. #include "Palette.hpp" namespace vdraw { Palette::Palette(const Color &base, double imin, double imax) { setRange(imin,imax); setColor(imin,base); setColor(imax,base); } Palette::Palette(const Palette &p) { min = p.min; width = p.width; palette = p.palette; } Palette& Palette::operator=(Palette p) { // p is a copy, swap the variables std::swap(min,p.min); std::swap(width,p.width); std::swap(palette,p.palette); // p is destructed with the old data from this return *this; } void Palette::setColor(double val, const Color &c) { clamp(val); val = (val-min)/width; if(palette.size()==0) palette.push_back(std::pair<double,Color>(val,c)); else { std::list<std::pair<double,Color> >::iterator i=palette.begin(); while((i!=palette.end())&&(i->first<val)) i++; if(i==palette.end()) palette.push_back(std::pair<double,Color>(val,c)); else if(i==palette.begin()) palette.push_front(std::pair<double,Color>(val,c)); else if(i->first==val) i->second=c; else palette.insert(i,std::pair<double,Color>(val,c)); } } Color Palette::getColor(double val) const { clamp(val); val = (val-min)/width; std::list<std::pair<double,Color> >::const_iterator j,i=palette.begin(); while((i!=palette.end())&&(i->first<val)) i++; if(i->first==val || i==palette.begin()) return i->second; else if(i==palette.end())return (--i)->second; j = i--; // i is before j return (i->second).interpolate((val-(i->first))/((j->first)-(i->first)),j->second); } }
33.31
87
0.590814
mfkiwl
f5eb05845bb9112c7134f335fdd99bbdd7ccb202
2,507
cpp
C++
src/AppService.cpp
lan143/aqua_controller_esp8266
74a9a2a185037ae465898bcf797adfc7e560aebd
[ "MIT" ]
null
null
null
src/AppService.cpp
lan143/aqua_controller_esp8266
74a9a2a185037ae465898bcf797adfc7e560aebd
[ "MIT" ]
null
null
null
src/AppService.cpp
lan143/aqua_controller_esp8266
74a9a2a185037ae465898bcf797adfc7e560aebd
[ "MIT" ]
null
null
null
/** * MIT License * * Copyright (c) 2018-2019 Kravchenko Artyom * * 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 "AppService.h" AppService* AppService::_instance = 0; void AppService::init() { _serial = &Serial; _serial->begin(115200); _settingsService = new SettingsService(); _serialService = new SerialService(); _wifiService = new WifiService(); _wifiService->init(); _ntpUDP = new WiFiUDP(); _ntpClient = new NTPClient(*_ntpUDP); _ntpClient->setTimeOffset(3 * 3600); _ntpClient->begin(); _clockService = new ClockService(); _clockService->init(); _webServer = new WebServer(); _webServer->init(); _lightService = new LightService(); _heatingService = new HeatingService(); _aerationService = new AerationService(); _filterService = new FilterService(); _maintainTemperatureService = new MaintainTemperatureService(); _outerTemperatureService = new OuterTemperatureService(); _apiService = new ApiService(); } void AppService::update() { this->getSerialService()->update(); this->getWifiService()->update(); this->getClockService()->update(); this->getLightService()->update(); this->getHeatingService()->update(); this->getAerationService()->update(); this->getFilterService()->update(); this->getMaintainTemperatureService()->update(); this->getOuterTemperatureService()->update(); this->getApiService()->update(); }
31.734177
81
0.716394
lan143
f5edcf74beccef6714df5999f1c005d89beb25ed
432
cpp
C++
cli/day10.cpp
maxnoe/adventofcode2020
eb2a3ea03af02bf951f145f214da6a9221d8fe4f
[ "MIT" ]
null
null
null
cli/day10.cpp
maxnoe/adventofcode2020
eb2a3ea03af02bf951f145f214da6a9221d8fe4f
[ "MIT" ]
null
null
null
cli/day10.cpp
maxnoe/adventofcode2020
eb2a3ea03af02bf951f145f214da6a9221d8fe4f
[ "MIT" ]
null
null
null
#include <string> #include <iostream> #include <aocmaxnoe2020/aocmaxnoe2020.h> #include <aocmaxnoe2020/day10.h> using namespace aocmaxnoe2020; int main() { std::string input = get_input(10); auto numbers = day10::parse_input(input); uint64_t part1 = day10::part1(numbers); std::cout << "Solution 1: " << part1 << std::endl; std::cout << "Solution 2: " << day10::part2(numbers) << std::endl; return 0; }
22.736842
70
0.657407
maxnoe
f5f0d2c0281bfbad164c4915c488f09e7fc98b28
2,161
cpp
C++
printscan/wia/test/wiatest2/wiaeditproprange.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
printscan/wia/test/wiatest2/wiaeditproprange.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
printscan/wia/test/wiatest2/wiaeditproprange.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// Wiaeditproprange.cpp : implementation file // #include "stdafx.h" #include "wiatest.h" #include "Wiaeditproprange.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CWiaeditproprange dialog CWiaeditproprange::CWiaeditproprange(CWnd* pParent /*=NULL*/) : CDialog(CWiaeditproprange::IDD, pParent) { //{{AFX_DATA_INIT(CWiaeditproprange) m_szPropertyName = _T(""); m_szPropertyValue = _T(""); m_szPropertyIncValue = _T(""); m_szPropertyMaxValue = _T(""); m_szPropertyMinValue = _T(""); m_szPropertyNomValue = _T(""); //}}AFX_DATA_INIT } void CWiaeditproprange::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CWiaeditproprange) DDX_Text(pDX, IDC_RANGE_PROPERTY_NAME, m_szPropertyName); DDX_Text(pDX, IDC_RANGE_PROPERTYVALUE_EDITBOX, m_szPropertyValue); DDX_Text(pDX, RANGE_PROPERTY_INCVALUE, m_szPropertyIncValue); DDX_Text(pDX, RANGE_PROPERTY_MAXVALUE, m_szPropertyMaxValue); DDX_Text(pDX, RANGE_PROPERTY_MINVALUE, m_szPropertyMinValue); DDX_Text(pDX, RANGE_PROPERTY_NOMVALUE, m_szPropertyNomValue); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CWiaeditproprange, CDialog) //{{AFX_MSG_MAP(CWiaeditproprange) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CWiaeditproprange message handlers void CWiaeditproprange::SetPropertyName(TCHAR *szPropertyName) { m_szPropertyName = szPropertyName; } void CWiaeditproprange::SetPropertyValue(TCHAR *szPropertyValue) { m_szPropertyValue = szPropertyValue; } void CWiaeditproprange::SetPropertyValidValues(PVALID_RANGE_VALUES pValidRangeValues) { m_szPropertyMinValue.Format(TEXT("%d"),pValidRangeValues->lMin); m_szPropertyMaxValue.Format(TEXT("%d"),pValidRangeValues->lMax); m_szPropertyNomValue.Format(TEXT("%d"),pValidRangeValues->lNom); m_szPropertyIncValue.Format(TEXT("%d"),pValidRangeValues->lInc); }
30.013889
86
0.700139
npocmaka
f5f18fe53294534cf46c1c4eb97d1c037feed78d
14,919
cpp
C++
applications/StructuralMechanicsApplication/custom_response_functions/response_utilities/stress_response_definitions.cpp
Jacklwln/Kratos
12ffe332622d7e8ea3e4a10bc061beb9d8e6e8de
[ "BSD-4-Clause" ]
1
2019-08-01T09:01:08.000Z
2019-08-01T09:01:08.000Z
applications/StructuralMechanicsApplication/custom_response_functions/response_utilities/stress_response_definitions.cpp
Jacklwln/Kratos
12ffe332622d7e8ea3e4a10bc061beb9d8e6e8de
[ "BSD-4-Clause" ]
null
null
null
applications/StructuralMechanicsApplication/custom_response_functions/response_utilities/stress_response_definitions.cpp
Jacklwln/Kratos
12ffe332622d7e8ea3e4a10bc061beb9d8e6e8de
[ "BSD-4-Clause" ]
null
null
null
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Martin Fusseder, https://github.com/MFusseder // // System includes // External includes // Project includes #include "stress_response_definitions.h" #include "utilities/compare_elements_and_conditions_utility.h" #include "structural_mechanics_application_variables.h" namespace Kratos { namespace StressResponseDefinitions { TracedStressType ConvertStringToTracedStressType(const std::string& Str) { const std::map<std::string, TracedStressType> traced_stress_type_map { { "FX", TracedStressType::FX }, { "FY", TracedStressType::FY }, { "FZ", TracedStressType::FZ }, { "MX", TracedStressType::MX }, { "MY", TracedStressType::MY }, { "MZ", TracedStressType::MZ }, { "FXX", TracedStressType::FXX }, { "FXY", TracedStressType::FXY }, { "FXZ", TracedStressType::FXZ }, { "FYX", TracedStressType::FYX }, { "FYY", TracedStressType::FYY }, { "FYZ", TracedStressType::FYZ }, { "FZX", TracedStressType::FZX }, { "FZY", TracedStressType::FZY }, { "FZZ", TracedStressType::FZZ }, { "MXX", TracedStressType::MXX }, { "MXY", TracedStressType::MXY }, { "MXZ", TracedStressType::MXZ }, { "MYX", TracedStressType::MYX }, { "MYY", TracedStressType::MYY }, { "MYZ", TracedStressType::MYZ }, { "MZX", TracedStressType::MZX }, { "MZY", TracedStressType::MZY }, { "MZZ", TracedStressType::MZZ }, { "PK2", TracedStressType::PK2 }, }; auto stress_type_it = traced_stress_type_map.find(Str); if (stress_type_it == traced_stress_type_map.end()) { std::stringstream available_types; for(auto& it : traced_stress_type_map) available_types << it.first << ",\n"; KRATOS_ERROR << "Chosen stress type '" <<Str<<"' is not available!" << " Available types are: \n" << available_types.str() << std::endl; } return stress_type_it->second; } StressTreatment ConvertStringToStressTreatment(const std::string& Str) { const std::map<std::string, StressTreatment> stress_treatment_map { { "mean", StressTreatment::Mean }, { "node", StressTreatment::Node }, { "GP", StressTreatment::GaussPoint } }; auto stress_treatment_it = stress_treatment_map.find(Str); if (stress_treatment_it == stress_treatment_map.end()) { std::stringstream available_types; for(auto& it : stress_treatment_map) available_types << it.first << ",\n"; KRATOS_ERROR << "Chosen stress treatment '" <<Str<<"' is not available!" << " Available types are: \n" << available_types.str() << std::endl; } return stress_treatment_it->second; } } // namespace StressResponseDefinitions. void StressCalculation::CalculateStressOnNode(Element& rElement, const TracedStressType rTracedStressType, Vector& rOutput, const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; std::string name_current_element; CompareElementsAndConditionsUtility::GetRegisteredName(rElement, name_current_element); if(name_current_element == "CrLinearBeamElement3D2N") StressCalculation::CalculateStressOnNodeBeam(rElement, rTracedStressType, rOutput, rCurrentProcessInfo); else if(name_current_element == "ShellThinElement3D3N") KRATOS_ERROR << "Stress calculation on node not yet implemented for " << name_current_element << std::endl; else if(name_current_element == "TrussElement3D2N") KRATOS_ERROR << "Stress calculation on node not yet implemented for " << name_current_element << std::endl; else if(name_current_element == "TrussLinearElement3D2N") KRATOS_ERROR << "Stress calculation on node not yet implemented for " << name_current_element << std::endl; else KRATOS_ERROR << "Stress calculation on node not yet implemented for " << name_current_element << std::endl; KRATOS_CATCH(""); } void StressCalculation::CalculateStressOnGP(Element& rElement, const TracedStressType rTracedStressType, Vector& rOutput, const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; std::string name_current_element; CompareElementsAndConditionsUtility::GetRegisteredName(rElement, name_current_element); if(name_current_element == "CrLinearBeamElement3D2N") StressCalculation::CalculateStressOnGPBeam(rElement, rTracedStressType, rOutput, rCurrentProcessInfo); else if(name_current_element == "ShellThinElement3D3N") StressCalculation::CalculateStressOnGPShell(rElement, rTracedStressType, rOutput, rCurrentProcessInfo); else if(name_current_element == "TrussElement3D2N") StressCalculation::CalculateStressOnGPTruss(rElement, rTracedStressType, rOutput, rCurrentProcessInfo); else if(name_current_element == "TrussLinearElement3D2N") StressCalculation::CalculateStressOnGPLinearTruss(rElement, rTracedStressType, rOutput, rCurrentProcessInfo); else KRATOS_ERROR << "Stress calculation on GP not yet implemented for " << name_current_element << std::endl; KRATOS_CATCH(""); } void StressCalculation::CalculateStressOnGPLinearTruss(Element& rElement, const TracedStressType rTracedStressType, Vector& rOutput, const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; const SizeType GP_num = rElement.GetGeometry().IntegrationPoints().size(); if (rOutput.size() != GP_num) rOutput.resize(GP_num, false); switch (rTracedStressType) { case TracedStressType::FX: { std::vector< array_1d<double, 3 > > force_vector; rElement.CalculateOnIntegrationPoints(FORCE, force_vector, rCurrentProcessInfo); for(IndexType i = 0; i < GP_num ; ++i) rOutput(i) = force_vector[i][0]; break; } default: KRATOS_ERROR << "Invalid stress type! Stress type not supported for this element!" << std::endl; } KRATOS_CATCH(""); } void StressCalculation::CalculateStressOnGPTruss(Element& rElement, const TracedStressType rTracedStressType, Vector& rOutput, const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; const SizeType GP_num = (rElement.GetGeometry().IntegrationPoints()).size(); if (rOutput.size() != GP_num) rOutput.resize(GP_num, false); switch (rTracedStressType) { case TracedStressType::FX: { std::vector< array_1d<double, 3 > > force_vector; rElement.CalculateOnIntegrationPoints(FORCE, force_vector, rCurrentProcessInfo); for(IndexType i = 0; i < GP_num ; ++i) rOutput(i) = force_vector[i][0]; break; } case TracedStressType::PK2: { std::vector<Vector> stress_vector; rElement.CalculateOnIntegrationPoints(PK2_STRESS_VECTOR, stress_vector, rCurrentProcessInfo); for(IndexType i = 0; i < GP_num ; ++i) rOutput(i) = stress_vector[i][0]; break; } default: KRATOS_ERROR << "Invalid stress type! Stress type not supported for this element!" << std::endl; } KRATOS_CATCH(""); } void StressCalculation::CalculateStressOnGPShell(Element& rElement, const TracedStressType rTracedStressType, Vector& rOutput, const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; const SizeType num_gps = rElement.GetGeometry().IntegrationPointsNumber(rElement.GetIntegrationMethod()); int direction_1 = 0; int direction_2 = 0; std::vector<Matrix> stress_vector; bool stress_is_moment = true; switch (rTracedStressType) { case TracedStressType::MXX: { direction_1 = 0; direction_2 = 0; break; } case TracedStressType::MXY: { direction_1 = 0; direction_2 = 1; break; } case TracedStressType::MXZ: { direction_1 = 0; direction_2 = 2; break; } case TracedStressType::MYX: { direction_1 = 1; direction_2 = 0; break; } case TracedStressType::MYY : { direction_1 = 1; direction_2 = 1; break; } case TracedStressType::MYZ: { direction_1 = 1; direction_2 = 2; break; } case TracedStressType::MZX: { direction_1 = 2; direction_2 = 0; break; } case TracedStressType::MZY: { direction_1 = 2; direction_2 = 1; break; } case TracedStressType::MZZ : { direction_1 = 2; direction_2 = 2; break; } case TracedStressType::FXX : { direction_1 = 0; direction_2 = 0; stress_is_moment = false; break; } case TracedStressType::FXY: { direction_1 = 0; direction_2 = 1; stress_is_moment = false; break; } case TracedStressType::FXZ: { direction_1 = 0; direction_2 = 2; stress_is_moment = false; break; } case TracedStressType::FYX: { direction_1 = 1; direction_2 = 0; stress_is_moment = false; break; } case TracedStressType::FYY: { direction_1 = 1; direction_2 = 1; stress_is_moment = false; break; } case TracedStressType::FYZ: { direction_1 = 1; direction_2 = 2; stress_is_moment = false; break; } case TracedStressType::FZX: { direction_1 = 2; direction_2 = 0; stress_is_moment = false; break; } case TracedStressType::FZY: { direction_1 = 2; direction_2 = 1; stress_is_moment = false; break; } case TracedStressType::FZZ: { direction_1 = 2; direction_2 = 2; stress_is_moment = false; break; } default: KRATOS_ERROR << "Invalid stress type! Stress type not supported for this element!" << std::endl; } if(stress_is_moment) rElement.CalculateOnIntegrationPoints(SHELL_MOMENT_GLOBAL, stress_vector, rCurrentProcessInfo); else rElement.CalculateOnIntegrationPoints(SHELL_FORCE_GLOBAL, stress_vector, rCurrentProcessInfo); rOutput.resize(num_gps, false); for(IndexType i = 0; i < num_gps; i++) { rOutput(i) = stress_vector[i](direction_1, direction_2); } KRATOS_CATCH(""); } void StressCalculation::StressCalculation::CalculateStressBeam(Element& rElement, const TracedStressType rTracedStressType, std::vector< array_1d<double, 3 > >& rStressVector, const ProcessInfo& rCurrentProcessInfo, int& rDirection) { rDirection = 0; bool stress_is_moment = true; switch (rTracedStressType) { case TracedStressType::MX: { rDirection = 0; break; } case TracedStressType::MY: { rDirection = 1; break; } case TracedStressType::MZ: { rDirection = 2; break; } case TracedStressType::FX: { rDirection = 0; stress_is_moment = false; break; } case TracedStressType::FY: { rDirection = 1; stress_is_moment = false; break; } case TracedStressType::FZ: { rDirection = 2; stress_is_moment = false; break; } default: KRATOS_ERROR << "Invalid stress type! Stress type not supported for this element!" << std::endl; } if(stress_is_moment) rElement.CalculateOnIntegrationPoints(MOMENT, rStressVector, rCurrentProcessInfo); else rElement.CalculateOnIntegrationPoints(FORCE, rStressVector, rCurrentProcessInfo); } void StressCalculation::CalculateStressOnGPBeam(Element& rElement, const TracedStressType rTracedStressType, Vector& rOutput, const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; int direction_1; std::vector< array_1d<double, 3 > > stress_vector; StressCalculation::CalculateStressBeam(rElement, rTracedStressType, stress_vector, rCurrentProcessInfo, direction_1); const SizeType GP_num = rElement.GetGeometry().IntegrationPointsNumber(Kratos::GeometryData::GI_GAUSS_3); rOutput.resize(GP_num, false); for(IndexType i = 0; i < GP_num ; i++) { rOutput(i) = stress_vector[i][direction_1]; } KRATOS_CATCH("") } void StressCalculation::CalculateStressOnNodeBeam(Element& rElement, const TracedStressType rTracedStressType, Vector& rOutput, const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY; int direction_1; std::vector< array_1d<double, 3 > > stress_vector; StressCalculation::CalculateStressBeam(rElement, rTracedStressType, stress_vector, rCurrentProcessInfo, direction_1); rOutput.resize(2, false); rOutput(0) = 2 * stress_vector[0][direction_1] - stress_vector[1][direction_1]; rOutput(1) = 2 * stress_vector[2][direction_1] - stress_vector[1][direction_1]; KRATOS_CATCH("") } } // namespace Kratos.
32.362256
117
0.572357
Jacklwln
f5f22f3726756be63be4d965a664a98be804efda
1,489
hpp
C++
micro_ros_agent/include/agent/Agent.hpp
ZhenshengLee/micro-ROS-Agent
90545b718410e0214819028e2b479be3f7d6d382
[ "Apache-2.0" ]
31
2019-09-20T23:52:48.000Z
2022-03-30T16:00:17.000Z
micro_ros_agent/include/agent/Agent.hpp
ZhenshengLee/micro-ROS-Agent
90545b718410e0214819028e2b479be3f7d6d382
[ "Apache-2.0" ]
70
2019-06-20T00:06:10.000Z
2022-03-22T09:26:16.000Z
micro_ros_agent/include/agent/Agent.hpp
ZhenshengLee/micro-ROS-Agent
90545b718410e0214819028e2b479be3f7d6d382
[ "Apache-2.0" ]
11
2020-09-24T20:23:33.000Z
2022-03-08T12:02:24.000Z
// Copyright 2020 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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 _UROS_AGENT_AGENT_HPP #define _UROS_AGENT_AGENT_HPP #include <uxr/agent/AgentInstance.hpp> #include <uxr/agent/middleware/Middleware.hpp> #include <uxr/agent/middleware/utils/Callbacks.hpp> #include <agent/graph_manager/graph_manager.hpp> // TODO(jamoralp): class Documentation namespace uros { namespace agent { class Agent { public: Agent(); ~Agent() = default; bool create( int argc, char** argv); void run(); private: eprosima::uxr::AgentInstance& xrce_dds_agent_instance_; std::map<eprosima::fastdds::dds::DomainId_t, std::shared_ptr<graph_manager::GraphManager>> graph_manager_map_; std::shared_ptr<graph_manager::GraphManager> find_or_create_graph_manager(eprosima::fastdds::dds::DomainId_t domain_id); }; } // namespace agent } // namespace uros #endif // _UROS_AGENT_AGENT_HPP
29.196078
124
0.739422
ZhenshengLee
f5f262fc4e015ba765cb6884c8ef86788c17a556
1,696
cc
C++
docs/source/tutorial/libpy_tutorial/arrays.cc
gerrymanoim/libpy
ffe19d53aa9602893aecc2dd8c9feda90e06b262
[ "Apache-2.0" ]
71
2020-06-26T00:36:33.000Z
2021-12-02T13:57:02.000Z
docs/source/tutorial/libpy_tutorial/arrays.cc
stefan-jansen/libpy
e174ee103db76a9d0fcd29165d54c676ed1f2629
[ "Apache-2.0" ]
32
2020-06-26T18:59:15.000Z
2022-03-01T19:02:44.000Z
docs/source/tutorial/libpy_tutorial/arrays.cc
gerrymanoim/libpy
ffe19d53aa9602893aecc2dd8c9feda90e06b262
[ "Apache-2.0" ]
24
2020-06-26T17:01:57.000Z
2022-02-15T00:25:27.000Z
#include <string> #include <vector> #include <libpy/autofunction.h> #include <libpy/automodule.h> #include <libpy/ndarray_view.h> #include <libpy/numpy_utils.h> namespace libpy_tutorial { std::int64_t simple_sum(py::array_view<const std::int64_t> values) { std::int64_t out = 0; for (auto value : values) { out += value; } return out; } std::int64_t simple_sum_iterator(py::array_view<const std::int64_t> values) { return std::accumulate(values.begin(), values.end(), 0); } void negate_inplace(py::array_view<std::int64_t> values) { std::transform(values.cbegin(), values.cend(), values.begin(), [](std::int64_t v) { return -v; }); } bool check_prime(std::int64_t n) { if (n <= 3) { return n > 1; } else if (n % 2 == 0 || n % 3 == 0) { return false; } for (auto i = 5; std::pow(i, 2) < n; i += 6) { if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } py::owned_ref<> is_prime(py::array_view<const std::int64_t> values) { std::vector<py::py_bool> out(values.size()); std::transform(values.begin(), values.end(), out.begin(), check_prime); return py::move_to_numpy_array(std::move(out)); } LIBPY_AUTOMODULE(libpy_tutorial, arrays, ({py::autofunction<simple_sum>("simple_sum"), py::autofunction<simple_sum_iterator>("simple_sum_iterator"), py::autofunction<negate_inplace>("negate_inplace"), py::autofunction<is_prime>("is_prime")})) (py::borrowed_ref<>) { return false; } } // namespace libpy_tutorial
27.803279
80
0.579599
gerrymanoim
f5f3c8ef2ec38f4bb3a7927029967bf5768cf87c
1,570
cpp
C++
TACO_Benchmarks/nl_means/process.cpp
TUE-EE-ES/HalideReuseScheduler
3700c3b14a7f2116fe1d8503942dff069a8c4d9a
[ "MIT" ]
null
null
null
TACO_Benchmarks/nl_means/process.cpp
TUE-EE-ES/HalideReuseScheduler
3700c3b14a7f2116fe1d8503942dff069a8c4d9a
[ "MIT" ]
null
null
null
TACO_Benchmarks/nl_means/process.cpp
TUE-EE-ES/HalideReuseScheduler
3700c3b14a7f2116fe1d8503942dff069a8c4d9a
[ "MIT" ]
1
2021-04-30T05:14:03.000Z
2021-04-30T05:14:03.000Z
#include <cstdio> #include <chrono> #include "nl_means.h" #include "nl_means_auto_schedule.h" #include "halide_benchmark.h" #include "HalideBuffer.h" #include "halide_image_io.h" using namespace Halide::Runtime; using namespace Halide::Tools; int main(int argc, char **argv) { if (argc < 7) { printf("Usage: ./process input.png patch_size search_area sigma timing_iterations output.png\n" "e.g.: ./process input.png 7 7 0.12 10 output.png\n"); return 0; } Buffer<float> input = load_and_convert_image(argv[1]); int patch_size = atoi(argv[2]); int search_area = atoi(argv[3]); float sigma = atof(argv[4]); Buffer<float> output(input.width(), input.height(), 3); int timing_iterations = atoi(argv[5]); nl_means(input, patch_size, search_area, sigma, output); // Timing code printf("Input size: %d by %d, patch size: %d, search area: %d, sigma: %f\n", input.width(), input.height(), patch_size, search_area, sigma); // Manually-tuned version double min_t_manual = benchmark(timing_iterations, 1, [&]() { nl_means(input, patch_size, search_area, sigma, output); output.device_sync(); }); printf("Manually-tuned time: %gms\n", min_t_manual * 1e3); // Auto-scheduled version double min_t_auto = benchmark(timing_iterations, 1, [&]() { nl_means_auto_schedule(input, patch_size, search_area, sigma, output); }); printf("Auto-scheduled time: %gms\n", min_t_auto * 1e3); convert_and_save_image(output, argv[6]); return 0; }
30.192308
103
0.659236
TUE-EE-ES
f5f4b5d10ebf69721c7cacaaa442f4ff7f57d79c
128
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/SelfAdjointEigenSolver_compute_MatrixType2.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/SelfAdjointEigenSolver_compute_MatrixType2.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/snippets/SelfAdjointEigenSolver_compute_MatrixType2.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:8aa5ed706dca5c634da572b1fb1bbb853d4587e7f5852d746790690c0ed3cd7e size 396
32
75
0.882813
initialz
f5f560c7d8dd8906c60f23dc3b0e9188111f96c5
376
cc
C++
Bcore/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x86-shared.cc
zzzgoda/BlackDex
565c9573a89d1741b554817cfe01a6a87b585efc
[ "Apache-2.0" ]
3,239
2021-05-24T08:34:32.000Z
2022-03-31T08:24:39.000Z
Bcore/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x86-shared.cc
LGDhuanghe/BlackDex
2d8592649278b72cfaaa82ddf081d57369cbf223
[ "Apache-2.0" ]
111
2019-12-23T10:02:43.000Z
2022-03-28T01:16:43.000Z
Bcore/src/main/cpp/Dobby/source/core/modules/assembler/assembler-x86-shared.cc
LGDhuanghe/BlackDex
2d8592649278b72cfaaa82ddf081d57369cbf223
[ "Apache-2.0" ]
666
2021-05-24T08:44:43.000Z
2022-03-31T04:23:07.000Z
#include "platform_macro.h" #if defined(TARGET_ARCH_X64) || defined(TARGET_ARCH_IA32) #include "core/modules/assembler/assembler-x86-shared.h" using namespace zz::x86shared; void Assembler::jmp(Immediate imm) { buffer_->Emit8(0xE9); buffer_->Emit32((int)imm.value()); } uint64_t TurboAssembler::CurrentIP() { return pc_offset() + (addr_t)realized_address_; } #endif
22.117647
57
0.75
zzzgoda
f5f6075e06cee2818ca127e1d624ec7ff946fbc9
6,510
cpp
C++
Redneck/ReInstructionGenerator.cpp
MurielSoftware/Muriel
169ab5a96e1cf70b47f7892906a3dca2d6481ae3
[ "Apache-2.0" ]
1
2017-03-01T12:15:27.000Z
2017-03-01T12:15:27.000Z
Redneck/ReInstructionGenerator.cpp
MurielSoftware/Muriel
169ab5a96e1cf70b47f7892906a3dca2d6481ae3
[ "Apache-2.0" ]
1
2017-03-01T12:19:17.000Z
2017-03-01T12:19:52.000Z
Redneck/ReInstructionGenerator.cpp
MurielSoftware/Muriel
169ab5a96e1cf70b47f7892906a3dca2d6481ae3
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #include "ReInstructionGenerator.h" #include "ReExpression.h" #include "ReInstruction.h" #include "ReBinaryOperationExpression.h" #include "ReIfExpression.h" #include "ReDeclarationExpression.h" #include "ReAssociationExpression.h" #include "ReValueExpression.h" #include "ReIdentifierExpression.h" #include "ReWhileExpression.h" namespace Redneck { InstructionGenerator::InstructionGenerator() { } InstructionGenerator::~InstructionGenerator() { } vector<Instruction*> InstructionGenerator::Generate(list<Expression*> expressions) { vector<Instruction*> instructions; DoGenerateInner(instructions, expressions, 0); return instructions; } void InstructionGenerator::DoGenerateInner(vector<Instruction*>& instructions, list<Expression*> expressions, unsigned depth) { for (Expression* expression : expressions) { DoGenerate(instructions, expression, depth); } } void InstructionGenerator::DoGenerate(vector<Instruction*>& instructions, Expression* expression, unsigned depth) { switch (expression->GetExpressionType()) { case ExpressionType::EXPRESSION_DECLARATION: GenerateDeclaration(instructions, expression, depth); break; case ExpressionType::EXPRESSION_ASSOCIATION: GenerateAssociation(instructions, expression, depth); break; case ExpressionType::EXPRESSION_VALUE: GenerateValue(instructions, expression, depth); break; case ExpressionType::EXPRESSION_IDENTIFIER: GenerateIdentifier(instructions, expression, depth); break; case ExpressionType::EXPRESSION_BIN_OPERATION: GenerateBinaryOperation(instructions, expression, depth); break; case ExpressionType::EXPRESSION_IF: GenerateIf(instructions, expression, depth); break; case ExpressionType::EXPRESSION_WHILE: GenerateWhile(instructions, expression, depth); break; } } void InstructionGenerator::GenerateDeclaration(vector<Instruction*>& instructions, Expression* expression, unsigned depth) { DeclarationExpression* declarationExpression = (DeclarationExpression*)expression; AddInstruction(instructions, ByteCode::VAR, declarationExpression->GetIdentifier()->GetValue()); DoGenerate(instructions, declarationExpression->GetDeclaration(), depth); AddInstruction(instructions, ByteCode::ASN, declarationExpression->GetIdentifier()->GetValue()); } void InstructionGenerator::GenerateAssociation(vector<Instruction*>& instructions, Expression* expression, unsigned depth) { AssociationExpression* associationExpression = (AssociationExpression*)expression; DoGenerate(instructions, associationExpression->GetDeclaration(), depth); AddInstruction(instructions, ByteCode::ASN, associationExpression->GetIdentifier()->GetValue()); } void InstructionGenerator::GenerateValue(vector<Instruction*>& instructions, Expression* expression, unsigned depth) { ValueExpression* valueExpression = (ValueExpression*)expression; AddInstruction(instructions, ByteCode::PUSH, valueExpression->GetValue()); } void InstructionGenerator::GenerateIdentifier(vector<Instruction*>& instructions, Expression* expression, unsigned depth) { IdentifierExpression* identifierExpression = (IdentifierExpression*)expression; AddInstruction(instructions, ByteCode::LOAD, identifierExpression->GetValue()); } void InstructionGenerator::GenerateBinaryOperation(vector<Instruction*>& instructions, Expression* expression, unsigned depth) { BinaryOperationExpression* binaryOperationExpression = (BinaryOperationExpression*)expression; DoGenerate(instructions, binaryOperationExpression->GetArg0(), depth); DoGenerate(instructions, binaryOperationExpression->GetArg1(), depth); if (binaryOperationExpression->GetOperator() == "+") { AddInstruction(instructions, ByteCode::ADD, EMPTY); } else if (binaryOperationExpression->GetOperator() == "-") { AddInstruction(instructions, ByteCode::SUB, EMPTY); } else if (binaryOperationExpression->GetOperator() == "*") { AddInstruction(instructions, ByteCode::MULT, EMPTY); } else if (binaryOperationExpression->GetOperator() == "/") { AddInstruction(instructions, ByteCode::DIV, EMPTY); } else if (binaryOperationExpression->GetOperator() == "==") { AddInstruction(instructions, ByteCode::EQUALS, EMPTY); } else if (binaryOperationExpression->GetOperator() == "!=") { AddInstruction(instructions, ByteCode::NEQUALS, EMPTY); } else if (binaryOperationExpression->GetOperator() == ">") { AddInstruction(instructions, ByteCode::GRT, EMPTY); } else if (binaryOperationExpression->GetOperator() == "<") { AddInstruction(instructions, ByteCode::LS, EMPTY); } else if (binaryOperationExpression->GetOperator() == ">=") { AddInstruction(instructions, ByteCode::GRTE, EMPTY); } else if (binaryOperationExpression->GetOperator() == "<=") { AddInstruction(instructions, ByteCode::LSE, EMPTY); } } void InstructionGenerator::GenerateIf(vector<Instruction*>& instructions, Expression* expression, unsigned depth) { //IfExpression* ifExpression = (IfExpression*)expression; //string jumpAddress = GetJumpAddress("cond", depth++); //DoGenerate(instructions, ifExpression->GetCondition(), depth); //AddInstruction(instructions, ByteCode::JZERO, jumpAddress); //DoGenerateInner(instructions, ifExpression->GetStatements(), depth); //AddInstruction(instructions, ByteCode::END, jumpAddress); } void InstructionGenerator::GenerateWhile(vector<Instruction*>& instructions, Expression* expression, unsigned depth) { //WhileExpression* whileExpression = (WhileExpression*)expression; //string jumpAddress = GetJumpAddress("loop", depth++); //AddInstruction(instructions, ByteCode::SKIP, jumpAddress); //DoGenerate(instructions, whileExpression->GetCondition(), depth); //AddInstruction(instructions, ByteCode::JZERO, EMPTY); //DoGenerateInner(instructions, whileExpression->GetStatements(), depth); //AddInstruction(instructions, ByteCode::LOOP, jumpAddress); } void InstructionGenerator::AddInstruction(vector<Instruction*>& instructions, ByteCode byteCode, const string& value) { instructions.push_back(new Instruction(byteCode, value)); } string InstructionGenerator::GetJumpAddress(const string& name, int depth) { stringstream sstream; sstream << name << depth; return sstream.str(); } }
36.988636
128
0.747773
MurielSoftware
f5f9426508c6b6a8ce02b42a3b3626cecd75b347
2,222
cc
C++
server/core/misc.cc
nephtyws/MaxScale
312469dca2721666d9fff310b6c3166b0d05d2a3
[ "MIT" ]
null
null
null
server/core/misc.cc
nephtyws/MaxScale
312469dca2721666d9fff310b6c3166b0d05d2a3
[ "MIT" ]
null
null
null
server/core/misc.cc
nephtyws/MaxScale
312469dca2721666d9fff310b6c3166b0d05d2a3
[ "MIT" ]
null
null
null
/* * Copyright (c) 2016 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2023-01-01 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #include <maxscale/ccdefs.hh> #include <maxscale/maxscale.h> #include <time.h> #include <maxscale/mainworker.hh> #include <maxscale/routingworker.hh> #include "internal/maxscale.hh" #include "internal/service.hh" #include "internal/admin.hh" #include "internal/monitormanager.hh" static time_t started; namespace { struct ThisUnit { std::atomic<const mxb::Worker*> admin_worker {nullptr}; }; ThisUnit this_unit; } void maxscale_reset_starttime(void) { started = time(0); } time_t maxscale_started(void) { return started; } int maxscale_uptime() { return time(0) - started; } static sig_atomic_t n_shutdowns = 0; bool maxscale_is_shutting_down() { return n_shutdowns != 0; } int maxscale_shutdown() { int n = n_shutdowns++; if (n == 0) { auto func = []() { if (mxs::MainWorker::created()) { mxs::MainWorker::get().shutdown(); } /*< Stop all monitors */ MonitorManager::stop_all_monitors(); mxs_admin_shutdown(); mxs::RoutingWorker::shutdown_all(); }; auto w = mxs::RoutingWorker::get(mxs::RoutingWorker::MAIN); w->execute(func, nullptr, mxs::RoutingWorker::EXECUTE_QUEUED); } return n + 1; } static bool teardown_in_progress = false; bool maxscale_teardown_in_progress() { return teardown_in_progress; } void maxscale_start_teardown() { teardown_in_progress = true; } bool running_in_admin_thread() { auto current_worker = mxb::Worker::get_current(); return current_worker == this_unit.admin_worker.load(std::memory_order_acquire); } void set_admin_worker(const mxb::Worker* admin_worker) { this_unit.admin_worker.store(admin_worker, std::memory_order_release); }
20.385321
84
0.660666
nephtyws
f5fbf623cf0ead0b8eb9cbb7c04ccfe9b559bf51
8,771
cpp
C++
iree/compiler/Dialect/Flow/Transforms/RematerializeDispatchConstants.cpp
rsuderman/iree
fa5faf0a254db3311dafacc70c383a7469376095
[ "Apache-2.0" ]
1
2020-08-16T17:38:49.000Z
2020-08-16T17:38:49.000Z
iree/compiler/Dialect/Flow/Transforms/RematerializeDispatchConstants.cpp
rsuderman/iree
fa5faf0a254db3311dafacc70c383a7469376095
[ "Apache-2.0" ]
null
null
null
iree/compiler/Dialect/Flow/Transforms/RematerializeDispatchConstants.cpp
rsuderman/iree
fa5faf0a254db3311dafacc70c383a7469376095
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include "iree/compiler/Dialect/Flow/IR/FlowOps.h" #include "llvm/Support/Debug.h" #include "mlir/Dialect/StandardOps/Ops.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/BlockAndValueMapping.h" #include "mlir/IR/Builders.h" #include "mlir/IR/Location.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/StandardTypes.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassRegistry.h" #include "mlir/Support/LLVM.h" #include "mlir/Support/LogicalResult.h" #include "mlir/Transforms/Utils.h" #include "tensorflow/compiler/mlir/xla/ir/hlo_ops.h" namespace mlir { namespace iree_compiler { namespace IREE { namespace Flow { namespace { // Chosen randomly for now. We can measure and see what makes sense. constexpr int64_t kMaxRematerializedConstantSizeInBytes = 1 * 1024; // Returns true if the constant value is under a certain threshold. // This threshold is fixed for all backends as a value that is assumed small // enough to be worth inlining possibly several times (at the cost of binary // bloat). bool isConstantSmall(ConstantOp constantOp) { if (auto shapedType = constantOp.getType().dyn_cast<ShapedType>()) { return shapedType.getSizeInBits() / 8 <= kMaxRematerializedConstantSizeInBytes; } // Assume anything unshaped is small. This may not always be true in custom // dialects but is in std for now. return true; } // Returns true if the dispatch region is allowed to have constants inside. // Certain regions that may get replaced or turned into kernel imports shouldn't // have the constants moved into them as they'll just get lost. bool canDispatchRegionContainConstants(DispatchRegionOp dispatchRegionOp) { for (auto &block : dispatchRegionOp.body()) { for (auto &op : block) { // TODO(b/144530470): replace with tablegen attributes/interfaces. if (isa<xla_hlo::DotOp>(&op) || isa<xla_hlo::ConvOp>(&op)) { return false; } } } return true; } // Recursively clones the given |sourceOp| and returns the newly cloned op. Operation *recursivelyCloneOp(Operation *sourceOp, OpBuilder &builder, BlockAndValueMapping *mapping) { // Note that we dedupe required operands in the case of multiple arguments // coming from the same source operation. SmallPtrSet<Operation *, 4> operandOps; for (auto operand : sourceOp->getOperands()) { operandOps.insert(operand.getDefiningOp()); } for (auto *operandOp : operandOps) { recursivelyCloneOp(operandOp, builder, mapping); } return builder.clone(*sourceOp, *mapping); } // Clones the |sourceValue| op tree into |targetBlock|. // |mapping| is used to lookup existing values that may be present in the block // such as block arguments or already cloned ancestor ops. |mapping| will be // updated as the tree is cloned. Value cloneOpTreeIntoBlock(Value sourceValue, Block *targetBlock, BlockAndValueMapping *mapping) { // If the op has already been cloned we can just reuse that. // This happens if multiple arguments reference the same trees. if (auto existingValue = mapping->lookupOrNull(sourceValue)) { return existingValue; } OpBuilder builder(targetBlock); builder.setInsertionPointToStart(targetBlock); auto *sourceOp = sourceValue.getDefiningOp(); auto *clonedOp = recursivelyCloneOp(sourceOp, builder, mapping); // Return only the result matching our source value (in the case of multiple // results). int resultIndex = std::distance( sourceOp->result_begin(), std::find(sourceOp->result_begin(), sourceOp->result_end(), sourceValue)); return clonedOp->getResult(resultIndex); } // Inlines use of the given |value| from outside of a dispatch region to inside // of it and removes the argument. Supports multiple arguments that reference // |value| and will clone the entire value tree. LogicalResult inlineDispatchRegionOperandsUsingValue( DispatchRegionOp dispatchRegionOp, Value value) { // Find all args that are using this value. SmallVector<unsigned, 4> argIndices; for (auto arg : llvm::enumerate(dispatchRegionOp.args())) { if (arg.value() == value) { argIndices.push_back(arg.index()); } } if (argIndices.empty()) { // Not used? Wasteful call! return success(); } // Clone the value (and the ops required to create it) into the entry block. auto &entryBlock = dispatchRegionOp.body().getBlocks().front(); BlockAndValueMapping mapping; auto clonedValue = cloneOpTreeIntoBlock(value, &entryBlock, &mapping); // Replace all uses of the inner operand with the new value. for (unsigned argIndex : argIndices) { entryBlock.getArgument(argIndex).replaceAllUsesWith(clonedValue); } // Remove the dispatch region args and the block args that have been // replaced. for (unsigned argIndex : llvm::reverse(argIndices)) { dispatchRegionOp.getOperation()->eraseOperand( dispatchRegionOp.mapArgOperandToOpOperand(argIndex)); entryBlock.eraseArgument(argIndex); } return success(); } // Rematerializes a constant inside of all dispatch regions that use it. // Afterward the constant is only removed if there are no other uses within the // non-dispatch block (such as by sequencer ops). LogicalResult rematerializeConstantInDispatchRegions(ConstantOp constantOp) { Value constantValue = constantOp.getResult(); SmallVector<DispatchRegionOp, 4> usingRegionOps; for (auto *user : constantValue.getUsers()) { if (auto dispatchRegionOp = dyn_cast<DispatchRegionOp>(user)) { // Ensure this isn't just the workload and is used as an arg. if (std::find(dispatchRegionOp.args().begin(), dispatchRegionOp.args().end(), constantValue) != dispatchRegionOp.args().end()) { if (canDispatchRegionContainConstants(dispatchRegionOp)) { usingRegionOps.push_back(dispatchRegionOp); } } } } for (auto &dispatchRegionOp : usingRegionOps) { if (failed(inlineDispatchRegionOperandsUsingValue(dispatchRegionOp, constantValue))) { return failure(); } } // Remove if there are no other uses within the block. if (constantOp.use_empty()) { constantOp.erase(); } return success(); } } // namespace // Finds constant arguments to dispatch regions that are too small to be worth // putting into constant pools. This prevents things like a CSE'd scalar // constant of 0.0 being passed by reference to a bunch of regions. Later // backend-specific passes running on the dispatch regions may also be able to // improve their constant propagation chances by having the full constant value // available. // // Note that this currently only operates at the block level. Constants that are // pushed across branches are assumed to have been rematerialized within blocks // already, but if that isn't the case then this pass can be extended to do // that. class RematerializeDispatchConstantsPass : public FunctionPass<RematerializeDispatchConstantsPass> { public: void runOnFunction() override { for (auto &block : getFunction()) { SmallVector<ConstantOp, 8> smallConstantOps; for (auto constantOp : block.getOps<ConstantOp>()) { if (isConstantSmall(constantOp)) { smallConstantOps.push_back(constantOp); } } // Note: we iterate in reverse so that the rematerialized constants appear // in the same order they did originally (as insertion is at the top). for (auto constantOp : llvm::reverse(smallConstantOps)) { if (failed(rematerializeConstantInDispatchRegions(constantOp))) { return signalPassFailure(); } } } } }; std::unique_ptr<OpPassBase<FuncOp>> createRematerializeDispatchConstantsPass() { return std::make_unique<RematerializeDispatchConstantsPass>(); } static PassRegistration<RematerializeDispatchConstantsPass> pass( "iree-flow-rematerialize-dispatch-constants", "Rematerializes small previously-CSE'd constants into dispatch regions"); } // namespace Flow } // namespace IREE } // namespace iree_compiler } // namespace mlir
37.969697
80
0.721126
rsuderman
f5fc65664d1a838ef75507fddab916617491d1fe
3,535
cpp
C++
Server/Modules/src/JTPacketSender.cpp
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
4
2015-08-17T20:12:22.000Z
2020-05-30T19:53:26.000Z
Server/Modules/src/JTPacketSender.cpp
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
Server/Modules/src/JTPacketSender.cpp
wayfinder/Wayfinder-Server
a688546589f246ee12a8a167a568a9c4c4ef8151
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd 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 Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "JTPacketSender.h" #include "IPnPort.h" #include "Vector.h" #include "Packet.h" #include "PacketQueue.h" JTPacketSender:: JTPacketSender( QueuedPacketSender::SendQueue& sendQueue, PacketQueue* jobQueue, uint32 tcpLimit, uint32 excludePort, const Vector& tcpTypes, bool verbose ): ModulePacketSender( sendQueue, tcpLimit ), m_jobQueue( jobQueue ), m_excludePort( excludePort ), m_tcpTypes( tcpTypes ), m_sum( 0 ), m_cnt( 0 ), m_verbose( verbose ) { } bool JTPacketSender::sendPacket( Packet* packet, const IPnPort& destination ) { const int printEveryNpacket = 1; if ( packet == NULL ) { mc2dbg << warn << "[JobThread] Reply packet is NULL!" << endl; return false; } if ( destination == IPnPort( 0, 0 ) ) { mc2log << warn << "[JobThread] Reply packet has invalid IP/port" << "(0:0) " << endl; delete packet; return false; } if (m_verbose && packet->getLength() < 0) { packet->dump(true); m_sum += TimeUtility::getCurrentMicroTime() - packet->getDebInfo(); if (m_cnt % printEveryNpacket == 0) { mc2log << info << "[JobThread] Time to process packet: " << m_sum/printEveryNpacket << endl; if (dynamic_cast<PacketQueue*>(m_jobQueue) != NULL) mc2log << info << "[JobThread] " << ((PacketQueue*)m_jobQueue)->getStatistics() << endl; m_sum = 0; } m_cnt++; } // exclude port from tcp send if ( m_excludePort == destination.getPort() ) { sendUDP( packet, destination ); return true; } // some packets wants to be sent via tcp if ( m_tcpTypes. binarySearch( packet->getSubType() ) < MAX_UINT32 ) { sendTCP( packet, destination ); return true; } return ModulePacketSender::sendPacket( packet, destination ); }
40.170455
755
0.672419
wayfinder
f5fc7cad59b5ad1db760f6bee7dd14efb13c592d
8,377
cpp
C++
src/Selector.cpp
cppcooper/gumbo-query
f4c69278f09616e6275acd0dd2ea1d22f3785dc8
[ "MIT" ]
1
2022-02-28T15:51:39.000Z
2022-02-28T15:51:39.000Z
src/Selector.cpp
cppcooper/gumbo-query
f4c69278f09616e6275acd0dd2ea1d22f3785dc8
[ "MIT" ]
null
null
null
src/Selector.cpp
cppcooper/gumbo-query
f4c69278f09616e6275acd0dd2ea1d22f3785dc8
[ "MIT" ]
null
null
null
/*************************************************************************** * * $Id$ * **************************************************************************/ /** * @file $HeadURL$ * @author $Author$(hoping@baimashi.com) * @date $Date$ * @version $Revision$ * @brief * **/ #include <gumbo-query/Selector.h> #include <gumbo-query/QueryUtil.h> bool CSelector::match(GumboNode* apNode) { switch (mOp) { case EDummy: return true; case EEmpty: { if (apNode->type != GUMBO_NODE_ELEMENT) { return false; } GumboVector children = apNode->v.element.children; for (unsigned int i = 0; i < children.length; i++) { GumboNode* child = (GumboNode*) children.data[i]; if (child->type == GUMBO_NODE_TEXT || child->type == GUMBO_NODE_ELEMENT) { return false; } } return true; } case EOnlyChild: { if (apNode->type != GUMBO_NODE_ELEMENT) { return false; } GumboNode* parent = apNode->parent; if (parent == NULL) { return false; } unsigned int count = 0; for (unsigned int i = 0; i < parent->v.element.children.length; i++) { GumboNode* child = (GumboNode*) parent->v.element.children.data[i]; if (child->type != GUMBO_NODE_ELEMENT || (mOfType && apNode->v.element.tag == child->v.element.tag)) { continue; } count++; if (count > 1) { return false; } } return count == 1; } case ENthChild: { if (apNode->type != GUMBO_NODE_ELEMENT) { return false; } GumboNode* parent = apNode->parent; if (parent == NULL) { return false; } unsigned int i = 0; unsigned int count = 0; for (unsigned int j = 0; j < parent->v.element.children.length; j++) { GumboNode* child = (GumboNode*) parent->v.element.children.data[j]; if (child->type != GUMBO_NODE_ELEMENT || (mOfType && apNode->v.element.tag == child->v.element.tag)) { continue; } count++; if (apNode == child) { i = count; if (!mLast) { break; } } } if (mLast) { i = count - i + 1; } i -= mB; if (mA == 0) { return i == 0; } return i % mA == 0 && i / mA > 0; } case ETag: return apNode->type == GUMBO_NODE_ELEMENT && apNode->v.element.tag == mTag; default: return false; } } std::vector<GumboNode*> CSelector::filter(std::vector<GumboNode*> nodes) { std::vector<GumboNode*> ret; for (std::vector<GumboNode*>::iterator it = nodes.begin(); it != nodes.end(); it++) { GumboNode* n = *it; if (match(n)) { ret.push_back(n); } } return ret; } std::vector<GumboNode*> CSelector::matchAll(GumboNode* apNode) { std::vector<GumboNode*> ret; matchAllInto(apNode, ret); return ret; } void CSelector::matchAllInto(GumboNode* apNode, std::vector<GumboNode*>& nodes) { if (match(apNode)) { nodes.push_back(apNode); } if (apNode->type != GUMBO_NODE_ELEMENT) { return; } for (unsigned int i = 0; i < apNode->v.element.children.length; i++) { GumboNode* child = (GumboNode*) apNode->v.element.children.data[i]; matchAllInto(child, nodes); } } CBinarySelector::CBinarySelector(TOperator aOp, CSelector* apS1, CSelector* apS2) { mpS1 = apS1; mpS1->retain(); mpS2 = apS2; mpS2->retain(); mOp = aOp; mAdjacent = false; } CBinarySelector::~CBinarySelector() { if (mpS1 != NULL) { mpS1->release(); mpS1 = NULL; } if (mpS2 != NULL) { mpS2->release(); mpS2 = NULL; } } CBinarySelector::CBinarySelector(CSelector* apS1, CSelector* apS2, bool aAdjacent) { mpS1 = apS1; mpS1->retain(); mpS2 = apS2; mpS2->retain(); mOp = EAdjacent; mAdjacent = aAdjacent; } bool CBinarySelector::match(GumboNode* apNode) { switch (mOp) { case EUnion: return mpS1->match(apNode) || mpS2->match(apNode); case EIntersection: return mpS1->match(apNode) && mpS2->match(apNode); case EChild: return mpS2->match(apNode) && apNode->parent != NULL && mpS1->match(apNode->parent); case EDescendant: { if (!mpS2->match(apNode)) { return false; } for (GumboNode* p = apNode->parent; p != NULL; p = p->parent) { if (mpS1->match(p)) { return true; } } return false; } case EAdjacent: { if (!mpS2->match(apNode)) { return false; } if (apNode->type != GUMBO_NODE_ELEMENT) { return false; } size_t pos = apNode->index_within_parent; GumboNode* parent = apNode->parent; if (mAdjacent) { for (long i = pos; i >= 0; i--) { GumboNode* sibling = (GumboNode*) parent->v.element.children.data[i]; if (sibling->type == GUMBO_NODE_TEXT || sibling->type == GUMBO_NODE_COMMENT) { continue; } return mpS1->match(sibling); } return false; } for (long i = pos; i >= 0; i--) { GumboNode* sibling = (GumboNode*) parent->v.element.children.data[i]; if (mpS1->match(sibling)) { return true; } } return false; } default: return false; } return false; } CAttributeSelector::CAttributeSelector(TOperator aOp, std::string aKey, std::string aValue) { mKey = aKey; mValue = aValue; mOp = aOp; } bool CAttributeSelector::match(GumboNode* apNode) { if (apNode->type != GUMBO_NODE_ELEMENT) { return false; } GumboVector attributes = apNode->v.element.attributes; for (unsigned int i = 0; i < attributes.length; i++) { GumboAttribute* attr = (GumboAttribute*) attributes.data[i]; if (mKey != attr->name) { continue; } std::string value = attr->value; switch (mOp) { case EExists: return true; case EEquals: return mValue == value; case EIncludes: for (unsigned int i = 0, j = 0; i < value.size(); i++) { if (value[i] == ' ' || value[i] == '\t' || value[i] == '\r' || value[i] == '\n' || value[i] == '\f' || i == value.size() - 1) { unsigned int length = i - j; if (i == value.size() - 1) { length++; } std::string segment = value.substr(j, length); if (segment == mValue) { return true; } j = i + 1; } } return false; case EDashMatch: if (mValue == value) { return true; } if (value.size() < mValue.size()) { return false; } return value.substr(0, mValue.size()) == mValue && value[mValue.size()] == '-'; case EPrefix: return value.size() >= mValue.size() && value.substr(0, mValue.size()) == mValue; case ESuffix: return value.size() >= mValue.size() && value.substr(value.size() - mValue.size(), mValue.size()) == mValue; case ESubString: return value.find(mValue) != std::string::npos; default: return false; } } return false; } CUnarySelector::CUnarySelector(TOperator aOp, CSelector* apS) { mpS = apS; mpS->retain(); mOp = aOp; } CUnarySelector::~CUnarySelector() { if (mpS != NULL) { mpS->release(); mpS = NULL; } } bool CUnarySelector::hasDescendantMatch(GumboNode* apNode, CSelector* apS) { for (unsigned int i = 0; i < apNode->v.element.children.length; i++) { GumboNode* child = (GumboNode*) apNode->v.element.children.data[i]; if (apS->match(child) || (child->type == GUMBO_NODE_ELEMENT && hasDescendantMatch(child, apS))) { return true; } } return false; } bool CUnarySelector::hasChildMatch(GumboNode* apNode, CSelector* apS) { for (unsigned int i = 0; i < apNode->v.element.children.length; i++) { GumboNode* child = (GumboNode*) apNode->v.element.children.data[i]; if (apS->match(child)) { return true; } } return false; } bool CUnarySelector::match(GumboNode* apNode) { switch (mOp) { case ENot: return !mpS->match(apNode); case EHasDescendant: if (apNode->type != GUMBO_NODE_ELEMENT) { return false; } return hasDescendantMatch(apNode, mpS); case EHasChild: if (apNode->type != GUMBO_NODE_ELEMENT) { return false; } return hasChildMatch(apNode, mpS); default: return false; } } bool CTextSelector::match(GumboNode* apNode) { std::string text; switch (mOp) { case EContains: text = CQueryUtil::nodeText(apNode); break; case EOwnContains: text = CQueryUtil::nodeOwnText(apNode); break; default: return false; } text = CQueryUtil::tolower(text); return text.find(mValue) != std::string::npos; } /* vim: set ts=4 sw=4 sts=4 tw=100 noet: */
19.34642
91
0.586726
cppcooper
f5fd1c55ef8abe98b3ce3a1103a32e218c189f88
2,257
cpp
C++
SysProgTemplate_SS_15/Buffer/src/Buffer.cpp
SystemOfAProg/SysProg
75cec3d856033b5bada8b9af2290c692cb2084da
[ "MIT" ]
null
null
null
SysProgTemplate_SS_15/Buffer/src/Buffer.cpp
SystemOfAProg/SysProg
75cec3d856033b5bada8b9af2290c692cb2084da
[ "MIT" ]
null
null
null
SysProgTemplate_SS_15/Buffer/src/Buffer.cpp
SystemOfAProg/SysProg
75cec3d856033b5bada8b9af2290c692cb2084da
[ "MIT" ]
1
2018-10-11T08:52:27.000Z
2018-10-11T08:52:27.000Z
/* * Buffer.cpp * * Created on: Sep 26, 2012 * Author: sofa1011 */ using namespace std; #include "../includes/Buffer.h" #include <iostream> #include <fstream> #include <stdlib.h> #include <unistd.h> Buffer::Buffer( int bufferSize) { size = bufferSize; buffer1 = new char[bufferSize]; buffer2 = new char[bufferSize]; next = buffer1; lastReadIndex = 0; fillUpBuffer(buffer1); } Buffer::~Buffer() { } char Buffer::getCurrentChar() { return *next; } char Buffer::getNextChar(){ char c; c= *next; if (*next == NULL) { if (next == &buffer1[(size-1)]) { fillUpBuffer(buffer2); next = buffer2; return getNextChar(); } else if (next == &buffer2[(size-1)]) { fillUpBuffer(buffer1); next = buffer1; return getNextChar(); } } else { next ++; } return c; } char Buffer::returnCurrentChar(){ char c; if (next == &buffer1[0]) { cout << "[Buffer]: Set pointer 'next' back to end of buffer2." << endl; next = &buffer2[(size-1)]; } else if (next == &buffer2[0]) { cout << "[Buffer]: Set pointer 'next' back to end of buffer1." << endl; next = &buffer2[(size-1)]; } else { next--; } c = *next; return c; } int Buffer::fillUpBuffer(char* bufferIndex) { ifstream is ("buffer-test-file.txt", ios::binary | ios::ate); if (is) { int length = is.tellg(); int distanceToRead; if((size-1) > (length - lastReadIndex)) { distanceToRead = (length - lastReadIndex); } else { distanceToRead = (size-1); } is.seekg (lastReadIndex, is.beg); is.read (bufferIndex, distanceToRead); bufferIndex[distanceToRead] = NULL; is.close(); lastReadIndex += distanceToRead; } return 0; } void Buffer::printDebugInfo() { cout << "[BUFFER-DEBUG-INFO]: The size of the buffer has been set to " << size << endl; cout << "[BUFFER-DEBUG-INFO]: Start-Address for buffer 1: " << ((void *) buffer1) << endl; cout << "[BUFFER-DEBUG-INFO]: Start-Address for buffer 2: " << ((void *) buffer2) << endl; cout << "[BUFFER-DEBUG-INFO]: Start-Address for next: " << ((void *) next ) << endl; } /** * For debug purposes. */ void Buffer::printCurrentDirectory() { char cwd[256]; getcwd(cwd, sizeof(cwd)); cout << endl; printf("[BUFFER-DEBUG-INFO]: Current working directory is: %s\n", cwd); }
21.701923
93
0.625609
SystemOfAProg
eb0093cac37369b07ffc4a11b6252198768048f9
22,786
cpp
C++
src/libs/tools/tests/testtool_backendbuilder.cpp
dev2718/libelektra
cd581101febbc8ee2617243d0d93f871ef2fae88
[ "BSD-3-Clause" ]
188
2015-01-07T20:34:26.000Z
2022-03-16T09:55:09.000Z
src/libs/tools/tests/testtool_backendbuilder.cpp
dev2718/libelektra
cd581101febbc8ee2617243d0d93f871ef2fae88
[ "BSD-3-Clause" ]
3,813
2015-01-02T14:00:08.000Z
2022-03-31T14:19:11.000Z
src/libs/tools/tests/testtool_backendbuilder.cpp
dev2718/libelektra
cd581101febbc8ee2617243d0d93f871ef2fae88
[ "BSD-3-Clause" ]
149
2015-01-10T02:07:50.000Z
2022-03-16T09:50:24.000Z
/** * @file * * @brief Tests for the Backend builder class * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ #define ELEKTRA_PLUGINSPEC_WITH_COMPARE #include <backendbuilder.hpp> #include <backend.hpp> #include <backends.hpp> #include <plugindatabase.hpp> #include <algorithm> #include <iostream> #include <string> #include <unordered_map> #include <gtest/gtest.h> #include <kdb.hpp> #include <kdbconfig.h> #include <kdbhelper.h> // We disable certain tests on ASAN enabled builds: https://travis-ci.org/sanssecours/elektra/jobs/418573941 #ifdef ENABLE_ASAN #define GTEST_DISABLE_ASAN(name) DISABLED_##name #else #define GTEST_DISABLE_ASAN(name) name #endif TEST (BackendBuilder, withDatabase) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("a")]["ordering"] = "c"; mpd->data[PluginSpec ("b")]["ordering"] = "c"; mpd->data[PluginSpec ("c")]["ordering"]; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.addPlugin (PluginSpec ("a")); bb.addPlugin (PluginSpec ("b")); bb.addPlugin (PluginSpec ("c")); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("a")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("b")); EXPECT_EQ (bb.cbegin ()[2], PluginSpec ("c")); } TEST (BackendBuilder, withDatabaseIrrelevantDep) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("a")]["ordering"] = "d"; mpd->data[PluginSpec ("b")]["ordering"] = "d"; mpd->data[PluginSpec ("c")]["ordering"]; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.addPlugin (PluginSpec ("a")); bb.addPlugin (PluginSpec ("b")); bb.addPlugin (PluginSpec ("c")); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("a")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("b")); EXPECT_EQ (bb.cbegin ()[2], PluginSpec ("c")); } TEST (MountBackendBuilder, basicAddRem) { using namespace kdb; using namespace kdb::tools; try { Backend b; b.addPlugin (PluginSpec ("resolver")); b.addPlugin (PluginSpec ("dump")); } catch (std::exception const & e) { std::cout << "Plugin missing, abort test case: " << e.what () << std::endl; return; } MountBackendBuilder bb; bb.addPlugin (PluginSpec ("resolver")); EXPECT_FALSE (bb.validated ()); bb.addPlugin (PluginSpec ("dump")); EXPECT_TRUE (bb.validated ()); bb.remPlugin (PluginSpec ("dump")); EXPECT_FALSE (bb.validated ()); bb.addPlugin (PluginSpec ("dump")); EXPECT_TRUE (bb.validated ()); } TEST (GTEST_DISABLE_ASAN (MountBackendBuilder), basicSort) { using namespace kdb; using namespace kdb::tools; try { Backend b; b.addPlugin (PluginSpec ("resolver")); b.addPlugin (PluginSpec ("glob")); b.addPlugin (PluginSpec ("keytometa")); b.addPlugin (PluginSpec ("augeas")); } catch (std::exception const & e) { std::cout << "Plugin missing, abort test case: " << e.what () << std::endl; return; } MountBackendBuilder bb; bb.addPlugin (PluginSpec ("resolver")); EXPECT_FALSE (bb.validated ()); bb.addPlugin (PluginSpec ("keytometa")); EXPECT_FALSE (bb.validated ()); bb.addPlugin (PluginSpec ("glob")); EXPECT_FALSE (bb.validated ()); bb.addPlugin (PluginSpec ("augeas")); // std::cout << "Solution: "; // for (auto const & p : bb) std::cout << p.getName() << " "; // std::cout << std::endl; EXPECT_TRUE (bb.validated ()) << "Reordering not successful?"; } TEST (GTEST_DISABLE_ASAN (MountBackendBuilder), allSort) { using namespace kdb; using namespace kdb::tools; try { Backend b; b.addPlugin (PluginSpec ("resolver")); b.addPlugin (PluginSpec ("glob")); b.addPlugin (PluginSpec ("keytometa")); b.addPlugin (PluginSpec ("augeas")); // b.addPlugin (PluginSpec ("type")); // b.addPlugin (PluginSpec ("validation")); // b.addPlugin (PluginSpec ("struct", KeySet(5, *Key("user:/module", KEY_END), KS_END))); } catch (std::exception const & e) { std::cout << "Plugin missing, abort test case: " << e.what () << std::endl; return; } std::vector<std::string> permutation = { "augeas", "glob", "keytometa", "resolver" // , "type", "validation" }; do { // for (auto const & p : permutation) std::cout << p << " "; // std::cout << std::endl; MountBackendBuilder bb; bb.addPlugin (PluginSpec (permutation[0])); bb.addPlugin (PluginSpec (permutation[1])); bb.addPlugin (PluginSpec (permutation[2])); bb.addPlugin (PluginSpec (permutation[3])); // bb.addPlugin (PluginSpec (permutation[4])); // bb.addPlugin (PluginSpec (permutation[5])); // bb.addPlugin (PluginSpec (permutation[6])); // std::cout << "Solution: "; // for (auto const & p : bb) std::cout << p.getName() << " "; // std::cout << std::endl; EXPECT_TRUE (bb.validated ()) << "Reordering not successful?"; } while (std::next_permutation (permutation.begin (), permutation.end ())); } TEST (MountBackendBuilder, resolveNeeds) { using namespace kdb; using namespace kdb::tools; try { Backend b; b.addPlugin (PluginSpec ("resolver")); b.addPlugin (PluginSpec ("line")); b.addPlugin (PluginSpec ("null")); } catch (std::exception const & e) { std::cout << "Plugin missing, abort test case: " << e.what () << std::endl; return; } MountBackendBuilder bb; bb.addPlugin (PluginSpec ("resolver")); EXPECT_FALSE (bb.validated ()) << "resolver+null should be missing"; bb.addPlugin (PluginSpec ("line")); EXPECT_FALSE (bb.validated ()) << "null should be missing"; bb.resolveNeeds (); EXPECT_TRUE (bb.validated ()) << "Did not add null automatically"; } TEST (BackendBuilder, resolveDoubleNeeds) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("a")]["needs"] = "c v"; mpd->data[PluginSpec ("c")]["provides"] = "v"; mpd->data[PluginSpec ("resolver")]["provides"] = "resolver"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.addPlugin (PluginSpec ("resolver")); bb.addPlugin (PluginSpec ("a")); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 2); bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 3); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("resolver")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("a")); EXPECT_EQ (bb.cbegin ()[2], PluginSpec ("c")); } TEST (BackendBuilder, resolveDoubleNeedsVirtual) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("a")]["needs"] = "v c"; mpd->data[PluginSpec ("c")]["provides"] = "v"; mpd->data[PluginSpec ("resolver")]["provides"] = "resolver"; EXPECT_EQ (mpd->lookupInfo (PluginSpec ("c"), "provides"), "v"); EXPECT_EQ (mpd->lookupInfo (PluginSpec ("c", "v"), "provides"), "v"); BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.addPlugin (PluginSpec ("resolver")); bb.addPlugin (PluginSpec ("a")); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 2); bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 3); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("resolver")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("a")); EXPECT_EQ (bb.cbegin ()[2], PluginSpec ("c", "v")) << "remember it was virtual"; } TEST (BackendBuilder, doubleAddWithConf) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("a")]["needs"] = "v c"; mpd->data[PluginSpec ("c")]["provides"] = "v"; mpd->data[PluginSpec ("resolver")]["provides"] = "resolver"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.addPlugin (PluginSpec ("resolver")); bb.addPlugin (PluginSpec ("a")); bb.addPlugin (PluginSpec ("c", KeySet (2, *Key ("user:/abc", KEY_END), KS_END))); bb.addPlugin (PluginSpec ("v", KeySet (2, *Key ("user:/vef", KEY_END), KS_END))); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 4); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("resolver")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("a")); EXPECT_EQ (bb.cbegin ()[2], PluginSpec ("c", KeySet (2, *Key ("user:/abc", KEY_END), KS_END))); EXPECT_EQ (bb.cbegin ()[3], PluginSpec ("c", "v", KeySet (2, *Key ("user:/vef", KEY_END), KS_END))) << "remember it was virtual"; bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 4); } TEST (BackendBuilder, doubleAddWithConfVirtual) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("a")]["needs"] = "v c"; mpd->data[PluginSpec ("c")]["provides"] = "v"; mpd->data[PluginSpec ("noresolver")]["provides"] = "resolver"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.addPlugin (PluginSpec ("resolver")); bb.addPlugin (PluginSpec ("a")); bb.addPlugin (PluginSpec ("v", KeySet (2, *Key ("user:/vef", KEY_END), KS_END))); bb.addPlugin (PluginSpec ("c", KeySet (2, *Key ("user:/abc", KEY_END), KS_END))); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 4); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("noresolver", "resolver")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("a")); EXPECT_EQ (bb.cbegin ()[2], PluginSpec ("c", "v", KeySet (2, *Key ("user:/vef", KEY_END), KS_END))); EXPECT_EQ (bb.cbegin ()[3], PluginSpec ("c", KeySet (2, *Key ("user:/abc", KEY_END), KS_END))); bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 4); } TEST (BackendBuilder, directPluginLoading) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("a")]["plugins"] = "x a=b"; mpd->data[PluginSpec ("a")]["needs"] = "resolver"; mpd->data[PluginSpec ("x")]["provides"] = "x"; mpd->data[PluginSpec ("noresolver")]["provides"] = "resolver"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.addPlugin (PluginSpec ("a")); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 1); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("a")); bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 3); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("a")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("x", KeySet (2, *Key ("user:/a", KEY_VALUE, "b", KEY_END), KS_END))); EXPECT_EQ (bb.cbegin ()[2], PluginSpec ("noresolver", "resolver")); } TEST (BackendBuilder, metadata) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("r")]["metadata"] = "rename/toupper"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.needMetadata ("rename/toupper"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 1); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("r")); } TEST (BackendBuilder, metadataTwo) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("r1")]["metadata"] = "rename/toupper"; mpd->data[PluginSpec ("r1")]["status"] = "unittest"; mpd->data[PluginSpec ("r2")]["metadata"] = "rename/toupper rename/tolower"; mpd->data[PluginSpec ("r2")]["status"] = "memleak"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.needMetadata ("rename/toupper rename/tolower"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 1); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("r2")); } TEST (BackendBuilder, metadataTwoRev) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("r1")]["metadata"] = "rename/tolower"; // relevant mpd->data[PluginSpec ("r1")]["status"] = "unittest"; mpd->data[PluginSpec ("r2")]["metadata"] = "rename/toupper rename/tolower"; mpd->data[PluginSpec ("r2")]["status"] = "memleak"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.needMetadata ("rename/tolower rename/toupper"); // order not relevant ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 2); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("r1")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("r2")); } TEST (BackendBuilder, manualNeeds) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.needPlugin ("n"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 1); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("n")); } TEST (BackendBuilder, manualNeedsProvides) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.needPlugin ("x"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 1); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("n", "x")); } TEST (BackendBuilder, manualMultipleNeeds) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; mpd->data[PluginSpec ("y")]["provides"] = "z"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.needPlugin ("n"); bb.needPlugin ("n"); bb.needPlugin ("x"); bb.needPlugin ("x"); bb.needPlugin ("y"); bb.needPlugin ("y"); bb.needPlugin ("z"); bb.needPlugin ("z"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 2); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("n")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("y")); } TEST (BackendBuilder, manualMultipleNeedsSingleLine) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; mpd->data[PluginSpec ("y")]["provides"] = "z"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.needPlugin ("n n x x y y z z"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 2); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("n")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("y")); } TEST (BackendBuilder, manualRecommends) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.recommendPlugin ("n"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 1); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("n")); } TEST (BackendBuilder, manualNoRecommends) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.recommendPlugin ("n"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (false); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); } TEST (BackendBuilder, manualRecommendsProvides) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.recommendPlugin ("x"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (true); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 1); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("n", "x")); } TEST (BackendBuilder, manualMultipleRecommends) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; mpd->data[PluginSpec ("y")]["provides"] = "z"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.recommendPlugin ("n"); bb.recommendPlugin ("n"); bb.recommendPlugin ("x"); bb.recommendPlugin ("x"); bb.recommendPlugin ("y"); bb.recommendPlugin ("y"); bb.recommendPlugin ("z"); bb.recommendPlugin ("z"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 2); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("n")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("y")); } TEST (BackendBuilder, manualMultipleRecommendsSingleLine) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("n")]["provides"] = "x"; mpd->data[PluginSpec ("y")]["provides"] = "z"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.recommendPlugin ("n n x x y y z z"); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 0); bb.resolveNeeds (); ASSERT_EQ (std::distance (bb.cbegin (), bb.cend ()), 2); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("n")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("y")); } TEST (BackendBuilder, resolveDoubleRecommends) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("a")]["recommends"] = "c v"; mpd->data[PluginSpec ("c")]["provides"] = "v"; mpd->data[PluginSpec ("resolver")]["provides"] = "resolver"; BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); bb.addPlugin (PluginSpec ("resolver")); bb.addPlugin (PluginSpec ("a")); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 2); bb.resolveNeeds (); EXPECT_EQ (std::distance (bb.cbegin (), bb.cend ()), 3); EXPECT_EQ (bb.cbegin ()[0], PluginSpec ("resolver")); EXPECT_EQ (bb.cbegin ()[1], PluginSpec ("a")); EXPECT_EQ (bb.cbegin ()[2], PluginSpec ("c")); } static int checkconfLookup (ckdb::Key * errorKey ELEKTRA_UNUSED, ckdb::KeySet * config) { ckdb::Key * k = ckdb::ksLookupByName (config, "/a", 0); if (k) { return 0; } return -1; } TEST (BackendBuilder, checkconfOkNoChange) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("checkconf1")]["provides"] = "test123"; mpd->setCheckconfFunction (checkconfLookup); BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); PluginSpec spec ("checkconf1"); KeySet pluginConfig; Key a; a.setName ("user:/a"); a.setString ("abc"); pluginConfig.append (a); spec.appendConfig (pluginConfig); bb.addPlugin (spec); } TEST (BackendBuilder, checkconfNotOKmissing) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("checkconf3")]["c"] = "something"; mpd->setCheckconfFunction (checkconfLookup); BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); EXPECT_THROW (bb.addPlugin (PluginSpec ("checkconf3")), PluginConfigInvalid); } static int checkconfAppend (ckdb::Key * errorKey ELEKTRA_UNUSED, ckdb::KeySet * config) { ckdb::ksAppendKey (config, ckdb::keyNew ("user:/b", KEY_VALUE, "test", KEY_END)); return 1; } TEST (BackendBuilder, checkconfOkChanged) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("checkconf1")]["provides"] = "test123"; mpd->setCheckconfFunction (checkconfAppend); BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); PluginSpec spec ("checkconf1"); KeySet pluginConfig; spec.appendConfig (pluginConfig); bb.addPlugin (spec); // we expect b to be added now spec = *bb.begin (); EXPECT_EQ (spec.getConfig ().get<std::string> ("user:/b"), "test"); } static int checkconfDelete (ckdb::Key * errorKey ELEKTRA_UNUSED, ckdb::KeySet * config) { ckdb::ksCopy (config, NULL); return 1; } TEST (BackendBuilder, checkconfOkRemovedPluginConfig) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("checkconf1")]["provides"] = "test123"; mpd->setCheckconfFunction (checkconfDelete); BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); PluginSpec spec ("checkconf1"); KeySet pluginConfig; Key a; a.setName ("user:/a"); a.setString ("abc"); pluginConfig.append (a); spec.appendConfig (pluginConfig); bb.addPlugin (spec); // we expect a to be removed now spec = *bb.begin (); EXPECT_THROW (spec.getConfig ().get<std::string> ("user:/a"), KeyNotFoundException); } TEST (BackendBuilder, checkconfOkRemovedBackendConfig) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("checkconf1")]["provides"] = "test123"; mpd->setCheckconfFunction (checkconfDelete); BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); PluginSpec spec ("checkconf1"); KeySet pluginConfig; spec.appendConfig (pluginConfig); KeySet backendConfig; Key b; b.setName ("system:/b"); b.setString ("xyz"); backendConfig.append (b); bb.setBackendConfig (backendConfig); bb.addPlugin (spec); // we expect b to be removed now spec = *bb.begin (); EXPECT_THROW (bb.getBackendConfig ().get<std::string> ("system:/b"), KeyNotFoundException); } static int checkconfAppendBackendConf (ckdb::Key * errorKey ELEKTRA_UNUSED, ckdb::KeySet * config) { ckdb::ksAppendKey (config, ckdb::keyNew ("system:/a", KEY_VALUE, "abc", KEY_END)); return 1; } TEST (BackendBuilder, checkconfOkAppendBackendConfig) { using namespace kdb; using namespace kdb::tools; std::shared_ptr<MockPluginDatabase> mpd = std::make_shared<MockPluginDatabase> (); mpd->data[PluginSpec ("checkconf1")]["provides"] = "test123"; mpd->setCheckconfFunction (checkconfAppendBackendConf); BackendBuilderInit bbi (mpd); BackendBuilder bb (bbi); PluginSpec spec ("checkconf1"); KeySet pluginConfig; spec.appendConfig (pluginConfig); bb.addPlugin (spec); // we expect b to be added now spec = *bb.begin (); EXPECT_EQ (bb.getBackendConfig ().get<std::string> ("system:/a"), "abc"); }
32.691535
130
0.680506
dev2718
eb02baeea0b3dbeb7a460df319181fcff99baa62
2,278
cpp
C++
apps/settings/Settings.cpp
seldon1000/fairwindplusplus
26cf18e0ecf49c642e24cc504d56722eaddd1399
[ "Apache-2.0" ]
null
null
null
apps/settings/Settings.cpp
seldon1000/fairwindplusplus
26cf18e0ecf49c642e24cc504d56722eaddd1399
[ "Apache-2.0" ]
null
null
null
apps/settings/Settings.cpp
seldon1000/fairwindplusplus
26cf18e0ecf49c642e24cc504d56722eaddd1399
[ "Apache-2.0" ]
null
null
null
// // Created by __author__ on 18/01/2022. // #include <FairWindSdk/settings/FairComboBox.hpp> #include <FairWindSdk/settings/FairLineEdit.hpp> #include <FairWindSdk/settings/FairCheckBox.hpp> #include <FairWindSdk/settings/DisplaysBrowser.hpp> #include <FairWindSdk/settings/LayersBrowser.hpp> #include "Settings.hpp" #include "MainPage.hpp" #include "general/General.hpp" #include "extensions/Extensions.hpp" namespace fairwind::apps::settings { // Called when the app is loaded void Settings::onCreate() { // Call the framework onCreate() FairWindApp::onCreate(); // Get the FairWind singleton auto fairWind = fairwind::FairWind::getInstance(); // Register settings pages inside the FairWind singleton fairWind->registerSettingsTab(new general::General()); //fairWind->registerSettingsTab(new Connections()); fairWind->registerSettingsTab(new extensions::Extensions()); } //Called by the FairWind framework when the app is invoked for the first time void Settings::onStart() { // Call the framework onCreate() FairWindApp::onStart(); // Create the main page auto mainPage = new MainPage(nullptr, this); // Add the main page to the app pages as root page add(mainPage); // Show the root page show(); } // Called when the app is going to be in foreground void Settings::onResume() { // Call the framework onResume() FairWindApp::onResume(); } // Called when the app is going to be in background void Settings::onPause() { // Call the framework onPause() FairWindApp::onPause(); } // Called when the app is going to be stopped void Settings::onStop() { // Call the framework on onStop() FairWindApp::onStop(); } // Called when the app is going to be unloaded once and forever void Settings::onDestroy() { // Call the framework onDestroy() FairWindApp::onDestroy(); } // Called when the app is going to be unloaded once and forever void Settings::onConfigChanged() { // Call the framework onDestroy() FairWindApp::onConfigChanged(); } } // fairwind::apps::settings
27.119048
81
0.651888
seldon1000
eb04decdd2e600bf815af60cbb8d329c507c2a7f
14,982
cpp
C++
Matrix3x3.cpp
mbrandonw/opengl_physics_engine
422815999f0dc14335d1b4238c58ce7813d58038
[ "MIT" ]
1
2018-05-07T18:29:18.000Z
2018-05-07T18:29:18.000Z
Matrix3x3.cpp
mbrandonw/opengl_physics_engine
422815999f0dc14335d1b4238c58ce7813d58038
[ "MIT" ]
null
null
null
Matrix3x3.cpp
mbrandonw/opengl_physics_engine
422815999f0dc14335d1b4238c58ce7813d58038
[ "MIT" ]
null
null
null
/* --------------------------------------------------------------------------- * * Matrix2x2 class - Michael Brandon Williams * * Matrix2x2.cpp * * --------------------------------------------------------------------------- */ #include "Matrix3x3.h" Matrix3x3::Matrix3x3() { elements[0][0] = 1; elements[0][1] = 0; elements[0][2] = 0; elements[1][0] = 0; elements[1][1] = 1; elements[1][2] = 0; elements[2][0] = 0; elements[2][1] = 0; elements[2][2] = 1; } // constructor for when this matrix is to be intialized with // the same elements as another matrix Matrix3x3::Matrix3x3 (const Matrix3x3 &M) { elements[0][0] = M.elements[0][0]; elements[0][1] = M.elements[0][1]; elements[0][2] = M.elements[0][2]; elements[1][0] = M.elements[1][0]; elements[1][1] = M.elements[1][1]; elements[1][2] = M.elements[1][2]; elements[2][0] = M.elements[2][0]; elements[2][1] = M.elements[2][1]; elements[2][2] = M.elements[2][2]; } Matrix3x3::~Matrix3x3() { } // accessor float Matrix3x3::_e (const int j, const int k) const { return (elements[j][k]); } float Matrix3x3::operator () (const int j, const int k) const { return (elements[j][k]); } // modifier void Matrix3x3::set_e (const int j, const int k, const float e) { elements[j][k] = e; } // assignment const Matrix3x3& Matrix3x3::operator = (const Matrix3x3 &M) { elements[0][0] = M.elements[0][0]; elements[0][1] = M.elements[0][1]; elements[0][2] = M.elements[0][2]; elements[1][0] = M.elements[1][0]; elements[1][1] = M.elements[1][1]; elements[1][2] = M.elements[1][2]; elements[2][0] = M.elements[2][0]; elements[2][1] = M.elements[2][1]; elements[2][2] = M.elements[2][2]; return (*this); } // tests for equality const bool Matrix3x3::operator == (const Matrix3x3 &M) const { return ((elements[0][0] == M.elements[0][0]) && (elements[0][1] == M.elements[0][1]) && (elements[0][2] == M.elements[0][2]) && (elements[1][0] == M.elements[1][0]) && (elements[1][1] == M.elements[1][1]) && (elements[1][2] == M.elements[1][2]) && (elements[2][0] == M.elements[2][0]) && (elements[2][1] == M.elements[2][1]) && (elements[2][2] == M.elements[2][2])); } // tests for inequality const bool Matrix3x3::operator != (const Matrix3x3 &M) const { return ((elements[0][0] != M.elements[0][0]) && (elements[0][1] != M.elements[0][1]) && (elements[0][2] != M.elements[0][2]) && (elements[1][0] != M.elements[1][0]) && (elements[1][1] != M.elements[1][1]) && (elements[1][2] != M.elements[1][2]) && (elements[2][0] != M.elements[2][0]) && (elements[2][1] != M.elements[2][1]) && (elements[2][2] != M.elements[2][2])); } // checks if the matrix is a zero matrix bool Matrix3x3::Zero_Matrix () const { return ((elements[0][0] == 0.0f) && (elements[0][1] == 0.0f) && (elements[0][2] == 0.0f) && (elements[1][0] == 0.0f) && (elements[1][1] == 0.0f) && (elements[1][2] == 0.0f) && (elements[2][0] == 0.0f) && (elements[2][1] == 0.0f) && (elements[2][2] == 0.0f)); } // checks if the matrix is an identity matrix bool Matrix3x3::Identity_Matrix () const { return ((elements[0][0] == 1.0f) && (elements[0][1] == 0.0f) && (elements[0][2] == 0.0f) && (elements[1][0] == 0.0f) && (elements[1][1] == 1.0f) && (elements[1][2] == 0.0f) && (elements[2][0] == 0.0f) && (elements[2][1] == 0.0f) && (elements[2][2] == 1.0f)); } // turns the matrix into an identity matrix void Matrix3x3::Set_Identity_Matrix () { elements[0][0] = elements[1][1] = elements[2][2] = 1.0f; elements[0][1] = elements[0][2] = 0.0f; elements[1][0] = elements[1][2] = 0.0f; elements[2][0] = elements[2][1] = 0.0f; } // addition (+) const Matrix3x3 Matrix3x3::operator + (const Matrix3x3 &M) const { Matrix3x3 temp; temp.elements[0][0] = elements[0][0] + M.elements[0][0]; temp.elements[0][1] = elements[0][1] + M.elements[0][1]; temp.elements[0][2] = elements[0][2] + M.elements[0][2]; temp.elements[1][0] = elements[1][0] + M.elements[1][0]; temp.elements[1][1] = elements[1][1] + M.elements[1][1]; temp.elements[1][2] = elements[1][2] + M.elements[1][2]; temp.elements[2][0] = elements[2][0] + M.elements[2][0]; temp.elements[2][1] = elements[2][1] + M.elements[2][1]; temp.elements[2][2] = elements[2][2] + M.elements[2][2]; return (temp); } // addition (+=) const Matrix3x3& Matrix3x3::operator += (const Matrix3x3 &M) { elements[0][0] += M.elements[0][0]; elements[0][1] += M.elements[0][1]; elements[0][2] += M.elements[0][2]; elements[1][0] += M.elements[1][0]; elements[1][1] += M.elements[1][1]; elements[1][2] += M.elements[1][2]; elements[2][0] += M.elements[2][0]; elements[2][1] += M.elements[2][1]; elements[2][2] += M.elements[2][2]; return (*this); } // subtraction (-) const Matrix3x3 Matrix3x3::operator - (const Matrix3x3 &M) const { Matrix3x3 temp; temp.elements[0][0] = elements[0][0] - M.elements[0][0]; temp.elements[0][1] = elements[0][1] - M.elements[0][1]; temp.elements[0][2] = elements[0][2] - M.elements[0][2]; temp.elements[1][0] = elements[1][0] - M.elements[1][0]; temp.elements[1][1] = elements[1][1] - M.elements[1][1]; temp.elements[1][2] = elements[1][2] - M.elements[1][2]; temp.elements[2][0] = elements[2][0] - M.elements[2][0]; temp.elements[2][1] = elements[2][1] - M.elements[2][1]; temp.elements[2][2] = elements[2][2] - M.elements[2][2]; return (temp); } // subtraction (-=) const Matrix3x3& Matrix3x3::operator -= (const Matrix3x3 &M) { elements[0][0] -= M.elements[0][0]; elements[0][1] -= M.elements[0][1]; elements[0][2] -= M.elements[0][2]; elements[1][0] -= M.elements[1][0]; elements[1][1] -= M.elements[1][1]; elements[1][2] -= M.elements[1][2]; elements[2][0] -= M.elements[2][0]; elements[2][1] -= M.elements[2][1]; elements[2][2] -= M.elements[2][2]; return (*this); } // multiplication (*) const Matrix3x3 Matrix3x3::operator * (const Matrix3x3 &M) const { Matrix3x3 temp; temp.elements[0][0] = (elements[0][0] * M.elements[0][0]) + (elements[0][1] * M.elements[1][0]) + (elements[0][2] * M.elements[2][0]); temp.elements[1][0] = (elements[1][0] * M.elements[0][0]) + (elements[1][1] * M.elements[1][0]) + (elements[1][2] * M.elements[2][0]); temp.elements[2][0] = (elements[2][0] * M.elements[0][0]) + (elements[2][1] * M.elements[1][0]) + (elements[2][2] * M.elements[2][0]); temp.elements[0][1] = (elements[0][0] * M.elements[0][1]) + (elements[0][1] * M.elements[1][1]) + (elements[0][2] * M.elements[2][1]); temp.elements[1][1] = (elements[1][0] * M.elements[0][1]) + (elements[1][1] * M.elements[1][1]) + (elements[1][2] * M.elements[2][1]); temp.elements[2][1] = (elements[2][0] * M.elements[0][1]) + (elements[2][1] * M.elements[1][1]) + (elements[2][2] * M.elements[2][1]); temp.elements[0][2] = (elements[0][0] * M.elements[0][2]) + (elements[0][1] * M.elements[1][2]) + (elements[0][2] * M.elements[2][2]); temp.elements[1][2] = (elements[1][0] * M.elements[0][2]) + (elements[1][1] * M.elements[1][2]) + (elements[1][2] * M.elements[2][2]); temp.elements[2][2] = (elements[2][0] * M.elements[0][2]) + (elements[2][1] * M.elements[1][2]) + (elements[2][2] * M.elements[2][2]); return (temp); } // multiplcation (*=) const Matrix3x3& Matrix3x3::operator *= (const Matrix3x3 &M) { Matrix3x3 temp; temp = *this * M; *this = temp; return (*this); } // scalar-multiplication (*) const Matrix3x3 Matrix3x3::operator * (const float s) const { Matrix3x3 M; M.elements[0][0] = elements[0][0] * s; M.elements[0][1] = elements[0][1] * s; M.elements[0][2] = elements[0][2] * s; M.elements[1][0] = elements[1][0] * s; M.elements[1][1] = elements[1][1] * s; M.elements[1][2] = elements[1][2] * s; M.elements[2][0] = elements[2][0] * s; M.elements[2][1] = elements[2][1] * s; M.elements[2][2] = elements[2][2] * s; return (M); } // scalar-multiplication (*=) const Matrix3x3& Matrix3x3::operator *= (const float s) { elements[0][0] *= s; elements[0][1] *= s; elements[0][2] *= s; elements[1][0] *= s; elements[1][1] *= s; elements[1][2] *= s; elements[2][0] *= s; elements[2][1] *= s; elements[2][2] *= s; return (*this); } // vector-multiplication (*) const Vector3D Matrix3x3::operator * (const Vector3D &V) const { Vector3D temp; temp.x = (V.x * elements[0][0]) + (V.y * elements[0][1]) + (V.z * elements[0][2]); temp.y = (V.x * elements[1][0]) + (V.y * elements[1][1]) + (V.z * elements[1][2]); temp.z = (V.x * elements[2][0]) + (V.y * elements[2][1]) + (V.z * elements[2][2]); return (temp); } // matrix-division (/) const Matrix3x3 Matrix3x3::operator / (const Matrix3x3 &M) const { return (*this * M.Inverse ()); } // matrix-division (/=) const Matrix3x3& Matrix3x3::operator /= (const Matrix3x3 &M) { return (*this = *this * M.Inverse ()); } // scalar-division (/) const Matrix3x3 Matrix3x3::operator / (const float s) const { Matrix3x3 temp; temp.elements[0][0] = elements[0][0] / s; temp.elements[0][1] = elements[0][1] / s; temp.elements[0][2] = elements[0][2] / s; temp.elements[1][0] = elements[1][0] / s; temp.elements[1][1] = elements[1][1] / s; temp.elements[1][2] = elements[1][2] / s; temp.elements[2][0] = elements[2][0] / s; temp.elements[2][1] = elements[2][1] / s; temp.elements[2][2] = elements[2][2] / s; return (temp); } // scalar-division (/=) const Matrix3x3& Matrix3x3::operator /= (const float s) { elements[0][0] /= s; elements[0][1] /= s; elements[0][2] /= s; elements[1][0] /= s; elements[1][1] /= s; elements[1][2] /= s; elements[2][0] /= s; elements[2][1] /= s; elements[2][2] /= s; return (*this); } // matrix to an integer power const Matrix3x3 Matrix3x3::operator ^ (const int p) const { Matrix3x3 temp; for (int j = 0; j < p; j++) { temp *= *this; } return (temp); } // fills the matrix with random elements void Matrix3x3::Random_Elements (const int min, const int max) { Random_Number generator; for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) { elements[j][k] = float (generator.Random (min, max)); } } } // sets the elements of the matrix to create a rotation matrix around the x-axis void Matrix3x3::Rotation_Matrix_X (const float sine, const float cosine) { elements[0][0] = 1; elements[0][1] = 0; elements[0][2] = 0; elements[1][0] = 0; elements[1][1] = cosine; elements[1][2] = -sine; elements[2][0] = 0; elements[2][1] = sine; elements[2][2] = cosine; } // sets the elements of the matrix to create a rotation matrix around the y-axis void Matrix3x3::Rotation_Matrix_Y (const float sine, const float cosine) { elements[0][0] = cosine; elements[0][1] = 0; elements[0][2] = sine; elements[1][0] = 0; elements[1][1] = 1; elements[1][2] = 0; elements[2][0] = -sine; elements[2][1] = 0; elements[2][2] = cosine; } // sets the elements of the matrix to create a rotation matrix around the z-axis void Matrix3x3::Rotation_Matrix_Z (const float sine, const float cosine) { elements[0][0] = cosine; elements[0][1] = -sine; elements[0][2] = 0; elements[1][0] = sine; elements[1][1] = cosine; elements[1][2] = 0; elements[2][0] = 0; elements[2][1] = 0; elements[2][2] = 1; } // sets the elements of the matrix to create a rotation matrix around an arbitrary axis void Matrix3x3::Rotation_Matrix_Axis (const float sine, const float cosine, const Vector3D &A) { float t = 1 - cosine; elements[0][0] = t * A.x * A.x + cosine; elements[0][1] = t * A.x * A.y - sine * A.z; elements[0][2] = t * A.x * A.z + sine * A.y; elements[1][0] = t * A.y * A.x + sine * A.z; elements[1][1] = t * A.y * A.y + cosine; elements[1][2] = t * A.y * A.z - sine * A.x; elements[2][0] = t * A.z * A.x - sine * A.y; elements[2][1] = t * A.z * A.y + sine * A.x; elements[2][2] = t * A.z * A.z + cosine; } // returns the inverse of an orthonormal matrix Matrix3x3 Matrix3x3::Orthonormal_Inverse () const { return (this->Transpose ()); } // returns the transpose of this matrix Matrix3x3 Matrix3x3::Transpose () const { Matrix3x3 temp; temp.elements[0][0] = elements[2][2]; temp.elements[0][1] = elements[2][1]; temp.elements[0][2] = elements[2][0]; temp.elements[1][0] = elements[1][2]; temp.elements[1][1] = elements[1][1]; temp.elements[1][2] = elements[1][0]; temp.elements[2][0] = elements[0][2]; temp.elements[2][1] = elements[0][1]; temp.elements[2][2] = elements[0][0]; return (temp); } // returns the determinant of the matrix float Matrix3x3::operator ! () const { return ((elements[0][0] * (elements[1][1] * elements[2][2] - elements[1][2] * elements[2][1])) - (elements[0][1] * (elements[1][0] * elements[2][2] - elements[1][2] * elements[2][0])) + (elements[0][2] * (elements[1][0] * elements[2][1] - elements[2][0] * elements[1][1]))); } // returns the inverse of the matrix Matrix3x3 Matrix3x3::Inverse () const { float det = !*this; Matrix3x3 temp; temp.elements[0][0] = (elements[1][1] * elements[2][2] - elements[1][2] * elements[2][1]) / det; temp.elements[0][1] = -(elements[0][1] * elements[2][2] - elements[2][1] * elements[0][2]) / det; temp.elements[0][2] = (elements[0][1] * elements[1][2] - elements[1][1] * elements[0][2]) / det; temp.elements[1][0] = -(elements[1][0] * elements[2][2] - elements[1][2] * elements[2][0]) / det; temp.elements[1][1] = (elements[0][0] * elements[2][2] - elements[2][0] * elements[0][2]) / det; temp.elements[1][2] = -(elements[0][0] * elements[1][2] - elements[1][0] * elements[0][2]) / det; temp.elements[2][0] = (elements[1][0] * elements[2][1] - elements[2][0] * elements[1][1]) / det; temp.elements[2][1] = -(elements[0][0] * elements[2][1] - elements[2][0] * elements[0][1]) / det; temp.elements[2][2] = (elements[0][0] * elements[1][1] - elements[0][1] * elements[1][0]) / det; return (temp); } // prints the properties of the maitrx void Matrix3x3::Matrix_Print (const char* name) const { cout << name << " :" << endl; cout << "[ " << elements[0][0] << " " << elements[0][1] << " " << elements[0][2] << " ]" << endl; cout << "[ " << elements[1][0] << " " << elements[1][1] << " " << elements[1][2] << " ]" << endl; cout << "[ " << elements[2][0] << " " << elements[2][1] << " " << elements[2][2] << " ]" << endl; cout << endl; }
26.376761
103
0.551128
mbrandonw
eb0a95beff1800d8a53cdd92d0c4cae0f40ec50d
4,054
cpp
C++
kernel_selector/core/actual_kernels/fully_connected/fully_connected_kernel_base.cpp
liyuming1978/clDNN
05e19dd2229dc977c2902ec360f3165ecb925b50
[ "BSL-1.0", "Intel", "Apache-2.0" ]
null
null
null
kernel_selector/core/actual_kernels/fully_connected/fully_connected_kernel_base.cpp
liyuming1978/clDNN
05e19dd2229dc977c2902ec360f3165ecb925b50
[ "BSL-1.0", "Intel", "Apache-2.0" ]
null
null
null
kernel_selector/core/actual_kernels/fully_connected/fully_connected_kernel_base.cpp
liyuming1978/clDNN
05e19dd2229dc977c2902ec360f3165ecb925b50
[ "BSL-1.0", "Intel", "Apache-2.0" ]
null
null
null
/* // Copyright (c) 2016 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 "fully_connected_kernel_base.h" #include "kernel_selector_utils.h" #include "common_tools.h" namespace KernelSelector { JitConstants FullyConnectedKernelBase::GetJitConstants(const FullyConnectedParams& params, const FullyConnectedKernelBase::DispatchData&) const { return MakeFullyConnectedJitConstants(params); } std::unique_ptr<FullyConnectedKernelBase::DispatchData> FullyConnectedKernelBase::SetDefault(const FullyConnectedParams& params) const { std::unique_ptr<DispatchData> dispatchData = std::make_unique<DispatchData>(); dispatchData->fp16UnitUsed = params.inputs[0].GetDType() == Datatype::F16; // Determine global work sizes. dispatchData->gws0 = params.output.LogicalSize(); dispatchData->gws1 = dispatchData->gws2 = 1; // Find largest positive local work size that is divider for global work size. dispatchData->lws0 = std::min(std::max(dispatchData->gws0, static_cast<size_t>(1)), static_cast<size_t>(32)); while (dispatchData->gws0 % dispatchData->lws0 != 0) { --dispatchData->lws0; } dispatchData->lws1 = dispatchData->lws2 = 1; return std::move(dispatchData); } KernelsData FullyConnectedKernelBase::GetCommonKernelsData(const Params& params, const OptionalParams& options, DataLayout dl, std::vector<WeightsLayout> wl, float estimated_time) const { if (!Validate(params, options) || wl.empty()) { return KernelsData(); } const auto& orgParams = static_cast<const FullyConnectedParams&>(params); const auto& orgOptParams = static_cast<const FullyConnectedOptionalParams&>(options); bool bProperInput = orgParams.inputs[0].GetLayout() == dl; if (!bProperInput && !orgParams.inputs[0].PitchesDifferFromLogicalDims()) { bProperInput = (dl == DataLayout::fb && orgParams.inputs[0].GetLayout() == DataLayout::fyxb) || (dl == DataLayout::bf && orgParams.inputs[0].GetLayout() == DataLayout::bfyx); } const bool bSupportedInput = orgOptParams.allowInputReordering || bProperInput; if (!bSupportedInput) { return KernelsData(); } KernelData kd = KernelData::Default<FullyConnectedParams>(params); FullyConnectedParams& newParams = *static_cast<FullyConnectedParams*>(kd.params.get()); if (!bProperInput) { newParams.inputs[0] = newParams.inputs[0].TransformIgnorePadding(dl); kd.reorderInput = true; } bool succeed = UpdateWeightsParams( newParams, options, wl, kd.weightsReorderParams); if (!succeed) { return{}; } kd.kernels.resize(1); auto entry_point = GetEntryPoint(kernelName, orgParams.layerID, options); const std::unique_ptr<DispatchData> runInfo = SetDefault(newParams); auto cldnn_jit = GetJitConstants(newParams, *runInfo.get()); std::string jit = CreateJit(kernelName, cldnn_jit, entry_point); auto& kernel = kd.kernels[0]; FillCLKernelData(kernel, *runInfo.get(), kernelName, jit, entry_point, ROUND_ROBIN, true, !orgParams.bias.empty()); kd.estimatedTime = estimated_time; kd.autoTuneIndex = -1; return{ kd }; } }
37.192661
189
0.656635
liyuming1978
eb0b3574be11276e7637fc8ad52a432e7a735406
600
hpp
C++
ios/IOS/IPCLog.hpp
StarMKWii/saoirse
1acd4b2c56a30b6e105130cb6a58f95dd4d5d440
[ "MIT" ]
7
2022-02-16T18:21:22.000Z
2022-02-27T18:39:07.000Z
ios/IOS/IPCLog.hpp
StarMKWii/saoirse
1acd4b2c56a30b6e105130cb6a58f95dd4d5d440
[ "MIT" ]
2
2022-02-16T18:36:14.000Z
2022-02-21T02:10:42.000Z
ios/IOS/IPCLog.hpp
StarMKWii/saoirse
1acd4b2c56a30b6e105130cb6a58f95dd4d5d440
[ "MIT" ]
1
2022-02-16T18:32:08.000Z
2022-02-16T18:32:08.000Z
// IPCLog.hpp - IOS to PowerPC logging through IPC // Written by Palapeli // // Copyright (C) 2022 Team Saoirse // SPDX-License-Identifier: MIT #pragma once #include <System/OS.hpp> #include <System/Types.h> class IPCLog { public: static IPCLog* sInstance; static constexpr int printSize = 256; IPCLog(); void Run(); void Print(const char* buffer); void Notify(); void WaitForStartRequest(); protected: void HandleRequest(IOS::Request* req); Queue<IOS::Request*> m_ipcQueue; Queue<IOS::Request*> m_responseQueue; Queue<int> m_startRequestQueue; };
19.354839
50
0.683333
StarMKWii
eb0ca5d8f491f3ebc3d3e2104e38c20e89a3d41c
5,049
cc
C++
build/fuchsia/pkg/lib/vfs/cpp/service_unittest.cc
chinmaygarde/buildroot
6b69caa4c7a04b6e81709bedd52297f29c2b1a14
[ "BSD-3-Clause" ]
1
2020-12-04T02:06:21.000Z
2020-12-04T02:06:21.000Z
build/fuchsia/pkg/lib/vfs/cpp/service_unittest.cc
mdempsky/flutter_buildroot
765b0ea58a095374a73943ad78471b915c2d63e1
[ "BSD-3-Clause" ]
null
null
null
build/fuchsia/pkg/lib/vfs/cpp/service_unittest.cc
mdempsky/flutter_buildroot
765b0ea58a095374a73943ad78471b915c2d63e1
[ "BSD-3-Clause" ]
1
2019-08-26T02:16:11.000Z
2019-08-26T02:16:11.000Z
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "lib/vfs/cpp/service.h" #include <fidl/examples/echo/cpp/fidl.h> #include <lib/fdio/vfs.h> #include <lib/fidl/cpp/binding_set.h> #include "lib/gtest/real_loop_fixture.h" #include "lib/vfs/cpp/pseudo_dir.h" class ServiceTest : public gtest::RealLoopFixture, public fidl::examples::echo::Echo { void EchoString(fidl::StringPtr value, EchoStringCallback callback) override { callback(answer_); } protected: ServiceTest() : answer_("my_fake_ans"), service_name_("echo_service"), second_loop_(&kAsyncLoopConfigNoAttachToThread) { auto service = std::make_unique<vfs::Service>( bindings_.GetHandler(this, second_loop_.dispatcher())); dir_.Serve(0, dir_ptr_.NewRequest().TakeChannel(), second_loop_.dispatcher()); dir_.AddEntry(service_name_, std::move(service)); second_loop_.StartThread("vfs test thread"); } const std::string& answer() const { return answer_; } const std::string& service_name() const { return service_name_; } void AssertInValidOpen(uint32_t flag, uint32_t mode, zx_status_t expected_status) { SCOPED_TRACE("flag: " + std::to_string(flag) + ", mode: " + std::to_string(mode)); fuchsia::io::NodePtr node_ptr; dir_ptr()->Open(flag | fuchsia::io::OPEN_FLAG_DESCRIBE, mode, service_name(), node_ptr.NewRequest()); bool on_open_called = false; node_ptr.events().OnOpen = [&](zx_status_t status, std::unique_ptr<fuchsia::io::NodeInfo> unused) { EXPECT_FALSE(on_open_called); // should be called only once on_open_called = true; EXPECT_EQ(expected_status, status); }; ASSERT_TRUE(RunLoopUntil([&]() { return on_open_called; }, zx::msec(1))); } fuchsia::io::DirectoryPtr& dir_ptr() { return dir_ptr_; } private: std::string answer_; std::string service_name_; fidl::BindingSet<Echo> bindings_; vfs::PseudoDir dir_; fuchsia::io::DirectoryPtr dir_ptr_; async::Loop second_loop_; }; TEST_F(ServiceTest, CanOpenAsNodeReferenceAndTestGetAttr) { fuchsia::io::NodeSyncPtr ptr; dir_ptr()->Open(fuchsia::io::OPEN_FLAG_NODE_REFERENCE, 0, service_name(), ptr.NewRequest()); zx_status_t s; fuchsia::io::NodeAttributes attr; ptr->GetAttr(&s, &attr); EXPECT_EQ(ZX_OK, s); EXPECT_EQ(fuchsia::io::MODE_TYPE_SERVICE, attr.mode & fuchsia::io::MODE_TYPE_SERVICE); } TEST_F(ServiceTest, CanCloneNodeReference) { fuchsia::io::NodeSyncPtr cloned_ptr; { fuchsia::io::NodeSyncPtr ptr; dir_ptr()->Open(fuchsia::io::OPEN_FLAG_NODE_REFERENCE, 0, service_name(), ptr.NewRequest()); ptr->Clone(0, cloned_ptr.NewRequest()); } zx_status_t s; fuchsia::io::NodeAttributes attr; cloned_ptr->GetAttr(&s, &attr); EXPECT_EQ(ZX_OK, s); EXPECT_EQ(fuchsia::io::MODE_TYPE_SERVICE, attr.mode & fuchsia::io::MODE_TYPE_SERVICE); } TEST_F(ServiceTest, TestDescribe) { fuchsia::io::NodeSyncPtr ptr; dir_ptr()->Open(fuchsia::io::OPEN_FLAG_NODE_REFERENCE, 0, service_name(), ptr.NewRequest()); fuchsia::io::NodeInfo info; ptr->Describe(&info); EXPECT_TRUE(info.is_service()); } TEST_F(ServiceTest, CanOpenAsAService) { uint32_t flags[] = {0, fuchsia::io::OPEN_RIGHT_READABLE, fuchsia::io::OPEN_RIGHT_WRITABLE}; uint32_t modes[] = { 0, fuchsia::io::MODE_TYPE_SERVICE, V_IRWXU, V_IRUSR, V_IWUSR, V_IXUSR}; for (uint32_t mode : modes) { for (uint32_t flag : flags) { SCOPED_TRACE("flag: " + std::to_string(flag) + ", mode: " + std::to_string(mode)); fidl::examples::echo::EchoSyncPtr ptr; dir_ptr()->Open(flag, mode, service_name(), fidl::InterfaceRequest<fuchsia::io::Node>( ptr.NewRequest().TakeChannel())); fidl::StringPtr ans; ptr->EchoString("hello", &ans); EXPECT_EQ(answer(), ans); } } } TEST_F(ServiceTest, CannotOpenServiceWithInvalidFlags) { uint32_t flags[] = {fuchsia::io::OPEN_RIGHT_ADMIN, fuchsia::io::OPEN_FLAG_CREATE, fuchsia::io::OPEN_FLAG_CREATE_IF_ABSENT, fuchsia::io::OPEN_FLAG_TRUNCATE, fuchsia::io::OPEN_FLAG_APPEND, fuchsia::io::OPEN_FLAG_NO_REMOTE}; for (uint32_t flag : flags) { AssertInValidOpen(flag, 0, ZX_ERR_NOT_SUPPORTED); } AssertInValidOpen(fuchsia::io::OPEN_FLAG_DIRECTORY, 0, ZX_ERR_NOT_DIR); } TEST_F(ServiceTest, CannotOpenServiceWithInvalidMode) { uint32_t modes[] = { fuchsia::io::MODE_TYPE_DIRECTORY, fuchsia::io::MODE_TYPE_BLOCK_DEVICE, fuchsia::io::MODE_TYPE_FILE, fuchsia::io::MODE_TYPE_SOCKET}; for (uint32_t mode : modes) { AssertInValidOpen(0, mode, ZX_ERR_INVALID_ARGS); } }
33
80
0.655575
chinmaygarde
eb0f489318ba55cba6be32810461375ad4ca1ed0
2,175
cpp
C++
tests/test_csrc/model/test_model.cpp
PeterH0323/mmdeploy-1
ac0b52f12ac897867b9bf3dae74b4192493b3d5f
[ "Apache-2.0" ]
null
null
null
tests/test_csrc/model/test_model.cpp
PeterH0323/mmdeploy-1
ac0b52f12ac897867b9bf3dae74b4192493b3d5f
[ "Apache-2.0" ]
null
null
null
tests/test_csrc/model/test_model.cpp
PeterH0323/mmdeploy-1
ac0b52f12ac897867b9bf3dae74b4192493b3d5f
[ "Apache-2.0" ]
null
null
null
// Copyright (c) OpenMMLab. All rights reserved. // clang-format off #include "catch.hpp" // clang-format on #include "mmdeploy/core/logger.h" #include "mmdeploy/core/model.h" #include "mmdeploy/core/model_impl.h" #include "test_resource.h" using namespace mmdeploy; TEST_CASE("model constructor", "[model]") { SECTION("default constructor") { Model model; REQUIRE(!model); } SECTION("explicit constructor with model path") { REQUIRE_THROWS(Model{"path/to/not/existing/model"}); } SECTION("explicit constructor with buffer") { REQUIRE_THROWS(Model{nullptr, 0}); } } TEST_CASE("model init", "[model]") { auto& gResource = MMDeployTestResources::Get(); for (auto& codebase : gResource.codebases()) { if (auto img_list = gResource.LocateImageResources(fs::path{codebase} / "images"); !img_list.empty()) { Model model; REQUIRE(model.Init(img_list.front()).has_error()); break; } } for (auto& codebase : gResource.codebases()) { for (auto& backend : gResource.backends()) { if (auto model_list = gResource.LocateModelResources(fs::path{codebase} / backend); !model_list.empty()) { Model model; REQUIRE(!model.Init(model_list.front()).has_error()); REQUIRE(!model.ReadFile("deploy.json").has_error()); auto const& meta = model.meta(); REQUIRE(!model.GetModelConfig(meta.models[0].name).has_error()); REQUIRE(model.GetModelConfig("not-existing-model").has_error()); break; } } } } TEST_CASE("ModelRegistry", "[model]") { class ANewModelImpl : public ModelImpl { Result<void> Init(const std::string& sdk_model_path) override { return Status(eNotSupported); } Result<std::string> ReadFile(const std::string& file_path) const override { return Status(eNotSupported); } Result<deploy_meta_info_t> ReadMeta() const override { deploy_meta_info_t meta; return meta; } }; // Test duplicated register. `DirectoryModel` is already registered. (void)ModelRegistry::Get().Register("DirectoryModel", []() -> std::unique_ptr<ModelImpl> { return std::make_unique<ANewModelImpl>(); }); }
32.462687
99
0.668506
PeterH0323
eb11c96949100356f0f01fb55f00ffa29279f7bf
584
cpp
C++
max7219/src/main.cpp
snakeye/stm32-projects
ed20e723dc1e50111c6b547fc142665b7db7843b
[ "MIT" ]
null
null
null
max7219/src/main.cpp
snakeye/stm32-projects
ed20e723dc1e50111c6b547fc142665b7db7843b
[ "MIT" ]
null
null
null
max7219/src/main.cpp
snakeye/stm32-projects
ed20e723dc1e50111c6b547fc142665b7db7843b
[ "MIT" ]
null
null
null
#include <SPI.h> #include "LedMatrix.h" #define NUMBER_OF_DEVICES 1 #define CS_PIN PB8 SPIClass SPI_2(PA7, PA6, PA5); LedMatrix ledMatrix = LedMatrix(NUMBER_OF_DEVICES, CS_PIN); int x = 0; void setup() { ledMatrix.init(); ledMatrix.setIntensity(3); ledMatrix.setText("MAX7219 Animation Demo"); ledMatrix.setNextText("Second text"); } void loop() { ledMatrix.clear(); ledMatrix.scrollTextLeft(); ledMatrix.drawText(); ledMatrix.commit(); delay(50); x = x + 1; if (x == 400) { ledMatrix.setNextText("Third text"); } }
16.222222
59
0.643836
snakeye
eb12579345dbf532985963fd617dd2411b575fe3
8,709
cpp
C++
src/layers/medWidgets/medWidgets.cpp
arthursw/medInria-public
d52af882c36f0d96cc433cc1a4082accaa1ca11a
[ "BSD-4-Clause" ]
61
2015-04-14T13:00:50.000Z
2022-03-09T22:22:18.000Z
src/layers/medWidgets/medWidgets.cpp
arthursw/medInria-public
d52af882c36f0d96cc433cc1a4082accaa1ca11a
[ "BSD-4-Clause" ]
510
2016-02-03T13:28:18.000Z
2022-03-23T10:23:44.000Z
src/layers/medWidgets/medWidgets.cpp
arthursw/medInria-public
d52af882c36f0d96cc433cc1a4082accaa1ca11a
[ "BSD-4-Clause" ]
36
2015-03-03T22:58:19.000Z
2021-12-28T18:19:23.000Z
/*========================================================================= medInria Copyright (c) INRIA 2013 - 2018. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include <medWidgets.h> namespace medWidgets { namespace pluginManager { void initialize(const QString& path, bool verbose) { for(QString const& realpath : path.split(';')) { if(realpath.isEmpty()) break; } } } namespace generic { namespace _private { medAbstractProcessPresenterFactory factory; } medAbstractProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace morphomathOperation { namespace erodeImage { namespace _private { medAbstractErodeImageProcessPresenterFactory factory; } medAbstractErodeImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace dilateImage { namespace _private { medAbstractDilateImageProcessPresenterFactory factory; } medAbstractDilateImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace openingImage { namespace _private { medAbstractOpeningImageProcessPresenterFactory factory; } medAbstractOpeningImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace closingImage { namespace _private { medAbstractClosingImageProcessPresenterFactory factory; } medAbstractClosingImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } } namespace arithmeticOperation { namespace addImage { namespace _private { medAbstractAddImageProcessPresenterFactory factory; } medAbstractAddImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace subtractImage { namespace _private { medAbstractSubtractImageProcessPresenterFactory factory; } medAbstractSubtractImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace multiplyImage { namespace _private { medAbstractMultiplyImageProcessPresenterFactory factory; } medAbstractMultiplyImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace divideImage { namespace _private { medAbstractDivideImageProcessPresenterFactory factory; } medAbstractDivideImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } } namespace maskImage { namespace _private { medAbstractMaskImageProcessPresenterFactory factory; } medAbstractMaskImageProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace dwiMasking { namespace _private { medAbstractDWIMaskingProcessPresenterFactory factory; } medAbstractDWIMaskingProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace diffusionModelEstimation { namespace _private { medAbstractDiffusionModelEstimationProcessPresenterFactory factory; } medAbstractDiffusionModelEstimationProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace diffusionScalarMaps { namespace _private { medAbstractDiffusionScalarMapsProcessPresenterFactory factory; } medAbstractDiffusionScalarMapsProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace tractography { namespace _private { medAbstractTractographyProcessPresenterFactory factory; } medAbstractTractographyProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace singleFilterOperation { namespace addFilter { namespace _private { medAbstractAddFilterProcessPresenterFactory factory; } medAbstractAddFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace divideFilter { namespace _private { medAbstractDivideFilterProcessPresenterFactory factory; } medAbstractDivideFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace gaussianFilter { namespace _private { medAbstractGaussianFilterProcessPresenterFactory factory; } medAbstractGaussianFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace invertFilter { namespace _private { medAbstractInvertFilterProcessPresenterFactory factory; } medAbstractInvertFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace medianFilter { namespace _private { medAbstractMedianFilterProcessPresenterFactory factory; } medAbstractMedianFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace multiplyFilter { namespace _private { medAbstractMultiplyFilterProcessPresenterFactory factory; } medAbstractMultiplyFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace normalizeFilter { namespace _private { medAbstractNormalizeFilterProcessPresenterFactory factory; } medAbstractNormalizeFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace shrinkFilter { namespace _private { medAbstractShrinkFilterProcessPresenterFactory factory; } medAbstractShrinkFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace subtractFilter { namespace _private { medAbstractSubtractFilterProcessPresenterFactory factory; } medAbstractSubtractFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace windowingFilter { namespace _private { medAbstractWindowingFilterProcessPresenterFactory factory; } medAbstractWindowingFilterProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace imageDenoising { namespace _private { medAbstractImageDenoisingProcessPresenterFactory factory; } medAbstractImageDenoisingProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace relaxometryEstimation { namespace _private { medAbstractRelaxometryEstimationProcessPresenterFactory factory; } medAbstractRelaxometryEstimationProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace symmetryAlignment { namespace _private { medAbstractSymmetryPlaneAlignmentProcessPresenterFactory factory; } medAbstractSymmetryPlaneAlignmentProcessPresenterFactory& presenterFactory() { return _private::factory; } } namespace biasCorrection { namespace _private { medAbstractBiasCorrectionProcessPresenterFactory factory; } medAbstractBiasCorrectionProcessPresenterFactory& presenterFactory() { return _private::factory; } } } } // end of medWidgets
21.450739
84
0.620393
arthursw
eb12e8c106cc2023e2424f6bdea758c0671c1f82
1,152
cpp
C++
acm/siweishixun/F.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
17
2016-01-01T12:57:25.000Z
2022-02-06T09:55:12.000Z
acm/siweishixun/F.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
null
null
null
acm/siweishixun/F.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
8
2018-12-27T01:31:49.000Z
2022-02-06T09:55:12.000Z
#include <iostream> #include <sstream> #include <ios> #include <iomanip> #include <functional> #include <algorithm> #include <vector> #include <string> #include <list> #include <queue> #include <deque> #include <stack> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <climits> #include <cctype> using namespace std; #define XINF INT_ma #define INF 0x3FFFFFFF #define MP(X,Y) make_pair(X,Y) #define PB(X) push_back(X) #define REP(X,N) for(int X=0;X<N;X++) #define REP2(X,L,R) for(int X=L;X<=R;X++) #define DEP(X,R,L) for(int X=R;X>=L;X--) #define CLR(A,X) memset(A,X,sizeof(A)) #define INF 0x3FFFFFFF #define IT iterator typedef long long ll; typedef pair<int,int> PII; typedef vector<PII> VII; typedef vector<int> VI; //const int maN = 10010; int T; int n; double ma,mi,num,sum,ave; int main(){ cin>>T; while(T--){ cin>>n; mi = 1000; ma = -1000; num = 0;sum = 0;ave = 0; REP(i,n) { cin>>num; if(mi>num){mi = num;} if(ma<num){ma = num;} sum += num; } printf("%.2lf,%.2lf,%.2lf\n",mi,ma,(sum - mi - ma)/(n-2)); } return 0; }
12.659341
60
0.625
xiaohuihuigh
eb13dabb8906f2b51e842205d1df729a27644de2
377
cpp
C++
TOI16/Camp-3/code.cpp
mrmuffinnxz/TOI-preparation
85a7d5b70d7fc661950bbb5de66a6885a835e755
[ "MIT" ]
null
null
null
TOI16/Camp-3/code.cpp
mrmuffinnxz/TOI-preparation
85a7d5b70d7fc661950bbb5de66a6885a835e755
[ "MIT" ]
null
null
null
TOI16/Camp-3/code.cpp
mrmuffinnxz/TOI-preparation
85a7d5b70d7fc661950bbb5de66a6885a835e755
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define endll "\n" int baseTwo(int n){ int left,a[100]; left=n; int i=0; while(left>0){ a[i+1]=left%2; left=left/2; i++; a[0]= left==1? 0:1 ; } for(int j=i;j>0;j--){ cout<<a[j]; } } main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); for(int i=0;i<4;i++){ baseTwo(i); cout << endll; } }
11.78125
30
0.543767
mrmuffinnxz
eb14d23764369379aee9cfa82cf6393c07699923
5,358
cpp
C++
stack/stackTest.cpp
hballaba/STL
d1064c102e87f6d871b61d251b9f383bead7b056
[ "Unlicense" ]
null
null
null
stack/stackTest.cpp
hballaba/STL
d1064c102e87f6d871b61d251b9f383bead7b056
[ "Unlicense" ]
null
null
null
stack/stackTest.cpp
hballaba/STL
d1064c102e87f6d871b61d251b9f383bead7b056
[ "Unlicense" ]
null
null
null
#include "stack.hpp" #include <stack> #include <vector> #include <deque> # define G "\e[92m\e[1m" # define D "\e[39m\e[0m" # define R "\e[91m" # define Y "\e[93m" int main() { try { /****** CONSTRUCTOR ********/ { std::cout << Y "My constructor\n" D; std::deque<int> mydeque1 (3,100); // deque with 3 elements std::vector<int> myvector1 (2,200); // vector with 2 elements ft::stack<int> first1; // empty stack ft::stack<int, std::deque<int> > second1(mydeque1); // stack initialized to copy of deque ft::stack<int,std::vector<int> > third1; // empty stack using vector ft::stack<int,std::vector<int> > fourth1 (myvector1); std::cout << "size of first: " << first1.size() << '\n'; std::cout << "size of second: " << second1.size() << '\n'; std::cout << "size of third: " << third1.size() << '\n'; std::cout << "size of fourth: " << fourth1.size() << '\n'; std::cout << Y"\nOriginal constructor\n"D; std::deque<int> origdeque (3,100); // deque with 3 elements std::vector<int> origvector (2,200); // vector with 2 elements std::stack<int> first; // empty stack std::stack<int> second (origdeque); // stack initialized to copy of deque std::stack<int,std::vector<int> > third; // empty stack using vector std::stack<int,std::vector<int> > fourth (origvector); std::cout << "size of first: " << first.size() << '\n'; std::cout << "size of second: " << second.size() << '\n'; std::cout << "size of third: " << third.size() << '\n'; std::cout << "size of fourth: " << fourth.size() << '\n'; } { std::cout << Y"My member function\n"D; std::stack<char> myStack; std::cout << "myStack empty = " << myStack.empty() << std::endl; myStack.push('A'); myStack.push('B'); myStack.push('C'); std::cout << "myStack empty = " << myStack.empty() << std::endl; std::cout << "size of myStack: " << myStack.size() << '\n'; std::cout << "top = " << myStack.top() << '\n'; myStack.top() += 5; //change top element + 5 std::cout << "top = " << myStack.top() << '\n'; myStack.pop(); std::cout << "After metod pop\n"; std::cout << "size of myStack: " << myStack.size() << '\n'; std::cout << "top = " << myStack.top() << '\n'; std::cout << "size of myStack: " << myStack.size() << '\n'; std::cout << Y"Original member function\n"D; std::stack<char> origStack; std::cout << "origStack empty = " << origStack.empty() << std::endl; origStack.push('A'); origStack.push('B'); origStack.push('C'); std::cout << "origStack empty = " << origStack.empty() << std::endl; std::cout << "size of origStack: " << origStack.size() << '\n'; std::cout << "top = " << origStack.top() << '\n'; origStack.top() += 5; std::cout << "top = " << origStack.top() << '\n'; origStack.pop(); std::cout << "After metod pop\n"; std::cout << "size of origStack: " << origStack.size() << '\n'; std::cout << "top = " << origStack.top() << '\n'; std::cout << "size of origStack: " << origStack.size() << '\n'; } { std::cout <<Y "My non-member function\n" D; ft::stack<int> myStack1; myStack1.push(5); ft::stack<int> myStack2; myStack1.push(3); std::cout << "'==' = " << (myStack1 == myStack2) << "\n"; std::cout << "'!=' = " << (myStack1 != myStack2) << "\n"; std::cout << "'>' = " << (myStack1 > myStack2) << "\n"; std::cout << "'>=' = " << (myStack1 >= myStack2) << "\n"; std::cout << "'<' = " << (myStack1 < myStack2) << "\n"; std::cout << "'<=' = " << (myStack1 == myStack2) << "\n"; std::cout <<Y "Original non-member function\n" D; std::stack<int> origStack1; origStack1.push(5); std::stack<int> origStack2; origStack2.push(3); std::cout << "'==' = " << (origStack1 == origStack2) << "\n"; std::cout << "'!=' = " << (origStack1 != origStack2) << "\n"; std::cout << "'>' = " << (origStack1 > origStack2) << "\n"; std::cout << "'>=' = " << (origStack1 >= origStack2) << "\n"; std::cout << "'<' = " << (origStack1 < origStack2) << "\n"; std::cout << "'<=' = " << (origStack1 == origStack2) << "\n"; std::cout << Y"Now you can check memory leaks, with leaks a.out in other terminal" << D"\n"; std::cout << G"To exit press Enter" << D"\n"; getchar(); std::cout << G"Good bye" << D"\n"; } } catch(const char * e) { std::cerr << e << '\n'; } catch(const std::exception& e) { std::cerr << e.what() << '\n'; } return 0; }
38.271429
109
0.447555
hballaba
a3e1fe9e435a8a803c5e1fa8f3443340cc22002a
11,551
hpp
C++
object_database/View.hpp
APrioriInvestments/object_database
d44b8432490b36b1ace67de0e23fb59f7ce9b529
[ "Apache-2.0" ]
2
2021-02-23T18:28:40.000Z
2021-04-18T03:00:53.000Z
object_database/View.hpp
APrioriInvestments/object_database
d44b8432490b36b1ace67de0e23fb59f7ce9b529
[ "Apache-2.0" ]
115
2019-10-08T18:32:58.000Z
2021-02-12T20:16:14.000Z
object_database/View.hpp
APrioriInvestments/object_database
d44b8432490b36b1ace67de0e23fb59f7ce9b529
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** Copyright 2017-2019 object_database Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ #pragma once #include "DatabaseConnectionState.hpp" #include "HashFunctions.hpp" #include <unordered_set> #include <unordered_map> /********** Views provide running (native)python threads with a snapshotted view of the current object-database's subscribed data. A view holds a reference to a collection of objects that have different representation at different transaction_ids, along with a single transaction_id. We show a coherent view of all the objects whose versions are <= the given transaction_id. We also track all objects and indices we read or write during execution. ***********/ class View { public: View(std::shared_ptr<DatabaseConnectionState> connection, transaction_id tid, bool allowWrites) : m_tid(tid), m_allow_writes(allowWrites), m_enclosing_view(nullptr), m_is_entered(false), m_ever_entered(false), m_versioned_objects(*connection->getVersionedObjects()), m_connection_state(connection) { m_connection_state->increfVersion(m_tid); m_serialization_context = m_connection_state->getContext(); } ~View() { if (!m_ever_entered) { m_connection_state->decrefVersion(m_tid); } } void setSerializationContext(std::shared_ptr<SerializationContext> context) { m_serialization_context = context; } std::shared_ptr<SerializationContext> getSerializationContext() { return m_serialization_context; } void enter() { if (m_is_entered || m_ever_entered) { throw std::runtime_error("Can't enter a view twice."); } m_ever_entered = true; m_is_entered = true; m_enclosing_view = s_current_view; s_current_view = this; } static View* currentView() { return s_current_view; } void exit() { if (!m_is_entered) { throw std::runtime_error("Can't exit an un-entered view."); } m_is_entered = false; s_current_view = m_enclosing_view; m_enclosing_view = nullptr; m_connection_state->decrefVersion(m_tid); } bool objectIsVisible(SchemaAndTypeName objType, object_id oid) { return m_connection_state->objectIsVisible(objType, oid, m_tid); } void loadLazyObjectIfNeeded(object_id oid) { m_connection_state->loadLazyObjectIfNeeded(oid); } void newObject(SchemaAndTypeName obType, object_id oid) { m_connection_state->markObjectSubscribed(obType, oid, m_tid); } // lookup the current value of an object. if we have written to it, use that value. // otherwise use the value in the view. If the value does not exist, returns a null pointer. // we also record what values were read instance_ptr getField(field_id field, object_id oid, Type* t, bool recordAccess=true) { auto delete_it = m_delete_cache.find(std::make_pair(field, oid)); if (delete_it != m_delete_cache.end()) { return nullptr; } auto write_it = m_write_cache.find(std::make_pair(field, oid)); if (write_it != m_write_cache.end()) { return write_it->second.data(); } instance_ptr i = m_versioned_objects.bestObjectVersion(t, m_serialization_context, field, oid, m_tid).first; if (recordAccess) { m_read_values.insert(std::make_pair(field, oid)); } return i; } bool fieldExists(field_id field, object_id oid, Type* t, bool recordAccess=true) { auto delete_it = m_delete_cache.find(std::make_pair(field, oid)); if (delete_it != m_delete_cache.end()) { return false; } auto write_it = m_write_cache.find(std::make_pair(field, oid)); if (write_it != m_write_cache.end()) { return true; } bool res = m_versioned_objects.existsAtTransaction(t, field, oid, m_tid); if (recordAccess) { m_read_values.insert(std::make_pair(field, oid)); } return res; } void setField(field_id field, object_id oid, Type* t, instance_ptr data) { if (!m_allow_writes) { throw std::runtime_error("Please use a transaction if you wish to write to object_database fields."); } auto delete_it = m_delete_cache.find(std::make_pair(field, oid)); if (delete_it != m_delete_cache.end()) { throw std::runtime_error("Value is deleted."); } if (data) { //if we're writing a new value, record whether this is a new object //that we're populating into 'm_new_writes' bool existsAlready = fieldExists(field, oid, t, false); if (!existsAlready) { m_new_writes.insert(std::make_pair(field, oid)); } m_write_cache[std::make_pair(field, oid)] = Instance(data, t); } else { bool wasNewWrite = m_new_writes.find(std::make_pair(field, oid)) != m_new_writes.end(); m_write_cache.erase(std::make_pair(field, oid)); if (!wasNewWrite) { //if the object already existed, we need to mark that we're deleting it m_delete_cache.insert(std::make_pair(field, oid)); } } } void indexAdd(field_id fid, index_value i, object_id o) { IndexKey key(fid, i); //check if we are adding something back to an index it was removed from already auto remove_it = m_set_removes.find(key); if (remove_it != m_set_removes.end()) { auto it = remove_it->second.find(o); if (it != remove_it->second.end()) { remove_it->second.erase(it); return; } } if (m_versioned_objects.indexContains(fid, i, m_tid, o)) { throw std::runtime_error("Index already contains this value."); } m_set_adds[key].insert(o); } void indexRemove(field_id fid, index_value i, object_id o) { IndexKey key(fid, i); //check if we are adding something back to an index it was removed from already auto add_it = m_set_adds.find(key); if (add_it != m_set_adds.end()) { auto it = add_it->second.find(o); if (it != add_it->second.end()) { add_it->second.erase(it); return; } } if (!m_versioned_objects.indexContains(fid, i, m_tid, o)) { throw std::runtime_error("Index doesn't contain this value."); } m_set_removes[key].insert(o); } bool shouldSuppressIndexValue(field_id fid, index_value i, object_id o) { auto remove_it = m_set_removes.find(IndexKey(fid, i)); if (remove_it == m_set_removes.end()) { return false; } return remove_it->second.find(o) != remove_it->second.end(); } object_id firstAddedIndexValue(field_id fid, index_value i) { auto add_it = m_set_adds.find(IndexKey(fid, i)); if (add_it == m_set_adds.end()) { return NO_OBJECT; } if (add_it->second.size() == 0) { return NO_OBJECT; } return *add_it->second.begin(); } object_id nextAddedIndexValue(field_id fid, index_value i, object_id o) { auto add_it = m_set_adds.find(IndexKey(fid, i)); if (add_it == m_set_adds.end()) { return NO_OBJECT; } auto next_ob_it = add_it->second.upper_bound(o); if (next_ob_it == add_it->second.end()) { return NO_OBJECT; } return *next_ob_it; } object_id indexLookupFirst(field_id fid, index_value i) { m_set_reads.insert(IndexKey(fid, i)); //we need to suppress anything in 'm_set_removes' and add anything in 'm_set_adds' object_id first = m_versioned_objects.indexLookupFirst(fid, i, m_tid); object_id firstAdded = firstAddedIndexValue(fid, i); if (first == NO_OBJECT) { return firstAdded; } //loop until we find a value in the main set that's lower than 'firstAdded' while (true) { if (firstAdded != NO_OBJECT && firstAdded < first) { return firstAdded; } if (!shouldSuppressIndexValue(fid, i, first)) { return first; } first = m_versioned_objects.indexLookupNext(fid, i, m_tid, first); if (first == NO_OBJECT) { return firstAdded; } } } object_id indexLookupNext(field_id fid, index_value i, object_id o) { m_set_reads.insert(IndexKey(fid, i)); object_id next = m_versioned_objects.indexLookupNext(fid, i, m_tid, o); object_id nextAdded = nextAddedIndexValue(fid, i, o); if (next == NO_OBJECT) { return nextAdded; } //loop until we find a value in the main set that's lower than 'firstAdded' while (true) { if (nextAdded != NO_OBJECT && nextAdded < next) { return nextAdded; } if (!shouldSuppressIndexValue(fid, i, next)) { return next; } next = m_versioned_objects.indexLookupNext(fid, i, m_tid, next); if (next == NO_OBJECT) { return nextAdded; } } } DatabaseConnectionState& getConnectionState() { return *m_connection_state; } bool isWriteable() const { return m_allow_writes; } const std::unordered_set<std::pair<field_id, object_id> >& getReadValues() const { return m_read_values; } const std::unordered_map<std::pair<field_id, object_id>, Instance>& getWriteCache() const { return m_write_cache; } const std::unordered_set<std::pair<field_id, object_id> >& getDeleteCache() const { return m_delete_cache; } const std::unordered_map<IndexKey, std::set<object_id> >& getSetAdds() const { return m_set_adds; } const std::unordered_map<IndexKey, std::set<object_id> >& getSetRemoves() const { return m_set_removes; } const std::unordered_set<IndexKey >& getSetReads() const { return m_set_reads; } transaction_id getTransactionId() const { return m_tid; } private: static thread_local View* s_current_view; //the transaction id that snapshots this view transaction_id m_tid; //is this a view or a transaction? bool m_allow_writes; View* m_enclosing_view; bool m_is_entered; bool m_ever_entered; std::unordered_set<std::pair<field_id, object_id> > m_read_values; std::unordered_map<std::pair<field_id, object_id>, Instance> m_write_cache; std::unordered_set<std::pair<field_id, object_id> > m_new_writes; std::unordered_set<std::pair<field_id, object_id> > m_delete_cache; std::unordered_map<IndexKey, std::set<object_id> > m_set_adds; std::unordered_map<IndexKey, std::set<object_id> > m_set_removes; std::unordered_set<IndexKey > m_set_reads; VersionedObjects& m_versioned_objects; std::shared_ptr<DatabaseConnectionState> m_connection_state; std::shared_ptr<SerializationContext> m_serialization_context; };
30.23822
114
0.644793
APrioriInvestments
a3e4539f4971a33311c2b5d816d06f0e2708ab7e
1,121
hpp
C++
include/SSVOpenHexagon/Global/Version.hpp
PKPenguin321/SSVOpenHexagon
1fcc25fea8f0ef6845d9b5502455a76563df91c3
[ "AFL-3.0" ]
20
2021-12-02T17:49:54.000Z
2022-03-26T05:52:26.000Z
include/SSVOpenHexagon/Global/Version.hpp
PKPenguin321/SSVOpenHexagon
1fcc25fea8f0ef6845d9b5502455a76563df91c3
[ "AFL-3.0" ]
4
2022-01-07T19:06:01.000Z
2022-03-28T01:26:16.000Z
include/SSVOpenHexagon/Global/Version.hpp
PKPenguin321/SSVOpenHexagon
1fcc25fea8f0ef6845d9b5502455a76563df91c3
[ "AFL-3.0" ]
1
2022-01-27T09:18:06.000Z
2022-01-27T09:18:06.000Z
// Copyright (c) 2013-2020 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: https://opensource.org/licenses/AFL-3.0 #pragma once namespace hg { // Allow us to represent the game's version in a major.minor.micro format struct GameVersion { int major; int minor; int micro; [[nodiscard]] constexpr bool operator<( const GameVersion& rhs) const noexcept { if(major != rhs.major) { return major < rhs.major; } if(minor != rhs.minor) { return minor < rhs.minor; } return micro < rhs.micro; } [[nodiscard]] constexpr bool operator==( const GameVersion& other) const noexcept { return (major == other.major) && (minor == other.minor) && (micro == other.micro); } [[nodiscard]] constexpr bool operator!=( const GameVersion& other) const noexcept { return !(*this == other); } }; inline constexpr GameVersion GAME_VERSION{2, 1, 4}; inline constexpr auto& GAME_VERSION_STR = "2.1.4"; } // namespace hg
22.42
73
0.58876
PKPenguin321
a3e7ea2097625ce49ecdf662156aced1be48fa5c
6,153
cpp
C++
ace/ace/IOStream_T.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
ace/ace/IOStream_T.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
ace/ace/IOStream_T.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
// IOStream_T.cpp,v 4.20 2000/04/19 02:49:34 brunsch Exp #ifndef ACE_IOSTREAM_T_C #define ACE_IOSTREAM_T_C #include "ace/IOStream_T.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ ACE_RCSID(ace, IOStream_T, "IOStream_T.cpp,v 4.20 2000/04/19 02:49:34 brunsch Exp") #if !defined (ACE_LACKS_ACE_IOSTREAM) #if defined (ACE_HAS_MINIMUM_IOSTREAMH_INCLUSION) && defined (__GNUG__) # if !defined (ACE_IOSTREAM_T_H) // _Only_ define this when compiling this .cpp file standalone, not // when instantiating templates. Its purpose is to provide something // for global constructors and destructors to be tied to. Without it, // they would be tied to the file(name). With Cygnus g++ 2.7.2/VxWorks, // that name is used directly in variable names in the munched ctor/dtor // file. That name contains a ".", so it's not a legal C variable name. // The root of all this trouble is a static instance (of Iostream_init) // declared in the iostream.h header file. int ACE_IOStream_global_of_builtin_type_to_avoid_munch_problems = 0; # endif /* ! ACE_IOSTREAM_T_H */ #endif /* ACE_HAS_MINIMUM_IOSTREAMH_INCLUSION && __GNUG__ */ #if !defined (__ACE_INLINE__) #include "ace/IOStream_T.i" #endif /* !__ACE_INLINE__ */ // We will be given a STREAM by the iostream object which creates us. // See the ACE_IOStream template for how that works. Like other // streambuf objects, we can be input-only, output-only or both. template <class STREAM> ACE_Streambuf_T<STREAM>::ACE_Streambuf_T (STREAM *peer, u_int streambuf_size, int io_mode) : ACE_Streambuf (streambuf_size, io_mode), peer_ (peer) { // A streambuf allows for unbuffered IO where every character is // read as requested and written as provided. To me, this seems // terribly inefficient for socket-type operations, so I've disabled // it. All of the work would be done by the underflow/overflow // functions anyway and I haven't implemented anything there to // support unbuffered IO. #if !defined (ACE_LACKS_UNBUFFERED_STREAMBUF) this->unbuffered (0); #endif /* ! ACE_LACKS_UNBUFFERED_STREAMBUF */ // Linebuffered is similar to unbuffered. Again, I don't have any // need for this and I don't see the advantage. I believe this // would have to be supported by underflow/overflow to be effective. #if !defined (ACE_LACKS_LINEBUFFERED_STREAMBUF) this->linebuffered (0); #endif /* ! ACE_LACKS_LINEBUFFERED_STREAMBUF */ } // The typical constructor. This will initiailze your STREAM and then // setup the iostream baseclass to use a custom streambuf based on // STREAM. template <class STREAM> ACE_IOStream<STREAM>::ACE_IOStream (STREAM &stream, u_int streambuf_size) : iostream (0), STREAM (stream) { ACE_NEW (streambuf_, ACE_Streambuf_T<STREAM> ((STREAM *) this, streambuf_size)); iostream::init (this->streambuf_); } template <class STREAM> ACE_IOStream<STREAM>::ACE_IOStream (u_int streambuf_size) : iostream (0) { ACE_NEW (this->streambuf_, ACE_Streambuf_T<STREAM> ((STREAM *) this, streambuf_size)); iostream::init (this->streambuf_); } // We have to get rid of the streambuf_ ourselves since we gave it to // iostream () template <class STREAM> ACE_IOStream<STREAM>::~ACE_IOStream (void) { delete this->streambuf_; } // The only ambituity in the multiple inheritance is the close () // function. template <class STREAM> int ACE_IOStream<STREAM>::close (void) { return STREAM::close (); } template <class STREAM> ACE_IOStream<STREAM> & ACE_IOStream<STREAM>::operator>> (ACE_Time_Value *&tv) { ACE_Time_Value *old_tv = this->streambuf_->recv_timeout (tv); tv = old_tv; return *this; } #if defined (ACE_HAS_STRING_CLASS) // A simple string operator. The base iostream has 'em for char* but // that isn't always the best thing for a String. If we don't provide // our own here, we may not get what we want. template <class STREAM> ACE_IOStream<STREAM> & ACE_IOStream<STREAM>::operator>> (ACE_IOStream_String &v) { if (ipfx0 ()) { char c; this->get (c); for (v = c; this->get (c) && !isspace (c); v += c) continue; } isfx (); return *this; } template <class STREAM> ACE_IOStream<STREAM> & ACE_IOStream<STREAM>::operator<< (ACE_IOStream_String &v) { if (opfx ()) { #if defined (ACE_WIN32) && defined (_MSC_VER) for (int i = 0; i < v.GetLength (); ++i) #else for (u_int i = 0; i < (u_int) v.length (); ++i) #endif /* ACE_WIN32 && defined (_MSC_VER) */ this->put (v[i]); } osfx (); return *this; } // A more clever put operator for strings that knows how to deal with // quoted strings containing back-quoted quotes. template <class STREAM> STREAM & operator>> (STREAM &stream, ACE_Quoted_String &str) { char c; if (!(stream >> c)) // eat space up to the first char // stream.set (ios::eofbit|ios::failbit); return stream; str = ""; // Initialize the string // if we don't have a quote, append until we see space if (c != '"') for (str = c; stream.get (c) && !isspace (c); str += c) continue; else for (; stream.get (c) && c != '"'; str += c) if (c == '\\') { stream.get (c); if (c != '"') str += '\\'; } return stream; } template <class STREAM> STREAM & operator<< (STREAM &stream, ACE_Quoted_String &str) { stream.put ('"'); for (u_int i = 0; i < str.length (); ++i) { if (str[i] == '"') stream.put ('\\'); stream.put (str[i]); } stream.put ('"'); return stream; } #endif /* ACE_HAS_STRING_CLASS */ #endif /* ACE_LACKS_ACE_IOSTREAM */ #endif /* ACE_IOSTREAM_T_C */
29.161137
84
0.627011
tharindusathis
a3eebe0c006811c0ed4bb8aed14a43b19205af91
432
cpp
C++
Firmware/unit_tests/tests/LcdBacklightTest/LcdBacklightTest.cpp
zukaitis/midi-grid
527ad37348983f481511fef52d1645eab3a2f60e
[ "BSD-3-Clause" ]
59
2018-03-17T10:32:48.000Z
2022-03-19T17:59:29.000Z
Firmware/unit_tests/tests/LcdBacklightTest/LcdBacklightTest.cpp
zukaitis/midi-grid
527ad37348983f481511fef52d1645eab3a2f60e
[ "BSD-3-Clause" ]
3
2019-11-12T09:49:59.000Z
2020-12-09T11:55:00.000Z
Firmware/unit_tests/tests/LcdBacklightTest/LcdBacklightTest.cpp
zukaitis/midi-grid
527ad37348983f481511fef52d1645eab3a2f60e
[ "BSD-3-Clause" ]
10
2019-03-14T22:53:39.000Z
2021-12-26T13:42:20.000Z
#include <gtest/gtest.h> #include "lcd/backlight/Backlight.h" #include "hardware/lcd/MockBacklightDriver.h" #include "freertos/MockThread.h" int main( int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } TEST( BacklightConstructor, Create ) { hardware::lcd::MockBacklightDriver mockBacklightDriver; const lcd::Backlight backlight( mockBacklightDriver ); SUCCEED(); }
20.571429
59
0.722222
zukaitis
a3f449eedbe5c0a195b2ab24f722062600fb5af9
28,928
cc
C++
attestation/server/pkcs11_key_store_test.cc
kalyankondapally/chromiumos-platform2
5e5337009a65b1c9aa9e0ea565f567438217e91f
[ "BSD-3-Clause" ]
null
null
null
attestation/server/pkcs11_key_store_test.cc
kalyankondapally/chromiumos-platform2
5e5337009a65b1c9aa9e0ea565f567438217e91f
[ "BSD-3-Clause" ]
null
null
null
attestation/server/pkcs11_key_store_test.cc
kalyankondapally/chromiumos-platform2
5e5337009a65b1c9aa9e0ea565f567438217e91f
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
// Copyright 2015 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "attestation/server/pkcs11_key_store.h" #include <map> #include <string> #include <vector> #include <base/logging.h> #include <base/strings/string_number_conversions.h> #include <chaps/attributes.h> #include <chaps/chaps_proxy_mock.h> #include <chaps/token_manager_client_mock.h> #include <brillo/cryptohome.h> #include <brillo/map_utils.h> #include <gmock/gmock.h> #include <gtest/gtest.h> using ::testing::_; using ::testing::DoAll; using ::testing::Invoke; using ::testing::NiceMock; using ::testing::Return; using ::testing::SetArgPointee; namespace { const uint64_t kSession = 7; // Arbitrary non-zero value. const char kDefaultUser[] = "test_user"; const char kValidRsaPublicKeyHex[] = "3082010A0282010100" "961037BC12D2A298BEBF06B2D5F8C9B64B832A2237F8CF27D5F96407A6041A4D" "AD383CB5F88E625F412E8ACD5E9D69DF0F4FA81FCE7955829A38366CBBA5A2B1" "CE3B48C14B59E9F094B51F0A39155874C8DE18A0C299EBF7A88114F806BE4F25" "3C29A509B10E4B19E31675AFE3B2DA77077D94F43D8CE61C205781ED04D183B4" "C349F61B1956C64B5398A3A98FAFF17D1B3D9120C832763EDFC8F4137F6EFBEF" "46D8F6DE03BD00E49DEF987C10BDD5B6F8758B6A855C23C982DDA14D8F0F2B74" "E6DEFA7EEE5A6FC717EB0FF103CB8049F693A2C8A5039EF1F5C025DC44BD8435" "E8D8375DADE00E0C0F5C196E04B8483CC98B1D5B03DCD7E0048B2AB343FFC11F" "0203" "010001"; const char kValidRsaCertificateHex[] = "3082040f308202f7a003020102020900bd0f8fd6bf496b67300d06092a864886" "f70d01010b050030819d310b3009060355040613025553311330110603550408" "0c0a43616c69666f726e69613116301406035504070c0d4d6f756e7461696e20" "5669657731133011060355040a0c0a4368726f6d69756d4f533111300f060355" "040b0c08556e6974546573743117301506035504030c0e506b637331314b6579" "53746f72653120301e06092a864886f70d010901161174657374406368726f6d" "69756d2e6f7267301e170d3135303231383137303132345a170d313731313133" "3137303132345a30819d310b3009060355040613025553311330110603550408" "0c0a43616c69666f726e69613116301406035504070c0d4d6f756e7461696e20" "5669657731133011060355040a0c0a4368726f6d69756d4f533111300f060355" "040b0c08556e6974546573743117301506035504030c0e506b637331314b6579" "53746f72653120301e06092a864886f70d010901161174657374406368726f6d" "69756d2e6f726730820122300d06092a864886f70d01010105000382010f0030" "82010a0282010100a8fb9e12b1e5298b9a24fabc3901d00c32057392c763836e" "0b55cff8e67d39b9b9853920fd615688b3e13c03a10cb5668187819172d1d269" "70f0ff8d4371ac581f6970a0e43a1d0d61a94741a771fe86aee45ab0ca059b1f" "c067f7416f08544cc4d08ec884b6d4327bb3ec0dc0789639375bd159df0efd87" "1cf4d605778c7a68c96b94cf0a6c29f9a23bc027e8250084eb2dfca817b20f57" "a6fe09513f884389db7b90788aea70c6e1638f24e39553ac0f859e585965c425" "9ed7b9680fde3e059f254d8c9494f6ab425ede80d63366dfcb7cc311f5bc6fb0" "1c27d81f4c5112d04b7614c37ba19c014916816372c773e4e44564fac34565ad" "ebf38fe56c1413170203010001a350304e301d0603551d0e04160414fe13c7db" "459bd2881e9113198e1f072e16cea144301f0603551d23041830168014fe13c7" "db459bd2881e9113198e1f072e16cea144300c0603551d13040530030101ff30" "0d06092a864886f70d01010b05000382010100a163d636ac64bd6f67eca53708" "5f92abc993a40fd0c0222a56b262c29f88057a3edf9abac024756ad85d7453d8" "4782e0be65d176aecfb0fbfc88ca567d17124fa190cb5ce832264360dd6daee1" "e121428de28dda0b8ba117a1be3cf438efd060a3b5fc812e7eba70cec12cb609" "738fc7d0912546c42b5aaadb142adce2167c7f30cd9e0049687d384334335aff" "72aebd1745a0aac4be816365969347f064f36f7fdec69f970f28b87061650470" "c63be8475bb23d0485985fb77c7cdd9d9fe008211a9ddd0fe68efb0b47cf629c" "941d31e3c2f88e670e7e4ef1129febad000e6a16222779fbfe34641e5243ca38" "74e2ad06f9585a00bec014744d3175ecc4808d"; constexpr char kValidEccPublicKeyHex[] = "3059301306072A8648CE3D020106082A8648CE3D030107034200045C9633047E7518B3E0DF" "6C019BAA7CC8D0CB1F18DB781B382E02273054A304CCBEEAD2ED273DA1D6FCDFAB8B55DE4E" "830FF43899F82DB6104381615992542F3D"; constexpr char kValidEccCertificateHex[] = "3082032930820211a00302010202160174fb9852da9f991b7fd47ebd190000000000001418" "300d06092a864886f70d01010505003081853120301e060355040313175072697661637920" "434120496e7465726d65646961746531123010060355040b13094368726f6d65204f533113" "3011060355040a130a476f6f676c6520496e63311630140603550407130d4d6f756e746169" "6e2056696577311330110603550408130a43616c69666f726e6961310b3009060355040613" "025553301e170d3230313030363034313032395a170d3232313030363034313032395a303d" "31183016060355040b130f73746174653a646576656c6f7065723121301f060355040a1318" "4368726f6d652044657669636520456e74657270726973653059301306072a8648ce3d0201" "06082a8648ce3d030107034200045c9633047e7518b3e0df6c019baa7cc8d0cb1f18db781b" "382e02273054a304ccbeead2ed273da1d6fcdfab8b55de4e830ff43899f82db61043816159" "92542f3da381a030819d30290603551d0e04220420837f40ecb000f7ffccda6dab8cd526d9" "43b6fe8ce56c84be5dc70cd3ed8f7410302b0603551d23042430228020f420b6d9d862f68b" "0915ce8b57a4fc574eb8c17ca5f9e656dbd0529429bd6d7f300e0603551d0f0101ff040403" "020780300c0603551d130101ff0402300030110603551d20040a300830060604551d200030" "12060a2b06010401d679020113040404020802300d06092a864886f70d0101050500038201" "010028a2e3a90c10a850cbee4e575da068bee21753212cc551b0f09eb327a15df01dffec87" "2509dedf06c9f34a5e9c987fb5c0d0878a400056c082f015d3153159a38dd71b6dd73e8dad" "2f1ce6ac43ed7cf550e8627b5d21dcf41661fcbc58075be7993b8cd7c06941b712ae052609" "6a20e559c9fb0cf3da807d261563cdddc74c18998ebd2859b26156d0c8bee2784dc8d6aeff" "d5400331466bdec5f6384cdad7f5e5eb620a246eb0e0ac8624e2f76d70207a4574adb53277" "4974ef08aedfb8dd3c05979b126414d17a7c1ad5bbc13f0bf95b1cded312837839aa344979" "151dc4f70ad86c842091d305a9b667b4e4bd67d6b2e3aa1df385a09553ae2028c9f18b45"; std::string HexDecode(const std::string hex) { std::vector<uint8_t> output; CHECK(base::HexStringToBytes(hex, &output)); return std::string(reinterpret_cast<char*>(output.data()), output.size()); } class ScopedFakeSalt { public: ScopedFakeSalt() : salt_(128, 0) { brillo::cryptohome::home::SetSystemSalt(&salt_); } ~ScopedFakeSalt() { brillo::cryptohome::home::SetSystemSalt(nullptr); } private: std::string salt_; }; class ScopedDisableVerboseLogging { public: ScopedDisableVerboseLogging() : original_severity_(logging::GetMinLogLevel()) { logging::SetMinLogLevel(logging::LOG_INFO); } ~ScopedDisableVerboseLogging() { logging::SetMinLogLevel(original_severity_); } private: logging::LogSeverity original_severity_; }; } // namespace namespace attestation { typedef chaps::ChapsProxyMock Pkcs11Mock; // Implements a fake PKCS #11 object store. Labeled data blobs can be stored // and later retrieved. The mocked interface is ChapsInterface so these // tests must be linked with the Chaps PKCS #11 library. The mock class itself // is part of the Chaps package; it is reused here to avoid duplication (see // chaps_proxy_mock.h). class KeyStoreTest : public testing::Test { public: KeyStoreTest() : pkcs11_(false), // Do not pre-initialize the mock PKCS #11 library. // This just controls whether the first call to // C_Initialize returns 'already initialized'. next_handle_(1) {} ~KeyStoreTest() override = default; void SetUp() override { std::vector<uint64_t> slot_list = {0, 1}; ON_CALL(pkcs11_, GetSlotList(_, _, _)) .WillByDefault(DoAll(SetArgPointee<2>(slot_list), Return(0))); ON_CALL(pkcs11_, OpenSession(_, _, _, _)) .WillByDefault(DoAll(SetArgPointee<3>(kSession), Return(0))); ON_CALL(pkcs11_, CloseSession(_, _)).WillByDefault(Return(0)); ON_CALL(pkcs11_, CreateObject(_, _, _, _)) .WillByDefault(Invoke(this, &KeyStoreTest::CreateObject)); ON_CALL(pkcs11_, DestroyObject(_, _, _)) .WillByDefault(Invoke(this, &KeyStoreTest::DestroyObject)); ON_CALL(pkcs11_, GetAttributeValue(_, _, _, _, _)) .WillByDefault(Invoke(this, &KeyStoreTest::GetAttributeValue)); ON_CALL(pkcs11_, SetAttributeValue(_, _, _, _)) .WillByDefault(Invoke(this, &KeyStoreTest::SetAttributeValue)); ON_CALL(pkcs11_, FindObjectsInit(_, _, _)) .WillByDefault(Invoke(this, &KeyStoreTest::FindObjectsInit)); ON_CALL(pkcs11_, FindObjects(_, _, _, _)) .WillByDefault(Invoke(this, &KeyStoreTest::FindObjects)); ON_CALL(pkcs11_, FindObjectsFinal(_, _)).WillByDefault(Return(0)); base::FilePath system_path("/var/lib/chaps"); ON_CALL(token_manager_, GetTokenPath(_, 0, _)) .WillByDefault(DoAll(SetArgPointee<2>(system_path), Return(true))); base::FilePath user_path( brillo::cryptohome::home::GetDaemonStorePath(kDefaultUser, "chaps")); ON_CALL(token_manager_, GetTokenPath(_, 1, _)) .WillByDefault(DoAll(SetArgPointee<2>(user_path), Return(true))); } // Stores a new labeled object, only CKA_LABEL and CKA_VALUE are relevant. virtual uint32_t CreateObject(const brillo::SecureBlob& isolate, uint64_t session_id, const std::vector<uint8_t>& attributes, uint64_t* new_object_handle) { *new_object_handle = next_handle_++; std::string label = GetValue(attributes, CKA_LABEL); handles_[*new_object_handle] = label; values_[label] = GetValue(attributes, CKA_VALUE); labels_[label] = *new_object_handle; return CKR_OK; } // Deletes a labeled object. virtual uint32_t DestroyObject(const brillo::SecureBlob& isolate, uint64_t session_id, uint64_t object_handle) { std::string label = handles_[object_handle]; handles_.erase(object_handle); values_.erase(label); labels_.erase(label); return CKR_OK; } // Supports reading CKA_VALUE. virtual uint32_t GetAttributeValue(const brillo::SecureBlob& isolate, uint64_t session_id, uint64_t object_handle, const std::vector<uint8_t>& attributes_in, std::vector<uint8_t>* attributes_out) { std::string label = handles_[object_handle]; std::string value = values_[label]; chaps::Attributes parsed; parsed.Parse(attributes_in); if (parsed.num_attributes() == 1 && parsed.attributes()[0].type == CKA_LABEL) value = label; if (parsed.num_attributes() != 1 || (parsed.attributes()[0].type != CKA_VALUE && parsed.attributes()[0].type != CKA_LABEL) || (parsed.attributes()[0].pValue && parsed.attributes()[0].ulValueLen != value.size())) return CKR_GENERAL_ERROR; parsed.attributes()[0].ulValueLen = value.size(); if (parsed.attributes()[0].pValue) memcpy(parsed.attributes()[0].pValue, value.data(), value.size()); parsed.Serialize(attributes_out); return CKR_OK; } // Supports writing CKA_VALUE. virtual uint32_t SetAttributeValue(const brillo::SecureBlob& isolate, uint64_t session_id, uint64_t object_handle, const std::vector<uint8_t>& attributes) { values_[handles_[object_handle]] = GetValue(attributes, CKA_VALUE); return CKR_OK; } // Finds stored objects by CKA_LABEL or CKA_VALUE. If no CKA_LABEL or // CKA_VALUE, find all objects. virtual uint32_t FindObjectsInit(const brillo::SecureBlob& isolate, uint64_t session_id, const std::vector<uint8_t>& attributes) { std::string label = GetValue(attributes, CKA_LABEL); std::string value = GetValue(attributes, CKA_VALUE); found_objects_.clear(); if (label.empty() && value.empty()) { // Find all objects. found_objects_ = brillo::GetMapKeysAsVector(handles_); } else if (!label.empty() && labels_.count(label) > 0) { // Find only the object with |label|. found_objects_.push_back(labels_[label]); } else { // Find all objects with |value|. for (const auto& item : values_) { if (item.second == value && labels_.count(item.first) > 0) { found_objects_.push_back(labels_[item.first]); } } } return CKR_OK; } // Reports a 'found' object based on find_status_. virtual uint32_t FindObjects(const brillo::SecureBlob& isolate, uint64_t session_id, uint64_t max_object_count, std::vector<uint64_t>* object_list) { while (!found_objects_.empty() && object_list->size() < max_object_count) { object_list->push_back(found_objects_.back()); found_objects_.pop_back(); } return CKR_OK; } protected: NiceMock<Pkcs11Mock> pkcs11_; NiceMock<chaps::TokenManagerClientMock> token_manager_; private: // A helper to pull the value for a given attribute out of a serialized // template. std::string GetValue(const std::vector<uint8_t>& attributes, CK_ATTRIBUTE_TYPE type) { chaps::Attributes parsed; parsed.Parse(attributes); CK_ATTRIBUTE_PTR array = parsed.attributes(); for (CK_ULONG i = 0; i < parsed.num_attributes(); ++i) { if (array[i].type == type) { if (!array[i].pValue) return ""; return std::string(reinterpret_cast<char*>(array[i].pValue), array[i].ulValueLen); } } return ""; } std::map<std::string, std::string> values_; // The fake store: label->value std::map<uint64_t, std::string> handles_; // The fake store: handle->label std::map<std::string, uint64_t> labels_; // The fake store: label->handle std::vector<uint64_t> found_objects_; // The most recent search results uint64_t next_handle_; // Tracks handle assignment ScopedFakeSalt fake_system_salt_; // We want to avoid all the Chaps verbose logging. ScopedDisableVerboseLogging no_verbose_logging; DISALLOW_COPY_AND_ASSIGN(KeyStoreTest); }; // This test assumes that chaps in not available on the system running the test. // The purpose of this test is to exercise the C_Initialize failure code path. // Without a mock, the Chaps library will attempt to connect to the Chaps daemon // unsuccessfully, resulting in a C_Initialize failure. TEST(KeyStoreTest_NoMock, Pkcs11NotAvailable) { chaps::TokenManagerClient token_manager; Pkcs11KeyStore key_store(&token_manager); std::string blob; EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); EXPECT_FALSE(key_store.Write(kDefaultUser, "test", blob)); EXPECT_FALSE(key_store.Read("", "test", &blob)); EXPECT_FALSE(key_store.Write("", "test", blob)); } // Exercises the key store when PKCS #11 returns success. This exercises all // non-error-handling code paths. TEST_F(KeyStoreTest, Pkcs11Success) { Pkcs11KeyStore key_store(&token_manager_); std::string blob; EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); EXPECT_TRUE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_TRUE(key_store.Read(kDefaultUser, "test", &blob)); EXPECT_EQ("test_data", blob); // Try with a different key name. EXPECT_FALSE(key_store.Read(kDefaultUser, "test2", &blob)); EXPECT_TRUE(key_store.Write(kDefaultUser, "test2", "test_data2")); EXPECT_TRUE(key_store.Read(kDefaultUser, "test2", &blob)); EXPECT_EQ("test_data2", blob); // Read the original key again. EXPECT_TRUE(key_store.Read(kDefaultUser, "test", &blob)); EXPECT_EQ("test_data", blob); // Replace key data. EXPECT_TRUE(key_store.Write(kDefaultUser, "test", "test_data3")); EXPECT_TRUE(key_store.Read(kDefaultUser, "test", &blob)); EXPECT_EQ("test_data3", blob); // Delete key data. EXPECT_TRUE(key_store.Delete(kDefaultUser, "test2")); EXPECT_FALSE(key_store.Read(kDefaultUser, "test2", &blob)); EXPECT_TRUE(key_store.Read(kDefaultUser, "test", &blob)); } TEST_F(KeyStoreTest, Pkcs11Success_NoUser) { Pkcs11KeyStore key_store(&token_manager_); std::string blob; EXPECT_FALSE(key_store.Read("", "test", &blob)); EXPECT_TRUE(key_store.Write("", "test", "test_data")); EXPECT_TRUE(key_store.Read("", "test", &blob)); EXPECT_EQ("test_data", blob); // Try with a different key name. EXPECT_FALSE(key_store.Read("", "test2", &blob)); EXPECT_TRUE(key_store.Write("", "test2", "test_data2")); EXPECT_TRUE(key_store.Read("", "test2", &blob)); EXPECT_EQ("test_data2", blob); // Read the original key again. EXPECT_TRUE(key_store.Read("", "test", &blob)); EXPECT_EQ("test_data", blob); // Replace key data. EXPECT_TRUE(key_store.Write("", "test", "test_data3")); EXPECT_TRUE(key_store.Read("", "test", &blob)); EXPECT_EQ("test_data3", blob); // Delete key data. EXPECT_TRUE(key_store.Delete("", "test2")); EXPECT_FALSE(key_store.Read("", "test2", &blob)); EXPECT_TRUE(key_store.Read("", "test", &blob)); } // Tests the key store when PKCS #11 has no token for the given user. TEST_F(KeyStoreTest, TokenNotAvailable) { EXPECT_CALL(token_manager_, GetTokenPath(_, _, _)) .WillRepeatedly(Return(false)); Pkcs11KeyStore key_store(&token_manager_); std::string blob; EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); EXPECT_FALSE(key_store.Write(kDefaultUser, "test", blob)); EXPECT_FALSE(key_store.Read("", "test", &blob)); EXPECT_FALSE(key_store.Write("", "test", blob)); } // Tests the key store when PKCS #11 fails to open a session. TEST_F(KeyStoreTest, NoSession) { EXPECT_CALL(pkcs11_, OpenSession(_, _, _, _)) .WillRepeatedly(Return(CKR_GENERAL_ERROR)); Pkcs11KeyStore key_store(&token_manager_); std::string blob; EXPECT_FALSE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); } // Tests the key store when PKCS #11 fails to create an object. TEST_F(KeyStoreTest, CreateObjectFail) { EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .WillRepeatedly(Return(CKR_GENERAL_ERROR)); Pkcs11KeyStore key_store(&token_manager_); std::string blob; EXPECT_FALSE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); } // Tests the key store when PKCS #11 fails to read attribute values. TEST_F(KeyStoreTest, ReadValueFail) { EXPECT_CALL(pkcs11_, GetAttributeValue(_, _, _, _, _)) .WillRepeatedly(Return(CKR_GENERAL_ERROR)); Pkcs11KeyStore key_store(&token_manager_); std::string blob; EXPECT_TRUE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); } // Tests the key store when PKCS #11 fails to delete key data. TEST_F(KeyStoreTest, DeleteValueFail) { EXPECT_CALL(pkcs11_, DestroyObject(_, _, _)) .WillRepeatedly(Return(CKR_GENERAL_ERROR)); Pkcs11KeyStore key_store(&token_manager_); EXPECT_TRUE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_FALSE(key_store.Write(kDefaultUser, "test", "test_data2")); EXPECT_FALSE(key_store.Delete(kDefaultUser, "test")); } // Tests the key store when PKCS #11 fails to find objects. Tests each part of // the multi-part find operation individually. TEST_F(KeyStoreTest, FindFail) { EXPECT_CALL(pkcs11_, FindObjectsInit(_, _, _)) .WillRepeatedly(Return(CKR_GENERAL_ERROR)); Pkcs11KeyStore key_store(&token_manager_); std::string blob; EXPECT_TRUE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); EXPECT_CALL(pkcs11_, FindObjectsInit(_, _, _)).WillRepeatedly(Return(CKR_OK)); EXPECT_CALL(pkcs11_, FindObjects(_, _, _, _)) .WillRepeatedly(Return(CKR_GENERAL_ERROR)); EXPECT_TRUE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); EXPECT_CALL(pkcs11_, FindObjects(_, _, _, _)).WillRepeatedly(Return(CKR_OK)); EXPECT_CALL(pkcs11_, FindObjectsFinal(_, _)) .WillRepeatedly(Return(CKR_GENERAL_ERROR)); EXPECT_TRUE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); } // Tests the key store when PKCS #11 successfully finds zero objects. TEST_F(KeyStoreTest, FindNoObjects) { std::vector<uint64_t> empty; EXPECT_CALL(pkcs11_, FindObjects(_, _, _, _)) .WillRepeatedly(DoAll(SetArgPointee<3>(empty), Return(CKR_OK))); Pkcs11KeyStore key_store(&token_manager_); std::string blob; EXPECT_TRUE(key_store.Write(kDefaultUser, "test", "test_data")); EXPECT_FALSE(key_store.Read(kDefaultUser, "test", &blob)); } TEST_F(KeyStoreTest, RegisterKeyWithoutCertificate) { Pkcs11KeyStore key_store(&token_manager_); // Try with a malformed public key. EXPECT_FALSE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_RSA, KEY_USAGE_SIGN, "private_key_blob", "bad_pubkey", "")); // Try with a well-formed public key. std::string public_key_der = HexDecode(kValidRsaPublicKeyHex); EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .Times(2) // Public, private (no certificate). .WillRepeatedly(Return(CKR_OK)); EXPECT_TRUE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_RSA, KEY_USAGE_SIGN, "private_key_blob", public_key_der, "")); } TEST_F(KeyStoreTest, RegisterKeyWithCertificate) { EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .Times(3) // Public, private, and certificate. .WillRepeatedly(Return(CKR_OK)); Pkcs11KeyStore key_store(&token_manager_); std::string public_key_der = HexDecode(kValidRsaPublicKeyHex); std::string certificate_der = HexDecode(kValidRsaCertificateHex); EXPECT_TRUE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_RSA, KEY_USAGE_SIGN, "private_key_blob", public_key_der, certificate_der)); // Also try with the system token. EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .Times(3) // Public, private, and certificate. .WillRepeatedly(Return(CKR_OK)); EXPECT_TRUE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_RSA, KEY_USAGE_SIGN, "private_key_blob", public_key_der, certificate_der)); } TEST_F(KeyStoreTest, RegisterEccKeyWithoutCertificate) { Pkcs11KeyStore key_store(&token_manager_); // Try with a malformed public key. EXPECT_FALSE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_ECC, KEY_USAGE_SIGN, "private_key_blob", "bad_pubkey", "")); // Try with a well-formed public key. std::string public_key_der = HexDecode(kValidEccPublicKeyHex); EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .Times(2) // Public, private (no certificate). .WillRepeatedly(Return(CKR_OK)); EXPECT_TRUE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_ECC, KEY_USAGE_SIGN, "private_key_blob", public_key_der, "")); } TEST_F(KeyStoreTest, RegisterEccKeyWithCertificate) { EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .Times(3) // Public, private, and certificate. .WillRepeatedly(Return(CKR_OK)); Pkcs11KeyStore key_store(&token_manager_); std::string public_key_der = HexDecode(kValidEccPublicKeyHex); std::string certificate_der = HexDecode(kValidEccCertificateHex); EXPECT_TRUE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_ECC, KEY_USAGE_SIGN, "private_key_blob", public_key_der, certificate_der)); // Also try with the system token. EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .Times(3) // Public, private, and certificate. .WillRepeatedly(Return(CKR_OK)); EXPECT_TRUE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_ECC, KEY_USAGE_SIGN, "private_key_blob", public_key_der, certificate_der)); } TEST_F(KeyStoreTest, RegisterKeyWithBadCertificate) { EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .Times(3) // Public, private, and certificate. .WillRepeatedly(Return(CKR_OK)); Pkcs11KeyStore key_store(&token_manager_); std::string public_key_der = HexDecode(kValidRsaPublicKeyHex); EXPECT_TRUE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_RSA, KEY_USAGE_SIGN, "private_key_blob", public_key_der, "bad_certificate")); } TEST_F(KeyStoreTest, RegisterWithWrongKeyType) { Pkcs11KeyStore key_store(&token_manager_); std::string public_key_der = HexDecode(kValidRsaPublicKeyHex); EXPECT_FALSE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_ECC, KEY_USAGE_SIGN, "private_key_blob", public_key_der, "")); } TEST_F(KeyStoreTest, RegisterDecryptionKey) { EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)).WillRepeatedly(Return(CKR_OK)); Pkcs11KeyStore key_store(&token_manager_); std::string public_key_der = HexDecode(kValidRsaPublicKeyHex); EXPECT_TRUE(key_store.Register(kDefaultUser, "test_label", KEY_TYPE_RSA, KEY_USAGE_DECRYPT, "private_key_blob", public_key_der, "")); } TEST_F(KeyStoreTest, RegisterCertificate) { Pkcs11KeyStore key_store(&token_manager_); std::string certificate_der = HexDecode(kValidRsaCertificateHex); EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .Times(2); // Once for valid, once for invalid. // Try with a valid certificate (hit multiple times to check dup logic). EXPECT_TRUE(key_store.RegisterCertificate(kDefaultUser, certificate_der)); EXPECT_TRUE(key_store.RegisterCertificate(kDefaultUser, certificate_der)); EXPECT_TRUE(key_store.RegisterCertificate(kDefaultUser, certificate_der)); // Try with an invalid certificate. EXPECT_TRUE(key_store.RegisterCertificate(kDefaultUser, "bad_certificate")); } TEST_F(KeyStoreTest, RegisterCertificateError) { Pkcs11KeyStore key_store(&token_manager_); std::string certificate_der = HexDecode(kValidRsaCertificateHex); // Handle an error from PKCS #11. EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)) .WillOnce(Return(CKR_GENERAL_ERROR)); EXPECT_FALSE(key_store.RegisterCertificate(kDefaultUser, certificate_der)); } TEST_F(KeyStoreTest, RegisterCertificateSystemToken) { Pkcs11KeyStore key_store(&token_manager_); std::string certificate_der = HexDecode(kValidRsaCertificateHex); // Try with the system token. EXPECT_CALL(pkcs11_, CreateObject(_, _, _, _)).WillOnce(Return(CKR_OK)); EXPECT_TRUE(key_store.RegisterCertificate(kDefaultUser, certificate_der)); } // Tests that the DeleteByPrefix() method removes the correct objects and only // the correct objects. TEST_F(KeyStoreTest, DeleteByPrefix) { Pkcs11KeyStore key_store(&token_manager_); // Test with no keys. ASSERT_TRUE(key_store.DeleteByPrefix(kDefaultUser, "prefix")); // Test with a single matching key. ASSERT_TRUE(key_store.Write(kDefaultUser, "prefix_test", "test")); ASSERT_TRUE(key_store.DeleteByPrefix(kDefaultUser, "prefix")); std::string blob; EXPECT_FALSE(key_store.Read(kDefaultUser, "prefix_test", &blob)); // Test with a single non-matching key. ASSERT_TRUE(key_store.Write(kDefaultUser, "_prefix_", "test")); ASSERT_TRUE(key_store.DeleteByPrefix(kDefaultUser, "prefix")); EXPECT_TRUE(key_store.Read(kDefaultUser, "_prefix_", &blob)); // Test with an empty prefix. ASSERT_TRUE(key_store.DeleteByPrefix(kDefaultUser, "")); EXPECT_FALSE(key_store.Read(kDefaultUser, "_prefix_", &blob)); // Test with multiple matching and non-matching keys. const int kNumKeys = 110; // Pkcs11KeyStore max is 100 for FindObjects. key_store.Write(kDefaultUser, "other1", "test"); for (int i = 0; i < kNumKeys; ++i) { std::string key_name = std::string("prefix") + base::NumberToString(i); key_store.Write(kDefaultUser, key_name, std::string(key_name)); } ASSERT_TRUE(key_store.Write(kDefaultUser, "other2", "test")); ASSERT_TRUE(key_store.DeleteByPrefix(kDefaultUser, "prefix")); EXPECT_TRUE(key_store.Read(kDefaultUser, "other1", &blob)); EXPECT_TRUE(key_store.Read(kDefaultUser, "other2", &blob)); for (int i = 0; i < kNumKeys; ++i) { std::string key_name = std::string("prefix") + base::NumberToString(i); EXPECT_FALSE(key_store.Read(kDefaultUser, key_name, &blob)); } } } // namespace attestation
45.05919
80
0.723106
kalyankondapally
a3f58ec8fd42d988fae022d5766d218c5ed405b7
6,695
cpp
C++
sources/GeoElementSide.cpp
Kauehenrik/FemCourseEigenClass2021
d4927d92b541fdd2b2aa1fa424a413dd561ae96e
[ "MIT" ]
1
2021-06-12T13:21:51.000Z
2021-06-12T13:21:51.000Z
sources/GeoElementSide.cpp
Kauehenrik/FemCourseEigenClass2021
d4927d92b541fdd2b2aa1fa424a413dd561ae96e
[ "MIT" ]
null
null
null
sources/GeoElementSide.cpp
Kauehenrik/FemCourseEigenClass2021
d4927d92b541fdd2b2aa1fa424a413dd561ae96e
[ "MIT" ]
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ #include "GeoMesh.h" #include "GeoElementSide.h" ///\cond #include <stdio.h> #include <algorithm> ///\endcond GeoElementSide::GeoElementSide() { } GeoElementSide::GeoElementSide(const GeoElementSide& copy) { fElement = copy.fElement; fSide = copy.fSide; } GeoElementSide& GeoElementSide::operator=(const GeoElementSide& copy) { fElement = copy.fElement; fSide = copy.fSide; return *this; } GeoElementSide GeoElementSide::Neighbour() const { return fElement ? fElement->Neighbour(fSide) : GeoElementSide(); } void GeoElementSide::SetNeighbour(const GeoElementSide& neighbour) { fElement->SetNeighbour(fSide, neighbour); } bool GeoElementSide::IsNeighbour(const GeoElementSide& candidate) const { if (candidate == *this) return true; GeoElementSide neighbour = Neighbour(); if (!(neighbour.Element() != 0 && neighbour.Side() > -1)) return false; while ((neighbour == *this) == false) { if (candidate == neighbour) return true; neighbour = neighbour.Neighbour(); } return false; } void GeoElementSide::IsertConnectivity(GeoElementSide& candidate) { if (this->IsNeighbour(candidate)) return; GeoElementSide neigh1 = Neighbour(); GeoElementSide neigh2 = candidate.Neighbour(); SetNeighbour(neigh2); candidate.SetNeighbour(neigh1); } void GeoElementSide::AllNeighbours(std::vector<GeoElementSide>& allneigh) const { if (fElement->NSideNodes(fSide) != 1) DebugStop(); GeoElementSide neigh = Neighbour(); int nodeindex = fElement->SideNodeIndex(fSide, 0); while (neigh != *this) { int neighnode = neigh.fElement->SideNodeIndex(neigh.fSide, 0); if (neighnode != nodeindex) DebugStop(); allneigh.push_back(neigh); neigh = neigh.Neighbour(); } } void GeoElementSide::ComputeNeighbours(std::vector<GeoElementSide>& compneigh) { if (fSide < fElement->NCornerNodes()) { AllNeighbours(compneigh); return; } int nsnodes = fElement->NSideNodes(fSide); std::vector<GeoElementSide> GeoElSideSet; std::vector<std::vector<int> > GeoElSet; GeoElSet.resize(nsnodes); int in; VecInt nodeindexes(nsnodes); for (in = 0; in < nsnodes; in++) { int nodeindex = fElement->SideNodeIndex(fSide, in); nodeindexes[in] = nodeindex; } // compute the neighbours along the cornernodes for (in = 0; in < nsnodes; in++) { int locindex = fElement->SideNodeLocIndex(fSide, in); int nodeindex = fElement->SideNodeIndex(fSide, in); GeoElSideSet.resize(0); GeoElementSide locside(fElement, locindex); int nodeindex_again = locside.Element()->SideNodeIndex(locside.Side(), 0); if (nodeindex != nodeindex_again) DebugStop(); locside.AllNeighbours(GeoElSideSet); for (auto& gelside : GeoElSideSet) { int node = gelside.Element()->SideNodeIndex(gelside.Side(), 0); if (node != nodeindex) DebugStop(); } int nel = GeoElSideSet.size(); int el; for (el = 0; el < nel; el++) { GeoElSet[in].push_back(GeoElSideSet[el].Element()->GetIndex()); } std::sort(GeoElSet[in].begin(), GeoElSet[in].end()); } std::vector<int> result; std::vector<int> result_aux; // build the neighbours along the higher dimension sides switch (nsnodes) { case 1: { result = GeoElSet[0]; } break; case 2: std::set_intersection(GeoElSet[0].begin(), GeoElSet[0].end(), GeoElSet[1].begin(), GeoElSet[1].end(), std::back_inserter(result)); break; case 3: std::set_intersection(GeoElSet[0].begin(), GeoElSet[0].end(), GeoElSet[1].begin(), GeoElSet[1].end(), std::back_inserter(result_aux)); std::set_intersection(result_aux.begin(), result_aux.end(), GeoElSet[2].begin(), GeoElSet[2].end(), std::back_inserter(result)); break; case 4: { std::vector<int> inter1, inter2; std::set_intersection(GeoElSet[0].begin(), GeoElSet[0].end(), GeoElSet[2].begin(), GeoElSet[2].end(), std::back_inserter(inter1)); if (inter1.size() == 0) break; std::set_intersection(GeoElSet[1].begin(), GeoElSet[1].end(), GeoElSet[3].begin(), GeoElSet[3].end(), std::back_inserter(inter2)); if (inter2.size() == 0) break; std::set_intersection(inter1.begin(), inter1.end(), inter2.begin(), inter2.end(), std::back_inserter(result)); inter1.clear(); inter2.clear(); } break; default: { std::vector<int> inter1, inter2; inter1 = GeoElSet[0]; for (in = 0; in < nsnodes - 1; in++) { std::set_intersection(inter1.begin(), inter1.end(), GeoElSet[in + 1].begin(), GeoElSet[in + 1].end(), std::back_inserter(inter2)); if (inter2.size() == 0) break; inter1 = inter2; } inter1.clear(); inter2.clear(); result = inter2; } } int el, nel = result.size(); GeoMesh* geoMesh = fElement->GetMesh(); for (el = 0; el < nel; el++) { GeoElement* gelResult = geoMesh->Element(result[el]); int whichSd = gelResult->WhichSide(nodeindexes); if (whichSd < 0) { std::cout << "nodeindexes " << nodeindexes << std::endl; std::cout << "neighbouring element index " << gelResult->GetIndex() << std::endl; std::cout << "neighbouring element nodes "; for (int i = 0; i < gelResult->NNodes(); i++) std::cout << gelResult->NodeIndex(i) << " "; std::cout << std::endl; for (int i = 0; i < nsnodes; i++) { auto gelset = GeoElSet[i]; std::cout << "GeoElSet along node " << i << " is "; for (auto g : gelset) std::cout << g << " "; std::cout << std::endl; } DebugStop(); } GeoElementSide gelside(gelResult, whichSd); if (gelside == *this) continue; if (whichSd > 0) { compneigh.push_back(GeoElementSide(gelResult, whichSd)); } } GeoElSideSet.clear(); GeoElSet.clear(); nodeindexes.resize(0); result.clear(); result_aux.clear(); } // Print the element index and side void GeoElementSide::Print(std::ostream& out) const { if (!fElement) { out << "GeoElSide empty\n"; } else { out << "elid " << fElement->GetIndex() << " side " << fSide << std::endl; } }
33.143564
142
0.603137
Kauehenrik
a3f6d573fd5fdd67b3e7d104be986e35b6aa7e24
913
inl
C++
Phoenix3D/PX2Unity/PX2CURLDownload.inl
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
36
2016-04-24T01:40:38.000Z
2022-01-18T07:32:26.000Z
Phoenix3D/PX2Unity/PX2CURLDownload.inl
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
null
null
null
Phoenix3D/PX2Unity/PX2CURLDownload.inl
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
16
2016-06-13T08:43:51.000Z
2020-09-15T13:25:58.000Z
// PX2CURLDownload.inl //---------------------------------------------------------------------------- inline CURLDownload::DownType CURLDownload::GetDownType () const { return mDownType; } //---------------------------------------------------------------------------- inline char *CURLDownload::GetDownloadMemory () { return mDownloadMemory; } //---------------------------------------------------------------------------- inline const char *CURLDownload::GetDownloadMemory () const { return mDownloadMemory; } //---------------------------------------------------------------------------- inline bool CURLDownload::IsDownLoadOK () const { return mIsDownLoadOK; } //---------------------------------------------------------------------------- inline float CURLDownload::GetDownLoadProgress () const { return mDownLoadProgress; } //----------------------------------------------------------------------------
32.607143
78
0.377875
PheonixFoundation
a3f810040acbae6197e1dd8a583055526da0625a
9,241
cc
C++
NS3-master/src/mpi/examples/simple-distributed.cc
legendPerceptor/blockchain
615ba331ae5ec53c683dfe6a16992a5181be0fea
[ "Apache-2.0" ]
1
2021-09-20T07:05:25.000Z
2021-09-20T07:05:25.000Z
NS3-master/src/mpi/examples/simple-distributed.cc
legendPerceptor/blockchain
615ba331ae5ec53c683dfe6a16992a5181be0fea
[ "Apache-2.0" ]
null
null
null
NS3-master/src/mpi/examples/simple-distributed.cc
legendPerceptor/blockchain
615ba331ae5ec53c683dfe6a16992a5181be0fea
[ "Apache-2.0" ]
2
2021-09-02T08:25:16.000Z
2022-01-03T08:48:38.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * TestDistributed creates a dumbbell topology and logically splits it in * half. The left half is placed on logical processor 0 and the right half * is placed on logical processor 1. * * ------- ------- * RANK 0 RANK 1 * ------- | ------- * | * n0 ---------| | |---------- n6 * | | | * n1 -------\ | | | /------- n7 * n4 ----------|---------- n5 * n2 -------/ | | | \------- n8 * | | | * n3 ---------| | |---------- n9 * * * OnOff clients are placed on each left leaf node. Each right leaf node * is a packet sink for a left leaf node. As a packet travels from one * logical processor to another (the link between n4 and n5), MPI messages * are passed containing the serialized packet. The message is then * deserialized into a new packet and sent on as normal. * * One packet is sent from each left leaf node. The packet sinks on the * right leaf nodes output logging information when they receive the packet. */ #include "ns3/core-module.h" #include "ns3/network-module.h" #include "ns3/mpi-interface.h" #include "ns3/ipv4-global-routing-helper.h" #include "ns3/point-to-point-helper.h" #include "ns3/internet-stack-helper.h" #include "ns3/ipv4-nix-vector-helper.h" #include "ns3/ipv4-address-helper.h" #include "ns3/on-off-helper.h" #include "ns3/packet-sink-helper.h" #ifdef NS3_MPI #include <mpi.h> #endif using namespace ns3; NS_LOG_COMPONENT_DEFINE ("SimpleDistributed"); int main (int argc, char *argv[]) { #ifdef NS3_MPI bool nix = true; bool nullmsg = false; bool tracing = false; // Parse command line CommandLine cmd; cmd.AddValue ("nix", "Enable the use of nix-vector or global routing", nix); cmd.AddValue ("nullmsg", "Enable the use of null-message synchronization", nullmsg); cmd.AddValue ("tracing", "Enable pcap tracing", tracing); cmd.Parse (argc, argv); // Distributed simulation setup; by default use granted time window algorithm. if(nullmsg) { GlobalValue::Bind ("SimulatorImplementationType", StringValue ("ns3::NullMessageSimulatorImpl")); } else { GlobalValue::Bind ("SimulatorImplementationType", StringValue ("ns3::DistributedSimulatorImpl")); } // Enable parallel simulator with the command line arguments MpiInterface::Enable (&argc, &argv); LogComponentEnable ("PacketSink", LOG_LEVEL_INFO); uint32_t systemId = MpiInterface::GetSystemId (); uint32_t systemCount = MpiInterface::GetSize (); // Check for valid distributed parameters. // Must have 2 and only 2 Logical Processors (LPs) if (systemCount != 2) { std::cout << "This simulation requires 2 and only 2 logical processors." << std::endl; return 1; } // Some default values Config::SetDefault ("ns3::OnOffApplication::PacketSize", UintegerValue (512)); Config::SetDefault ("ns3::OnOffApplication::DataRate", StringValue ("1Mbps")); Config::SetDefault ("ns3::OnOffApplication::MaxBytes", UintegerValue (512)); // Create leaf nodes on left with system id 0 NodeContainer leftLeafNodes; leftLeafNodes.Create (4, 0); // Create router nodes. Left router // with system id 0, right router with // system id 1 NodeContainer routerNodes; Ptr<Node> routerNode1 = CreateObject<Node> (0); Ptr<Node> routerNode2 = CreateObject<Node> (1); routerNodes.Add (routerNode1); routerNodes.Add (routerNode2); // Create leaf nodes on right with system id 1 NodeContainer rightLeafNodes; rightLeafNodes.Create (4, 1); PointToPointHelper routerLink; routerLink.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); routerLink.SetChannelAttribute ("Delay", StringValue ("5ms")); PointToPointHelper leafLink; leafLink.SetDeviceAttribute ("DataRate", StringValue ("1Mbps")); leafLink.SetChannelAttribute ("Delay", StringValue ("2ms")); // Add link connecting routers NetDeviceContainer routerDevices; routerDevices = routerLink.Install (routerNodes); // Add links for left side leaf nodes to left router NetDeviceContainer leftRouterDevices; NetDeviceContainer leftLeafDevices; for (uint32_t i = 0; i < 4; ++i) { NetDeviceContainer temp = leafLink.Install (leftLeafNodes.Get (i), routerNodes.Get (0)); leftLeafDevices.Add (temp.Get (0)); leftRouterDevices.Add (temp.Get (1)); } // Add links for right side leaf nodes to right router NetDeviceContainer rightRouterDevices; NetDeviceContainer rightLeafDevices; for (uint32_t i = 0; i < 4; ++i) { NetDeviceContainer temp = leafLink.Install (rightLeafNodes.Get (i), routerNodes.Get (1)); rightLeafDevices.Add (temp.Get (0)); rightRouterDevices.Add (temp.Get (1)); } InternetStackHelper stack; if (nix) { Ipv4NixVectorHelper nixRouting; stack.SetRoutingHelper (nixRouting); // has effect on the next Install () } stack.InstallAll (); Ipv4InterfaceContainer routerInterfaces; Ipv4InterfaceContainer leftLeafInterfaces; Ipv4InterfaceContainer leftRouterInterfaces; Ipv4InterfaceContainer rightLeafInterfaces; Ipv4InterfaceContainer rightRouterInterfaces; Ipv4AddressHelper leftAddress; leftAddress.SetBase ("10.1.1.0", "255.255.255.0"); Ipv4AddressHelper routerAddress; routerAddress.SetBase ("10.2.1.0", "255.255.255.0"); Ipv4AddressHelper rightAddress; rightAddress.SetBase ("10.3.1.0", "255.255.255.0"); // Router-to-Router interfaces routerInterfaces = routerAddress.Assign (routerDevices); // Left interfaces for (uint32_t i = 0; i < 4; ++i) { NetDeviceContainer ndc; ndc.Add (leftLeafDevices.Get (i)); ndc.Add (leftRouterDevices.Get (i)); Ipv4InterfaceContainer ifc = leftAddress.Assign (ndc); leftLeafInterfaces.Add (ifc.Get (0)); leftRouterInterfaces.Add (ifc.Get (1)); leftAddress.NewNetwork (); } // Right interfaces for (uint32_t i = 0; i < 4; ++i) { NetDeviceContainer ndc; ndc.Add (rightLeafDevices.Get (i)); ndc.Add (rightRouterDevices.Get (i)); Ipv4InterfaceContainer ifc = rightAddress.Assign (ndc); rightLeafInterfaces.Add (ifc.Get (0)); rightRouterInterfaces.Add (ifc.Get (1)); rightAddress.NewNetwork (); } if (!nix) { Ipv4GlobalRoutingHelper::PopulateRoutingTables (); } if (tracing == true) { if (systemId == 0) { routerLink.EnablePcap("router-left", routerDevices, true); leafLink.EnablePcap("leaf-left", leftLeafDevices, true); } if (systemId == 1) { routerLink.EnablePcap("router-right", routerDevices, true); leafLink.EnablePcap("leaf-right", rightLeafDevices, true); } } // Create a packet sink on the right leafs to receive packets from left leafs uint16_t port = 50000; if (systemId == 1) { Address sinkLocalAddress (InetSocketAddress (Ipv4Address::GetAny (), port)); PacketSinkHelper sinkHelper ("ns3::UdpSocketFactory", sinkLocalAddress); ApplicationContainer sinkApp; for (uint32_t i = 0; i < 4; ++i) { sinkApp.Add (sinkHelper.Install (rightLeafNodes.Get (i))); } sinkApp.Start (Seconds (1.0)); sinkApp.Stop (Seconds (5)); } // Create the OnOff applications to send if (systemId == 0) { OnOffHelper clientHelper ("ns3::UdpSocketFactory", Address ()); clientHelper.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]")); clientHelper.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]")); ApplicationContainer clientApps; for (uint32_t i = 0; i < 4; ++i) { AddressValue remoteAddress (InetSocketAddress (rightLeafInterfaces.GetAddress (i), port)); clientHelper.SetAttribute ("Remote", remoteAddress); clientApps.Add (clientHelper.Install (leftLeafNodes.Get (i))); } clientApps.Start (Seconds (1.0)); clientApps.Stop (Seconds (5)); } Simulator::Stop (Seconds (5)); Simulator::Run (); Simulator::Destroy (); // Exit the MPI execution environment MpiInterface::Disable (); return 0; #else NS_FATAL_ERROR ("Can't use distributed simulator without MPI compiled in"); #endif }
33.241007
95
0.65599
legendPerceptor
a3fbf0da6c0c5b585e941c3a3e00afb8a971fa22
2,534
cpp
C++
pwiz_tools/examples/hello_ramp.cpp
austinkeller/pwiz
aa8e575cb40fd5e97cc7d922e4d8da44c9277cca
[ "Apache-2.0" ]
null
null
null
pwiz_tools/examples/hello_ramp.cpp
austinkeller/pwiz
aa8e575cb40fd5e97cc7d922e4d8da44c9277cca
[ "Apache-2.0" ]
null
null
null
pwiz_tools/examples/hello_ramp.cpp
austinkeller/pwiz
aa8e575cb40fd5e97cc7d922e4d8da44c9277cca
[ "Apache-2.0" ]
null
null
null
// // $Id$ // // // Original author: Darren Kessner <darren@proteowizard.org> // // Copyright 2007 Spielberg Family Center for Applied Proteomics // Cedars-Sinai Medical Center, Los Angeles, California 90048 // // 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 "pwiz/data/msdata/RAMPAdapter.hpp" #include "pwiz/utility/misc/Std.hpp" using namespace pwiz::msdata; void test(const char* filename) { RAMPAdapter adapter(filename); InstrumentStruct instrument; adapter.getInstrument(instrument); cout << "manufacturer: " << instrument.manufacturer << endl; cout << "model: " << instrument.model << endl; cout << "ionisation: " << instrument.ionisation << endl; cout << "analyzer : " << instrument.analyzer << endl; cout << "detector: " << instrument.detector << endl; size_t scanCount = adapter.scanCount(); cout << "scanCount: " << scanCount << "\n\n"; for (size_t i=0; i<scanCount; i++) { ScanHeaderStruct header; adapter.getScanHeader(i, header); cout << "index: " << i << endl; cout << "seqNum: " << header.seqNum << endl; cout << "acquisitionNum: " << header.acquisitionNum << endl; cout << "msLevel: " << header.msLevel << endl; cout << "peaksCount: " << header.peaksCount << endl; cout << "precursorScanNum: " << header.precursorScanNum << endl; cout << "filePosition: " << header.filePosition << endl; vector<double> peaks; adapter.getScanPeaks(i, peaks); for (unsigned int j=0; j<min(peaks.size(),(size_t)20); j+=2) cout << " (" << peaks[j] << ", " << peaks[j+1] << ")\n"; cout << endl; } } int main(int argc, char* argv[]) { try { if (argc<2) throw runtime_error("Usage: hello_ramp filename"); test(argv[1]); return 0; } catch (exception& e) { cerr << e.what() << endl; } catch (...) { cerr << "Caught unknown exception.\n"; } return 1; }
28.47191
76
0.614049
austinkeller
4300268d0f5301e77ea9c96dfab712a5cc04d5c6
3,084
cpp
C++
msv_main/src/msv_main_node.cpp
daconjurer/ros_msv
dbf70083588b869172ac74f187b81166e78c8da1
[ "BSD-3-Clause" ]
2
2021-07-13T22:02:43.000Z
2022-03-10T15:46:58.000Z
msv_main/src/msv_main_node.cpp
daconjurer/ros_msv
dbf70083588b869172ac74f187b81166e78c8da1
[ "BSD-3-Clause" ]
null
null
null
msv_main/src/msv_main_node.cpp
daconjurer/ros_msv
dbf70083588b869172ac74f187b81166e78c8da1
[ "BSD-3-Clause" ]
null
null
null
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2019, Robótica de la Mixteca * 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 Universidad Tecnológica de la Mixteca nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ ///////////////////////////////////////////////////////////////////////////////////////// /// @file ROS msv_main node of the MSV-01 rescue robot for general control using the ROS /// Joy messages. The node publishes the teleoperation commands, as well as the control /// commands for the robotic arm and an orientation system for the RGBD sensor. /// @author Victor Esteban Sandoval-Luna /// /// Based on the "rescue" ROS metapackage from José Armando Sánchez-Rojas. /// Based on the Modbus protocol "lightmodbus" library (RTU) from Jacek Wieczorek, /// please see https://github.com/Jacajack/liblightmodbus. ///////////////////////////////////////////////////////////////////////////////////////// #include <msv_main/msv_main.h> #include <boost/asio.hpp> int main (int argc, char **argv) { //Initialize ROS ros::init(argc, argv, "msv_main"); try { //Create an object of class MsvMain that will do the job MsvMain *robot; MsvMain msv01; robot = &msv01; ros::Rate loop_rate(10); while (ros::ok()) { // Node callbacks handling ros::spinOnce(); loop_rate.sleep(); } return 0; } catch (boost::system::system_error ex) { ROS_ERROR("Error instantiating msv_main object. Error: %s", ex.what()); return -1; } }
40.578947
89
0.652724
daconjurer
4300b783305b277b46054bd480c590ebb58db0e2
5,015
hpp
C++
include/System/Net/NetworkCredential.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Net/NetworkCredential.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Net/NetworkCredential.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Net.ICredentials #include "System/Net/ICredentials.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Security namespace System::Security { // Forward declaring type: SecureString class SecureString; } // Forward declaring namespace: System namespace System { // Forward declaring type: Uri class Uri; } // Completed forward declares // Type namespace: System.Net namespace System::Net { // Size: 0x28 #pragma pack(push, 1) // Autogenerated type: System.Net.NetworkCredential class NetworkCredential : public ::Il2CppObject/*, public System::Net::ICredentials*/ { public: // private System.String m_domain // Size: 0x8 // Offset: 0x10 ::Il2CppString* m_domain; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // private System.String m_userName // Size: 0x8 // Offset: 0x18 ::Il2CppString* m_userName; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // private System.Security.SecureString m_password // Size: 0x8 // Offset: 0x20 System::Security::SecureString* m_password; // Field size check static_assert(sizeof(System::Security::SecureString*) == 0x8); // Creating value type constructor for type: NetworkCredential NetworkCredential(::Il2CppString* m_domain_ = {}, ::Il2CppString* m_userName_ = {}, System::Security::SecureString* m_password_ = {}) noexcept : m_domain{m_domain_}, m_userName{m_userName_}, m_password{m_password_} {} // Creating interface conversion operator: operator System::Net::ICredentials operator System::Net::ICredentials() noexcept { return *reinterpret_cast<System::Net::ICredentials*>(this); } // public System.Void .ctor(System.String userName, System.String password) // Offset: 0x164634C template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static NetworkCredential* New_ctor(::Il2CppString* userName, ::Il2CppString* password) { static auto ___internal__logger = ::Logger::get().WithContext("System::Net::NetworkCredential::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<NetworkCredential*, creationType>(userName, password))); } // public System.Void .ctor(System.String userName, System.String password, System.String domain) // Offset: 0x16463BC template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static NetworkCredential* New_ctor(::Il2CppString* userName, ::Il2CppString* password, ::Il2CppString* domain) { static auto ___internal__logger = ::Logger::get().WithContext("System::Net::NetworkCredential::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<NetworkCredential*, creationType>(userName, password, domain))); } // public System.String get_UserName() // Offset: 0x16465A8 ::Il2CppString* get_UserName(); // public System.Void set_UserName(System.String value) // Offset: 0x164649C void set_UserName(::Il2CppString* value); // public System.String get_Password() // Offset: 0x16465B0 ::Il2CppString* get_Password(); // public System.Void set_Password(System.String value) // Offset: 0x164650C void set_Password(::Il2CppString* value); // public System.String get_Domain() // Offset: 0x16465C8 ::Il2CppString* get_Domain(); // public System.Void set_Domain(System.String value) // Offset: 0x1646538 void set_Domain(::Il2CppString* value); // System.String InternalGetUserName() // Offset: 0x16465D0 ::Il2CppString* InternalGetUserName(); // System.String InternalGetPassword() // Offset: 0x16465BC ::Il2CppString* InternalGetPassword(); // System.String InternalGetDomain() // Offset: 0x16465D8 ::Il2CppString* InternalGetDomain(); // public System.Net.NetworkCredential GetCredential(System.Uri uri, System.String authType) // Offset: 0x16465E0 System::Net::NetworkCredential* GetCredential(System::Uri* uri, ::Il2CppString* authType); }; // System.Net.NetworkCredential #pragma pack(pop) static check_size<sizeof(NetworkCredential), 32 + sizeof(System::Security::SecureString*)> __System_Net_NetworkCredentialSizeCheck; static_assert(sizeof(NetworkCredential) == 0x28); } DEFINE_IL2CPP_ARG_TYPE(System::Net::NetworkCredential*, "System.Net", "NetworkCredential");
46.869159
222
0.700698
darknight1050
43011d27af9ae51634ace497ca9a058f29265695
329
hh
C++
DMSASD/live5552vlc/live555/UsageEnvironment/include/UsageEnvironment_version.hh
kancheng/kan-cs-report-in-2022
2a1e1eaa515349d59803c7831a7bd4cbea890a44
[ "MIT" ]
null
null
null
DMSASD/live5552vlc/live555/UsageEnvironment/include/UsageEnvironment_version.hh
kancheng/kan-cs-report-in-2022
2a1e1eaa515349d59803c7831a7bd4cbea890a44
[ "MIT" ]
null
null
null
DMSASD/live5552vlc/live555/UsageEnvironment/include/UsageEnvironment_version.hh
kancheng/kan-cs-report-in-2022
2a1e1eaa515349d59803c7831a7bd4cbea890a44
[ "MIT" ]
null
null
null
// Version information for the "UsageEnvironment" library // Copyright (c) 1996-2016 Live Networks, Inc. All rights reserved. #ifndef _USAGEENVIRONMENT_VERSION_HH #define _USAGEENVIRONMENT_VERSION_HH #define USAGEENVIRONMENT_LIBRARY_VERSION_STRING "2016.10.11" #define USAGEENVIRONMENT_LIBRARY_VERSION_INT 1476144000 #endif
29.909091
68
0.835866
kancheng
430245be8e7100d866ddb34000ed7c0890073a00
396
cpp
C++
bracket.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
null
null
null
bracket.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
null
null
null
bracket.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
1
2019-01-19T01:05:07.000Z
2019-01-19T01:05:07.000Z
/* #include <iostream> #include <cstdlib> #include <cmath> #include <algorithm> #include <stack> #include <string> #include <cstring> using namespace std; stack<int> st; int main(){ string s; cin>>s; //cout<<"F@ck you"; for(int i=0;i<s.length();i++){ if(s[i]=='(') st.push(i); if(s[i]==')') st.pop(); if(s[i]=='*') cout<<st.size(); } return 0; } */
18
38
0.527778
W-YXN
430397d271dd238409778828ff1bf6fc5a793d68
4,759
cpp
C++
Runtime/MP1/CSamusFaceReflection.cpp
Jcw87/urde
fb9ea9092ad00facfe957ece282a86c194e9cbda
[ "MIT" ]
267
2016-03-10T21:59:16.000Z
2021-03-28T18:21:03.000Z
Runtime/MP1/CSamusFaceReflection.cpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
129
2016-03-12T10:17:32.000Z
2021-04-05T20:45:19.000Z
Runtime/MP1/CSamusFaceReflection.cpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
31
2016-03-20T00:20:11.000Z
2021-03-10T21:14:11.000Z
#include "Runtime/MP1/CSamusFaceReflection.hpp" #include "Runtime/CStateManager.hpp" #include "Runtime/GameGlobalObjects.hpp" #include "Runtime/Camera/CFirstPersonCamera.hpp" #include "Runtime/World/CPlayer.hpp" #include "Runtime/World/CWorld.hpp" #include "TCastTo.hpp" // Generated file, do not modify include path namespace metaforce::MP1 { static const zeus::CTransform PreXf = zeus::CTransform::Scale(0.3f) * zeus::CTransform::Translate(0.f, 0.5f, 0.f); CSamusFaceReflection::CSamusFaceReflection(CStateManager& stateMgr) : x0_modelData(CAnimRes(g_ResFactory->GetResourceIdByName("ACS_SamusFace")->id, 0, zeus::skOne3f, 0, true)) , x4c_lights(std::make_unique<CActorLights>(8, zeus::skZero3f, 4, 4, false, false, false, 0.1f)) { x60_lookDir = zeus::skForward; constexpr CAnimPlaybackParms parms(0, -1, 1.f, true); x0_modelData.GetAnimationData()->SetAnimation(parms, false); } void CSamusFaceReflection::PreDraw(const CStateManager& mgr) { if (x6c_ != 2 && (x4c_lights->GetActiveLightCount() >= 1 || (x6c_ != 0 && x6c_ != 3))) { if (!TCastToConstPtr<CFirstPersonCamera>(mgr.GetCameraManager()->GetCurrentCamera(mgr))) { x70_hidden = true; } else { x70_hidden = false; x0_modelData.GetAnimationData()->PreRender(); } } } void CSamusFaceReflection::Draw(const CStateManager& mgr) { if (x70_hidden) return; if (TCastToConstPtr<CFirstPersonCamera> fpCam = (mgr.GetCameraManager()->GetCurrentCamera(mgr))) { SCOPED_GRAPHICS_DEBUG_GROUP("CSamusFaceReflection::Draw", zeus::skBlue); zeus::CQuaternion camRot(fpCam->GetTransform().basis); float dist = ITweakGui::FaceReflectionDistanceDebugValueToActualValue(g_tweakGui->GetFaceReflectionDistance()); float height = ITweakGui::FaceReflectionHeightDebugValueToActualValue(g_tweakGui->GetFaceReflectionHeight()); float aspect = ITweakGui::FaceReflectionAspectDebugValueToActualValue(g_tweakGui->GetFaceReflectionAspect()); float orthoWidth = ITweakGui::FaceReflectionOrthoWidthDebugValueToActualValue(g_tweakGui->GetFaceReflectionOrthoWidth()); float orthoHeight = ITweakGui::FaceReflectionOrthoHeightDebugValueToActualValue(g_tweakGui->GetFaceReflectionOrthoHeight()); zeus::CTransform modelXf = zeus::CTransform(camRot * x50_lookRot, fpCam->GetTransform().basis[1] * dist + fpCam->GetTransform().origin + fpCam->GetTransform().basis[2] * height) * PreXf; CGraphics::SetViewPointMatrix(fpCam->GetTransform()); CGraphics::SetOrtho(aspect * -orthoWidth, aspect * orthoWidth, orthoHeight, -orthoHeight, -10.f, 10.f); CActorLights* lights = x6c_ == 1 ? nullptr : x4c_lights.get(); if (x6c_ == 3) { x0_modelData.Render(mgr, modelXf, lights, CModelFlags(0, 0, 3, zeus::skWhite)); } else { float transFactor; if (mgr.GetPlayerState()->GetActiveVisor(mgr) == CPlayerState::EPlayerVisor::Combat) transFactor = mgr.GetPlayerState()->GetVisorTransitionFactor(); else transFactor = 0.f; if (transFactor > 0.f) { x0_modelData.Render(mgr, modelXf, nullptr, CModelFlags(7, 0, 3, zeus::skBlack)); x0_modelData.Render(mgr, modelXf, lights, CModelFlags(7, 0, 1, zeus::CColor(1.f, transFactor))); } } } } void CSamusFaceReflection::Update(float dt, const CStateManager& mgr, CRandom16& rand) { if (TCastToConstPtr<CFirstPersonCamera> fpCam = (mgr.GetCameraManager()->GetCurrentCamera(mgr))) { x0_modelData.AdvanceAnimationIgnoreParticles(dt, rand, true); x4c_lights->SetFindShadowLight(false); TAreaId areaId = mgr.GetPlayer().GetAreaIdAlways(); if (areaId == kInvalidAreaId) return; zeus::CAABox aabb(fpCam->GetTranslation() - 0.125f, fpCam->GetTranslation() + 0.125f); const CGameArea* area = mgr.GetWorld()->GetAreaAlways(areaId); x4c_lights->BuildFaceLightList(mgr, *area, aabb); zeus::CUnitVector3f lookDir(fpCam->GetTransform().basis[1]); zeus::CUnitVector3f xfLook = zeus::CQuaternion::lookAt(lookDir, zeus::skForward, 2.f * M_PIF).transform(x60_lookDir); zeus::CQuaternion xfLook2 = zeus::CQuaternion::lookAt(zeus::skForward, xfLook, 2.f * M_PIF); xfLook2 *= xfLook2; zeus::CMatrix3f newXf(xfLook2); zeus::CMatrix3f prevXf(x50_lookRot); float lookDot = prevXf[1].dot(newXf[1]); if (std::fabs(lookDot) > 1.f) lookDot = lookDot > 0.f ? 1.f : -1.f; float lookAng = std::acos(lookDot); x50_lookRot = zeus::CQuaternion::slerp( x50_lookRot, xfLook2, zeus::clamp(0.f, 18.f * dt * ((lookAng > 0.f) ? 0.5f * dt * g_tweakPlayer->GetFreeLookSpeed() / lookAng : 0.f), 1.f)); x60_lookDir = lookDir; } } } // namespace metaforce::MP1
44.896226
119
0.699517
Jcw87
4304992ce677ed0a51c999f03119555651941668
5,160
cpp
C++
AIPDebug/Out-Moc/moc_pic.cpp
Bluce-Song/Master-AIP
1757ab392504d839de89460da17630d268ff3eed
[ "Apache-2.0" ]
null
null
null
AIPDebug/Out-Moc/moc_pic.cpp
Bluce-Song/Master-AIP
1757ab392504d839de89460da17630d268ff3eed
[ "Apache-2.0" ]
null
null
null
AIPDebug/Out-Moc/moc_pic.cpp
Bluce-Song/Master-AIP
1757ab392504d839de89460da17630d268ff3eed
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** Meta object code from reading C++ file 'pic.h' ** ** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.5) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../External-Interface/pic.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'pic.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.5. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_pic[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 10, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 3, // signalCount // signals: signature, parameters, type, tag, flags 12, 5, 4, 4, 0x05, 38, 35, 4, 4, 0x05, 74, 35, 4, 4, 0x05, // slots: signature, parameters, type, tag, flags 110, 35, 4, 4, 0x0a, 146, 35, 4, 4, 0x0a, 184, 4, 4, 4, 0x08, 201, 4, 4, 4, 0x08, 220, 4, 4, 4, 0x08, 239, 4, 4, 4, 0x08, 260, 4, 4, 4, 0x08, 0 // eod }; static const char qt_meta_stringdata_pic[] = { "pic\0\0frame,\0canSend(can_frame,int)\0" ",,\0Signal_pic_to_Test(QString,int,int)\0" "Signal_pic_to_Main(QString,int,int)\0" "Pubs_from_main(QStringList,int,int)\0" "Pubs_from_Switchover(int,int32_t,int)\0" "Timer_Order_Go()\0L_Cylinder_Up_Go()\0" "R_Cylinder_Up_Go()\0Cylinder_Real_Back()\0" "IO_Join_Reset()\0" }; void pic::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Q_ASSERT(staticMetaObject.cast(_o)); pic *_t = static_cast<pic *>(_o); switch (_id) { case 0: _t->canSend((*reinterpret_cast< can_frame(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 1: _t->Signal_pic_to_Test((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break; case 2: _t->Signal_pic_to_Main((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break; case 3: _t->Pubs_from_main((*reinterpret_cast< QStringList(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break; case 4: _t->Pubs_from_Switchover((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int32_t(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break; case 5: _t->Timer_Order_Go(); break; case 6: _t->L_Cylinder_Up_Go(); break; case 7: _t->R_Cylinder_Up_Go(); break; case 8: _t->Cylinder_Real_Back(); break; case 9: _t->IO_Join_Reset(); break; default: ; } } } const QMetaObjectExtraData pic::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject pic::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_pic, qt_meta_data_pic, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &pic::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *pic::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *pic::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_pic)) return static_cast<void*>(const_cast< pic*>(this)); return QObject::qt_metacast(_clname); } int pic::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 10) qt_static_metacall(this, _c, _id, _a); _id -= 10; } return _id; } // SIGNAL 0 void pic::canSend(can_frame _t1, int _t2) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void pic::Signal_pic_to_Test(QString _t1, int _t2, int _t3) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } // SIGNAL 2 void pic::Signal_pic_to_Main(QString _t1, int _t2, int _t3) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)) }; QMetaObject::activate(this, &staticMetaObject, 2, _a); } QT_END_MOC_NAMESPACE
36.595745
191
0.609496
Bluce-Song
430643a9b2aaca52dc58d619aad3b73e7f160d38
1,423
cpp
C++
Source/SumoUE4Editor/Private/Factories/SumoNetworkAssetFactory.cpp
iwer/SumoUE4
8f2e5281a0b94e46cff97e1e2b535eca0f021dd6
[ "MIT" ]
4
2021-08-31T09:40:18.000Z
2022-02-07T02:48:25.000Z
Source/SumoUE4Editor/Private/Factories/SumoNetworkAssetFactory.cpp
iwer/SumoUE4
8f2e5281a0b94e46cff97e1e2b535eca0f021dd6
[ "MIT" ]
null
null
null
Source/SumoUE4Editor/Private/Factories/SumoNetworkAssetFactory.cpp
iwer/SumoUE4
8f2e5281a0b94e46cff97e1e2b535eca0f021dd6
[ "MIT" ]
2
2021-07-18T02:29:21.000Z
2022-02-07T02:48:28.000Z
// Copyright (c) Iwer Petersen. All rights reserved. #include "SumoNetworkAssetFactory.h" #include "SumoNetworkAsset.h" #include "SumoNetworkParser.h" USumoNetworkAssetFactory::USumoNetworkAssetFactory( const FObjectInitializer& ObjectInitializer ) : Super(ObjectInitializer) { SupportedClass = USumoNetworkAsset::StaticClass(); bCreateNew = false; bEditorImport = true; Formats.Add(TEXT("xml;Sumo network definition file")); } UObject * USumoNetworkAssetFactory::FactoryCreateFile(UClass* InClass, UObject* InParent, FName InName, EObjectFlags Flags, const FString& Filename, const TCHAR* Parms, FFeedbackContext* Warn, bool& bOutOperationCanceled) { USumoNetworkAsset* Asset = NewObject<USumoNetworkAsset>(InParent, InClass, InName, Flags); // populate Asset USumoNetworkParser parser; parser.ParseFile(Filename, Asset); return Asset; } bool USumoNetworkAssetFactory::FactoryCanImport(const FString & Filename) { if(!Filename.EndsWith(TEXT(".net.xml"))){ return false; } return true; }
34.707317
97
0.556571
iwer
430739accc1c4d49b2f5740770d83ca719f25717
15,341
cpp
C++
Developments/solidity-develop/libsolidity/interface/StandardCompiler.cpp
jansenbarabona/NFT-Game-Development
49bf6593925123f0212dac13badd609be3866561
[ "MIT" ]
null
null
null
Developments/solidity-develop/libsolidity/interface/StandardCompiler.cpp
jansenbarabona/NFT-Game-Development
49bf6593925123f0212dac13badd609be3866561
[ "MIT" ]
null
null
null
Developments/solidity-develop/libsolidity/interface/StandardCompiler.cpp
jansenbarabona/NFT-Game-Development
49bf6593925123f0212dac13badd609be3866561
[ "MIT" ]
null
null
null
/* This file is part of solidity. solidity is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. solidity is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Alex Beregszaszi * @date 2016 * Standard JSON compiler interface. */ #include <libsolidity/interface/StandardCompiler.h> #include <libsolidity/interface/SourceReferenceFormatter.h> #include <libsolidity/ast/ASTJsonConverter.h> #include <libevmasm/Instruction.h> #include <libdevcore/JSON.h> #include <libdevcore/SHA3.h> using namespace std; using namespace dev; using namespace dev::solidity; namespace { Json::Value formatError( bool _warning, string const& _type, string const& _component, string const& _message, string const& _formattedMessage = "", Json::Value const& _sourceLocation = Json::Value() ) { Json::Value error = Json::objectValue; error["type"] = _type; error["component"] = _component; error["severity"] = _warning ? "warning" : "error"; error["message"] = _message; error["formattedMessage"] = (_formattedMessage.length() > 0) ? _formattedMessage : _message; if (_sourceLocation.isObject()) error["sourceLocation"] = _sourceLocation; return error; } Json::Value formatFatalError(string const& _type, string const& _message) { Json::Value output = Json::objectValue; output["errors"] = Json::arrayValue; output["errors"].append(formatError(false, _type, "general", _message)); return output; } Json::Value formatErrorWithException( Exception const& _exception, bool const& _warning, string const& _type, string const& _component, string const& _message, function<Scanner const&(string const&)> const& _scannerFromSourceName ) { string message; string formattedMessage = SourceReferenceFormatter::formatExceptionInformation(_exception, _type, _scannerFromSourceName); // NOTE: the below is partially a copy from SourceReferenceFormatter SourceLocation const* location = boost::get_error_info<errinfo_sourceLocation>(_exception); if (string const* description = boost::get_error_info<errinfo_comment>(_exception)) message = ((_message.length() > 0) ? (_message + ":") : "") + *description; else message = _message; if (location && location->sourceName) { Json::Value sourceLocation = Json::objectValue; sourceLocation["file"] = *location->sourceName; sourceLocation["start"] = location->start; sourceLocation["end"] = location->end; } return formatError(_warning, _type, _component, message, formattedMessage, location); } set<string> requestedContractNames(Json::Value const& _outputSelection) { set<string> names; for (auto const& sourceName: _outputSelection.getMemberNames()) { for (auto const& contractName: _outputSelection[sourceName].getMemberNames()) { /// Consider the "all sources" shortcuts as requesting everything. if (contractName == "*" || contractName == "") return set<string>(); names.insert((sourceName == "*" ? "" : sourceName) + ":" + contractName); } } return names; } /// Returns true iff @a _hash (hex with 0x prefix) is the Keccak256 hash of the binary data in @a _content. bool hashMatchesContent(string const& _hash, string const& _content) { try { return dev::h256(_hash) == dev::keccak256(_content); } catch (dev::BadHexCharacter) { return false; } } StringMap createSourceList(Json::Value const& _input) { StringMap sources; Json::Value const& jsonSources = _input["sources"]; if (jsonSources.isObject()) for (auto const& sourceName: jsonSources.getMemberNames()) sources[sourceName] = jsonSources[sourceName]["content"].asString(); return sources; } Json::Value formatLinkReferences(std::map<size_t, std::string> const& linkReferences) { Json::Value ret(Json::objectValue); for (auto const& ref: linkReferences) { string const& fullname = ref.second; size_t colon = fullname.find(':'); solAssert(colon != string::npos, ""); string file = fullname.substr(0, colon); string name = fullname.substr(colon + 1); Json::Value fileObject = ret.get(file, Json::objectValue); Json::Value libraryArray = fileObject.get(name, Json::arrayValue); Json::Value entry = Json::objectValue; entry["start"] = Json::UInt(ref.first); entry["length"] = 20; libraryArray.append(entry); fileObject[name] = libraryArray; ret[file] = fileObject; } return ret; } Json::Value collectEVMObject(eth::LinkerObject const& _object, string const* _sourceMap) { Json::Value output = Json::objectValue; output["object"] = _object.toHex(); output["opcodes"] = solidity::disassemble(_object.bytecode); output["sourceMap"] = _sourceMap ? *_sourceMap : ""; output["linkReferences"] = formatLinkReferences(_object.linkReferences); return output; } } Json::Value StandardCompiler::compileInternal(Json::Value const& _input) { m_compilerStack.reset(false); if (!_input.isObject()) return formatFatalError("JSONError", "Input is not a JSON object."); if (_input["language"] != "Solidity") return formatFatalError("JSONError", "Only \"Solidity\" is supported as a language."); Json::Value const& sources = _input["sources"]; if (!sources) return formatFatalError("JSONError", "No input sources specified."); Json::Value errors = Json::arrayValue; for (auto const& sourceName: sources.getMemberNames()) { string hash; if (!sources[sourceName].isObject()) return formatFatalError("JSONError", "Source input is not a JSON object."); if (sources[sourceName]["keccak256"].isString()) hash = sources[sourceName]["keccak256"].asString(); if (sources[sourceName]["content"].isString()) { string content = sources[sourceName]["content"].asString(); if (!hash.empty() && !hashMatchesContent(hash, content)) errors.append(formatError( false, "IOError", "general", "Mismatch between content and supplied hash for \"" + sourceName + "\"" )); else m_compilerStack.addSource(sourceName, content); } else if (sources[sourceName]["urls"].isArray()) { if (!m_readFile) return formatFatalError("JSONError", "No import callback supplied, but URL is requested."); bool found = false; vector<string> failures; for (auto const& url: sources[sourceName]["urls"]) { ReadCallback::Result result = m_readFile(url.asString()); if (result.success) { if (!hash.empty() && !hashMatchesContent(hash, result.responseOrErrorMessage)) errors.append(formatError( false, "IOError", "general", "Mismatch between content and supplied hash for \"" + sourceName + "\" at \"" + url.asString() + "\"" )); else { m_compilerStack.addSource(sourceName, result.responseOrErrorMessage); found = true; break; } } else failures.push_back("Cannot import url (\"" + url.asString() + "\"): " + result.responseOrErrorMessage); } for (auto const& failure: failures) { /// If the import succeeded, let mark all the others as warnings, otherwise all of them are errors. errors.append(formatError( found ? true : false, "IOError", "general", failure )); } } else return formatFatalError("JSONError", "Invalid input source specified."); } Json::Value const& settings = _input.get("settings", Json::Value()); vector<string> remappings; for (auto const& remapping: settings.get("remappings", Json::Value())) remappings.push_back(remapping.asString()); m_compilerStack.setRemappings(remappings); Json::Value optimizerSettings = settings.get("optimizer", Json::Value()); bool const optimize = optimizerSettings.get("enabled", Json::Value(false)).asBool(); unsigned const optimizeRuns = optimizerSettings.get("runs", Json::Value(200u)).asUInt(); m_compilerStack.setOptimiserSettings(optimize, optimizeRuns); map<string, h160> libraries; Json::Value jsonLibraries = settings.get("libraries", Json::Value()); for (auto const& sourceName: jsonLibraries.getMemberNames()) { auto const& jsonSourceName = jsonLibraries[sourceName]; for (auto const& library: jsonSourceName.getMemberNames()) // @TODO use libraries only for the given source libraries[library] = h160(jsonSourceName[library].asString()); } m_compilerStack.setLibraries(libraries); Json::Value metadataSettings = settings.get("metadata", Json::Value()); m_compilerStack.useMetadataLiteralSources(metadataSettings.get("useLiteralContent", Json::Value(false)).asBool()); Json::Value outputSelection = settings.get("outputSelection", Json::Value()); m_compilerStack.setRequestedContractNames(requestedContractNames(outputSelection)); auto scannerFromSourceName = [&](string const& _sourceName) -> solidity::Scanner const& { return m_compilerStack.scanner(_sourceName); }; try { m_compilerStack.compile(); for (auto const& error: m_compilerStack.errors()) { Error const& err = dynamic_cast<Error const&>(*error); errors.append(formatErrorWithException( *error, err.type() == Error::Type::Warning, err.typeName(), "general", "", scannerFromSourceName )); } } /// This is only thrown in a very few locations. catch (Error const& _error) { errors.append(formatErrorWithException( _error, false, _error.typeName(), "general", "Uncaught error: ", scannerFromSourceName )); } /// This should not be leaked from compile(). catch (FatalError const& _exception) { errors.append(formatError( false, "FatalError", "general", "Uncaught fatal error: " + boost::diagnostic_information(_exception) )); } catch (CompilerError const& _exception) { errors.append(formatErrorWithException( _exception, false, "CompilerError", "general", "Compiler error (" + _exception.lineInfo() + ")", scannerFromSourceName )); } catch (InternalCompilerError const& _exception) { errors.append(formatErrorWithException( _exception, false, "InternalCompilerError", "general", "Internal compiler error (" + _exception.lineInfo() + ")", scannerFromSourceName )); } catch (UnimplementedFeatureError const& _exception) { errors.append(formatErrorWithException( _exception, false, "UnimplementedFeatureError", "general", "Unimplemented feature (" + _exception.lineInfo() + ")", scannerFromSourceName )); } catch (Exception const& _exception) { errors.append(formatError( false, "Exception", "general", "Exception during compilation: " + boost::diagnostic_information(_exception) )); } catch (...) { errors.append(formatError( false, "Exception", "general", "Unknown exception during compilation." )); } bool const analysisSuccess = m_compilerStack.state() >= CompilerStack::State::AnalysisSuccessful; bool const compilationSuccess = m_compilerStack.state() == CompilerStack::State::CompilationSuccessful; /// Inconsistent state - stop here to receive error reports from users if (!compilationSuccess && (errors.size() == 0)) return formatFatalError("InternalCompilerError", "No error reported, but compilation failed."); Json::Value output = Json::objectValue; if (errors.size() > 0) output["errors"] = errors; output["sources"] = Json::objectValue; unsigned sourceIndex = 0; for (string const& sourceName: analysisSuccess ? m_compilerStack.sourceNames() : vector<string>()) { Json::Value sourceResult = Json::objectValue; sourceResult["id"] = sourceIndex++; sourceResult["ast"] = ASTJsonConverter(false, m_compilerStack.sourceIndices()).toJson(m_compilerStack.ast(sourceName)); sourceResult["legacyAST"] = ASTJsonConverter(true, m_compilerStack.sourceIndices()).toJson(m_compilerStack.ast(sourceName)); output["sources"][sourceName] = sourceResult; } Json::Value contractsOutput = Json::objectValue; for (string const& contractName: compilationSuccess ? m_compilerStack.contractNames() : vector<string>()) { size_t colon = contractName.find(':'); solAssert(colon != string::npos, ""); string file = contractName.substr(0, colon); string name = contractName.substr(colon + 1); // ABI, documentation and metadata Json::Value contractData(Json::objectValue); contractData["abi"] = m_compilerStack.contractABI(contractName); contractData["metadata"] = m_compilerStack.metadata(contractName); contractData["userdoc"] = m_compilerStack.natspecUser(contractName); contractData["devdoc"] = m_compilerStack.natspecDev(contractName); // EVM Json::Value evmData(Json::objectValue); // @TODO: add ir evmData["assembly"] = m_compilerStack.assemblyString(contractName, createSourceList(_input)); evmData["legacyAssembly"] = m_compilerStack.assemblyJSON(contractName, createSourceList(_input)); evmData["methodIdentifiers"] = m_compilerStack.methodIdentifiers(contractName); evmData["gasEstimates"] = m_compilerStack.gasEstimates(contractName); evmData["bytecode"] = collectEVMObject( m_compilerStack.object(contractName), m_compilerStack.sourceMapping(contractName) ); evmData["deployedBytecode"] = collectEVMObject( m_compilerStack.runtimeObject(contractName), m_compilerStack.runtimeSourceMapping(contractName) ); contractData["evm"] = evmData; if (!contractsOutput.isMember(file)) contractsOutput[file] = Json::objectValue; contractsOutput[file][name] = contractData; } output["contracts"] = contractsOutput; return output; } Json::Value StandardCompiler::compile(Json::Value const& _input) { try { return compileInternal(_input); } catch (Json::LogicError const& _exception) { return formatFatalError("InternalCompilerError", string("JSON logic exception: ") + _exception.what()); } catch (Json::RuntimeError const& _exception) { return formatFatalError("InternalCompilerError", string("JSON runtime exception: ") + _exception.what()); } catch (Exception const& _exception) { return formatFatalError("InternalCompilerError", "Internal exception in StandardCompiler::compileInternal: " + boost::diagnostic_information(_exception)); } catch (...) { return formatFatalError("InternalCompilerError", "Internal exception in StandardCompiler::compileInternal"); } } string StandardCompiler::compile(string const& _input) { Json::Value input; Json::Reader reader; try { if (!reader.parse(_input, input, false)) return jsonCompactPrint(formatFatalError("JSONError", reader.getFormattedErrorMessages())); } catch(...) { return "{\"errors\":\"[{\"type\":\"JSONError\",\"component\":\"general\",\"severity\":\"error\",\"message\":\"Error parsing input JSON.\"}]}"; } // cout << "Input: " << input.toStyledString() << endl; Json::Value output = compile(input); // cout << "Output: " << output.toStyledString() << endl; try { return jsonCompactPrint(output); } catch(...) { return "{\"errors\":\"[{\"type\":\"JSONError\",\"component\":\"general\",\"severity\":\"error\",\"message\":\"Error writing output JSON.\"}]}"; } }
30.620758
156
0.715338
jansenbarabona
4307d5b1c4b676300bda191a618d72ef2f24814d
4,888
hpp
C++
include/amtrs/.inc/g3d-shader/vulkan.textureshader.frag.hpp
isaponsoft/libamtrs
5adf821ee15592fc3280985658ca8a4b175ffcaa
[ "BSD-2-Clause-FreeBSD" ]
1
2019-12-10T02:12:49.000Z
2019-12-10T02:12:49.000Z
include/amtrs/.inc/g3d-shader/vulkan.textureshader.frag.hpp
isaponsoft/libamtrs
5adf821ee15592fc3280985658ca8a4b175ffcaa
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
include/amtrs/.inc/g3d-shader/vulkan.textureshader.frag.hpp
isaponsoft/libamtrs
5adf821ee15592fc3280985658ca8a4b175ffcaa
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. * * Use of this source code is governed by a BSD-style license that * * can be found in the LICENSE file. */ unsigned char vulkan_textureshader_frag_spv[] = { 0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x0a, 0x00, 0x08, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x2e, 0x34, 0x35, 0x30, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x08, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x10, 0x00, 0x03, 0x00, 0x04, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00, 0x90, 0x01, 0x00, 0x00, 0x04, 0x00, 0x09, 0x00, 0x47, 0x4c, 0x5f, 0x41, 0x52, 0x42, 0x5f, 0x73, 0x65, 0x70, 0x61, 0x72, 0x61, 0x74, 0x65, 0x5f, 0x73, 0x68, 0x61, 0x64, 0x65, 0x72, 0x5f, 0x6f, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x73, 0x00, 0x00, 0x04, 0x00, 0x09, 0x00, 0x47, 0x4c, 0x5f, 0x41, 0x52, 0x42, 0x5f, 0x73, 0x68, 0x61, 0x64, 0x69, 0x6e, 0x67, 0x5f, 0x6c, 0x61, 0x6e, 0x67, 0x75, 0x61, 0x67, 0x65, 0x5f, 0x34, 0x32, 0x30, 0x70, 0x61, 0x63, 0x6b, 0x00, 0x05, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x09, 0x00, 0x00, 0x00, 0x6f, 0x75, 0x74, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x66, 0x72, 0x61, 0x67, 0x43, 0x6f, 0x6c, 0x6f, 0x72, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00, 0x10, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x72, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x14, 0x00, 0x00, 0x00, 0x66, 0x72, 0x61, 0x67, 0x55, 0x76, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x10, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x10, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x14, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x13, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x21, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x16, 0x00, 0x03, 0x00, 0x06, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x19, 0x00, 0x09, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x03, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x12, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x13, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x13, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x12, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x57, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x85, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, 0x09, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00 }; unsigned int vulkan_textureshader_frag_spv_len = 740;
70.84058
73
0.649959
isaponsoft