hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
232b0190be58f244992d15180c209b8a9c6e6382 | 5,891 | cc | C++ | google/cloud/iam_bindings_test.cc | orinem/google-cloud-cpp | c43f73e9abeb2b9d8a6e99f7d9750cba37f2f6b1 | [
"Apache-2.0"
] | 3 | 2020-05-27T23:21:23.000Z | 2020-05-31T22:31:53.000Z | google/cloud/iam_bindings_test.cc | orinem/google-cloud-cpp | c43f73e9abeb2b9d8a6e99f7d9750cba37f2f6b1 | [
"Apache-2.0"
] | 2 | 2020-05-31T22:26:57.000Z | 2020-06-19T00:14:10.000Z | google/cloud/iam_bindings_test.cc | orinem/google-cloud-cpp | c43f73e9abeb2b9d8a6e99f7d9750cba37f2f6b1 | [
"Apache-2.0"
] | 1 | 2021-12-09T16:26:23.000Z | 2021-12-09T16:26:23.000Z | // Copyright 2018 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
//
// 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 "google/cloud/iam_bindings.h"
#include <gmock/gmock.h>
namespace google {
namespace cloud {
inline namespace GOOGLE_CLOUD_CPP_NS {
namespace {
TEST(IamBindingsTest, DefaultConstructor) {
std::string role = "writer";
std::set<std::string> members = {"abc@gmail.com", "xyz@gmail.com"};
auto iam_binding = IamBinding(role, members);
std::vector<IamBinding> bindings_vector = {iam_binding};
auto iam_bindings = IamBindings(bindings_vector);
EXPECT_EQ(1, iam_bindings.bindings().size());
EXPECT_EQ("writer", iam_bindings.bindings().begin()->first);
EXPECT_EQ(2, iam_bindings.bindings().begin()->second.size());
}
TEST(IamBindingsTest, AddMemberTestRoleExists) {
std::string role = "writer";
std::set<std::string> members = {"abc@gmail.com", "xyz@gmail.com"};
auto iam_binding = IamBinding(role, members);
std::vector<IamBinding> bindings_vector = {iam_binding};
auto iam_bindings = IamBindings(bindings_vector);
iam_bindings.AddMember(role, "jkl@gmail.com");
EXPECT_EQ(3, iam_bindings.bindings().begin()->second.size());
}
TEST(IamBindingsTest, AddMemberTestNewRole) {
std::string role = "writer";
std::set<std::string> members = {"abc@gmail.com", "xyz@gmail.com"};
auto iam_binding = IamBinding(role, members);
std::vector<IamBinding> bindings_vector = {iam_binding};
auto iam_bindings = IamBindings(bindings_vector);
std::string new_role = "reader";
iam_bindings.AddMember(new_role, "jkl@gmail.com");
EXPECT_EQ(2, iam_bindings.bindings().size());
}
TEST(IamBindingsTest, AddMembersTestRoleExists) {
std::string role = "writer";
std::set<std::string> members = {"abc@gmail.com", "xyz@gmail.com"};
auto iam_binding = IamBinding(role, members);
std::vector<IamBinding> bindings_vector = {iam_binding};
auto iam_bindings = IamBindings(bindings_vector);
std::set<std::string> new_members = {"jkl@gmail.com", "pqr@gmail.com"};
iam_bindings.AddMembers(role, new_members);
EXPECT_EQ(4, iam_bindings.bindings().begin()->second.size());
}
TEST(IamBindingsTest, AddMembersTestIamBindingParma) {
std::string role = "writer";
std::set<std::string> members = {"abc@gmail.com", "xyz@gmail.com"};
auto iam_binding = IamBinding(role, members);
std::vector<IamBinding> bindings_vector = {iam_binding};
auto iam_bindings = IamBindings(bindings_vector);
std::set<std::string> new_members = {"jkl@gmail.com", "pqr@gmail.com"};
auto iam_binding_for_addition = IamBinding(role, new_members);
iam_bindings.AddMembers(iam_binding_for_addition);
EXPECT_EQ(4, iam_bindings.bindings().begin()->second.size());
}
TEST(IamBindingsTest, AddMembersTestNewRole) {
std::string role = "writer";
std::set<std::string> members = {"abc@gmail.com", "xyz@gmail.com"};
auto iam_binding = IamBinding(role, members);
std::vector<IamBinding> bindings_vector = {iam_binding};
auto iam_bindings = IamBindings(bindings_vector);
std::string new_role = "reader";
std::set<std::string> new_members = {"jkl@gmail.com", "pqr@gmail.com"};
iam_bindings.AddMembers(new_role, new_members);
EXPECT_EQ(2, iam_bindings.bindings().size());
}
TEST(IamBindingsTest, RemoveMemberTest) {
std::string role = "writer";
std::set<std::string> members = {"abc@gmail.com", "xyz@gmail.com"};
auto iam_binding = IamBinding(role, members);
std::vector<IamBinding> bindings_vector = {iam_binding};
auto iam_bindings = IamBindings(bindings_vector);
iam_bindings.RemoveMember(role, "abc@gmail.com");
auto temp_binding = iam_bindings.bindings();
auto it = temp_binding[role].find("abc@gmail.com");
EXPECT_EQ(temp_binding[role].end(), it);
iam_bindings.RemoveMember("writer", "xyz@gmail.com");
EXPECT_TRUE(iam_bindings.end() == iam_bindings.find(role));
}
TEST(IamBindingsTest, RemoveMembersTest) {
std::string role = "writer";
std::set<std::string> members = {"abc@gmail.com", "xyz@gmail.com"};
auto iam_binding = IamBinding(role, members);
std::vector<IamBinding> bindings_vector = {iam_binding};
auto iam_bindings = IamBindings(bindings_vector);
std::set<std::string> member_list = {"abc@gmail.com"};
iam_bindings.RemoveMembers(role, member_list);
auto temp_binding = iam_bindings.bindings();
EXPECT_TRUE(temp_binding[role].end() ==
temp_binding[role].find("abc@gmail.com"));
iam_bindings.RemoveMembers(role, std::set<std::string>{"xyz@gmail.com"});
EXPECT_TRUE(iam_bindings.end() == iam_bindings.find(role));
}
TEST(IamBindingsTest, RemoveMembersTestIamBindingParam) {
std::string role = "writer";
std::set<std::string> members = {"abc@gmail.com", "xyz@gmail.com"};
auto iam_binding = IamBinding(role, members);
std::vector<IamBinding> bindings_vector = {iam_binding};
auto iam_bindings = IamBindings(bindings_vector);
std::set<std::string> member_list = {"abc@gmail.com"};
auto iam_binding_for_removal = IamBinding(role, member_list);
iam_bindings.RemoveMembers(iam_binding_for_removal);
auto temp_binding = iam_bindings.bindings();
bool has_removed_member = false;
for (auto const& it : temp_binding[role]) {
if (it == *member_list.begin()) {
has_removed_member = true;
break;
}
}
EXPECT_FALSE(has_removed_member);
}
} // namespace
} // namespace GOOGLE_CLOUD_CPP_NS
} // namespace cloud
} // namespace google
| 31.843243 | 75 | 0.721609 | orinem |
232bd4a9a7d6d3e438ae0a90496ac3215cdc20b3 | 1,654 | cpp | C++ | codeforces/E - Alternating Tree/Wrong answer on test 5.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/E - Alternating Tree/Wrong answer on test 5.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/E - Alternating Tree/Wrong answer on test 5.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Aug/26/2018 09:46
* solution_verdict: Wrong answer on test 5 language: GNU C++14
* run_time: 218 ms memory_used: 9500 KB
* problem: https://codeforces.com/contest/960/problem/E
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const long mod=1e9+7;
const int N=2e5;
int n,vl[N+2],sz[N+2],sub[N+2][2];
vector<int>adj[N+2];long ans=0;
void dfs(int node,int par)
{
sz[node]=1;
for(int i=0;i<adj[node].size();i++)
{
int xx=adj[node][i];if(xx==par)continue;
dfs(xx,node);sz[node]+=sz[xx];
sub[node][0]=sub[node][0]+sub[xx][1];
sub[node][1]=sub[node][1]+sub[xx][0];
}
sub[node][0]=sub[node][0]+sz[node]*vl[node];
sub[node][1]=sub[node][1]+sz[node]*vl[node]*(-1);
}
void dds(int node,int par,long pos,long neg)
{
ans=ans+pos;
for(int i=0;i<adj[node].size();i++)
{
int xx=adj[node][i];if(xx==par)continue;
long ps=pos,ng=neg;
ps=neg-sz[xx]*vl[node]*(-1)+(sz[1]-sz[xx])*vl[xx];
ng=pos-sz[xx]*vl[node]+(sz[1]-sz[xx])*vl[xx]*(-1);
dds(xx,node,ps,ng);
}
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
cin>>n;
for(int i=1;i<=n;i++)
cin>>vl[i];
for(int i=1;i<n;i++)
{
int u,v;cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}dfs(1,-1);
dds(1,-1,sub[1][0],sub[1][1]);
cout<<ans<<endl;
return 0;
} | 30.62963 | 111 | 0.477025 | kzvd4729 |
232d46cb0148db8e05d528497309fe6ec4f489ce | 9,914 | cpp | C++ | old/cppcon-2017-web-service/example/server/beast/src/main.cpp | Voultapher/Presentations | 67e79dc4ce37cc563d1f976507095ab64c8ed8a1 | [
"Apache-2.0"
] | 7 | 2017-09-15T19:11:24.000Z | 2020-03-04T10:47:29.000Z | old/cppcon-2017-web-service/example/server/beast/src/main.cpp | Voultapher/Presentations | 67e79dc4ce37cc563d1f976507095ab64c8ed8a1 | [
"Apache-2.0"
] | 1 | 2018-03-08T07:02:59.000Z | 2018-03-11T20:51:02.000Z | old/cppcon-2017-web-service/example/server/beast/src/main.cpp | Voultapher/Presentations | 67e79dc4ce37cc563d1f976507095ab64c8ed8a1 | [
"Apache-2.0"
] | 1 | 2020-03-04T10:47:30.000Z | 2020-03-04T10:47:30.000Z | //
// Copyright (c) 2017 Lukas Bergdoll lukas.bergdoll@gmail.com
//
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/strand.hpp>
#include <boost/functional/hash.hpp>
#include <iostream>
#include <array>
#include <unordered_map>
#include <strawpoll.hpp>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
namespace websocket = boost::beast::websocket; // from <boost/beast/websocket.hpp>
//------------------------------------------------------------------------------
namespace detail
{
template<typename T> struct hash
{
size_t operator() (const T& v) const noexcept
{
if (v.is_v4()) return v.to_v4().to_ulong();
if (v.is_v6())
{
auto const& range = v.to_v6().to_bytes();
return boost::hash_range(range.begin(), range.end());
}
if (v.is_unspecified()) return 0x4751301174351161ul;
return boost::hash_value(v.to_string());
}
};
template<typename T, typename M> class member_func_ptr_closure
{
public:
using obj_ptr_t = T*;
using member_func_ptr_t = M;
constexpr member_func_ptr_closure(
obj_ptr_t obj_ptr,
member_func_ptr_t member_func_ptr
) noexcept
: obj_ptr_{obj_ptr}, member_func_ptr_{member_func_ptr}
{}
template<typename... Args> auto operator() (Args&&... args)
{
return ((obj_ptr_)->*(member_func_ptr_))(std::forward<Args>(args)...);
}
private:
obj_ptr_t obj_ptr_;
member_func_ptr_t member_func_ptr_;
};
namespace conv
{
boost::asio::const_buffer m_b(FlatBufferRef buffer)
{
return { buffer.data, buffer.size };
}
}
} // namespace detail
//using poll_data_t = PollData<VoteGuard<boost::asio::ip::address, detail::hash>>;
using poll_data_t = PollData<VoteGuard<std::string, std::hash>>;
//using poll_data_t = PollData<HippieVoteGuard<boost::asio::ip::address>>;
// Report a failure
void fail(boost::system::error_code ec, char const* what)
{
std::cerr << what << ": " << ec.message() << "\n";
}
// Echoes back all received WebSocket messages
template<typename FC, typename FB> class session
{
public:
// Take ownership of the socket
explicit session(
tcp::socket&& socket,
FC on_close,
FB broadcast,
size_t session_id,
poll_data_t& poll_data
)
: ws_{std::move(socket)}
, fingerprint_{}
, strand_{ws_.get_io_service()}
, read_in_process_{false}
, write_in_process_{false}
, on_close_{on_close}
, broadcast_{broadcast}
, session_id_{session_id}
, poll_data_{poll_data}
{
ws_.binary(true); // we'll only write binary
// Accept the websocket handshake
ws_.async_accept(
strand_.wrap([this](boost::system::error_code ec) { on_accept(ec); })
);
}
session(const session&) = delete;
session(session&&) = default;
session& operator= (const session&) = delete;
session& operator= (session&&) = default;
~session() = default;
void add_message(FlatBufferRef br)
{
if (
std::is_same_v<
poll_data_t::vote_guard_t,
HippieVoteGuard<boost::asio::ip::address>
>
|| !write_in_process_ // write should always write the most recent
|| has_voted()
)
message_queue_.push_back(detail::conv::m_b(br));
}
void flush_message_queue()
{
if (write_in_process_) return;
if (message_queue_.empty()) return;
ws_.async_write(
std::array<boost::asio::const_buffer, 1>{{
std::move(message_queue_.back())
}},
strand_.wrap(
[this](boost::system::error_code ec, size_t bytes_transferred)
{
write_in_process_ = false;
on_write(ec, bytes_transferred);
}
)
);
write_in_process_ = true;
message_queue_.pop_back();
}
private:
websocket::stream<tcp::socket> ws_;
std::string fingerprint_;
boost::asio::io_service::strand strand_;
boost::beast::multi_buffer buffer_;
std::vector<boost::asio::const_buffer> message_queue_;
bool read_in_process_;
bool write_in_process_;
FC on_close_;
FB broadcast_;
size_t session_id_;
poll_data_t& poll_data_;
void on_accept(boost::system::error_code ec)
{
if (ec) return fail(ec, "accept");
// Read a message
do_read();
}
void do_read()
{
if (read_in_process_) return;
// Clear the buffer
buffer_.consume(buffer_.size());
// Read a message into our buffer
ws_.async_read(
buffer_,
strand_.wrap(
[this](boost::system::error_code ec, size_t bytes_transferred)
{
read_in_process_ = false;
on_read(ec, bytes_transferred);
}
)
);
read_in_process_ = true;
}
void on_read(
boost::system::error_code ec,
size_t bytes_transferred
) {
boost::ignore_unused(bytes_transferred);
// This indicates that the session was closed
if (ec == websocket::error::closed)
{
on_close_(session_id_);
return;
}
if (ec) fail(ec, "read");
build_responses();
flush_message_queue();
}
void on_write(
boost::system::error_code ec,
size_t// bytes_transferred
) {
//boost::ignore_unused(bytes_transferred);
if (ec) return fail(ec, "write");
if (!message_queue_.empty())
{
flush_message_queue();
return;
}
// Do another read
do_read();
}
void build_responses()
{
const auto add_response = [&queue = message_queue_](FlatBufferRef br)
{
queue.push_back(detail::conv::m_b(br));
};
for (const auto buffer : buffer_.data())
{
const auto ok = flatbuffers::Verifier(
boost::asio::buffer_cast<const uint8_t*>(buffer),
boost::asio::buffer_size(buffer)
).VerifyBuffer<Strawpoll::Request>(nullptr);
if (!ok) {
add_response(poll_data_.error_responses.invalid_message.ref());
continue;
}
const auto request = flatbuffers::GetRoot<Strawpoll::Request>(
boost::asio::buffer_cast<const uint8_t*>(buffer)
);
switch(request->type())
{
case Strawpoll::RequestType_Poll:
fingerprint_ = request->fingerprint()->c_str();
add_response(poll_data_.poll_response.ref());
if (has_voted())
add_response(poll_data_.result_ref());
break;
case Strawpoll::RequestType_Result:
poll_data_.register_vote(
request->vote(),
fingerprint_,
add_response,
[&broadcast = broadcast_](FlatBufferRef br) { broadcast(br); }
);
break;
default:
add_response(poll_data_.error_responses.invalid_type.ref());
}
}
}
bool has_voted() const noexcept
{
return !fingerprint_.empty()
&& poll_data_.vote_guard.has_voted(fingerprint_);
}
};
// Accepts incoming connections and launches the sessions
class listener
{
public:
void on_session_close(size_t session_id)
{
sessions_.erase(session_id);
}
void broadcast(FlatBufferRef br)
{
for (auto& [key, session] : sessions_)
{
session.add_message(br);
session.flush_message_queue();
}
}
using on_session_close_t = detail::member_func_ptr_closure<
listener,
decltype(&listener::on_session_close)
>;
using broadcast_t = detail::member_func_ptr_closure<
listener,
decltype(&listener::broadcast)
>;
using session_t = session<on_session_close_t, broadcast_t>;
using sessions_t = std::unordered_map<size_t, session_t>;
explicit listener(
boost::asio::io_service& ios,
tcp::endpoint endpoint)
: strand_{ios}
, acceptor_{ios}
, socket_{ios}
, session_id_counter_{}
, on_session_close_{this, &listener::on_session_close}
, broadcast_{this, &listener::broadcast}
, poll_data_{}
{
boost::system::error_code ec;
// Open the acceptor
acceptor_.open(endpoint.protocol(), ec);
if (ec)
{
fail(ec, "open");
return;
}
// Bind to the server address
acceptor_.bind(endpoint, ec);
if (ec)
{
fail(ec, "bind");
return;
}
// Start listening for connections
acceptor_.listen(boost::asio::socket_base::max_connections, ec);
if (ec)
{
fail(ec, "listen");
return;
}
if (!acceptor_.is_open()) return;
do_accept();
}
listener(const listener&) = delete;
listener(listener&&) = default;
listener& operator= (const listener&) = delete;
listener& operator= (listener&&) = default;
~listener() = default;
void do_accept()
{
acceptor_.async_accept(
socket_,
strand_.wrap([this](boost::system::error_code ec) { on_accept(ec); })
);
}
void on_accept(boost::system::error_code ec)
{
if (ec)
{
fail(ec, "accept");
}
else
{
// Create the session and run it
//const auto address = socket_.remote_endpoint().address();
sessions_.try_emplace(
session_id_counter_,
std::move(socket_),
//std::move(address),
on_session_close_,
broadcast_,
session_id_counter_,
poll_data_
);
++session_id_counter_;
}
// Accept another connection
do_accept();
}
private:
boost::asio::io_service::strand strand_;
tcp::acceptor acceptor_;
tcp::socket socket_;
size_t session_id_counter_;
on_session_close_t on_session_close_;
broadcast_t broadcast_;
sessions_t sessions_;
poll_data_t poll_data_;
};
//------------------------------------------------------------------------------
int main()
{
const auto address = boost::asio::ip::address::from_string("127.0.0.1");
const auto port = static_cast<unsigned short>(3003);
boost::asio::io_service ios{1};
listener lis{ios, tcp::endpoint{address, port}};
ios.run(); // blocking
}
| 23.604762 | 83 | 0.621142 | Voultapher |
232e78455a5504c010fb9c474543bde1fd64e341 | 3,094 | cpp | C++ | src/0.3.7-R1/CVehiclePool.cpp | DarkP1xel/SAMP-API | 0d43a3603239f2f4bc65b8305ffc72177386cc29 | [
"MIT"
] | 7 | 2019-09-23T10:19:40.000Z | 2021-07-25T06:17:27.000Z | src/0.3.7-R1/CVehiclePool.cpp | DarkP1xel/SAMP-API | 0d43a3603239f2f4bc65b8305ffc72177386cc29 | [
"MIT"
] | null | null | null | src/0.3.7-R1/CVehiclePool.cpp | DarkP1xel/SAMP-API | 0d43a3603239f2f4bc65b8305ffc72177386cc29 | [
"MIT"
] | 1 | 2021-04-11T17:13:00.000Z | 2021-04-11T17:13:00.000Z | /*
This is a SAMP (0.3.7-R1) API project file.
Developer: LUCHARE <luchare.dev@gmail.com>
See more here https://github.com/LUCHARE/SAMP-API
Copyright (c) 2018 BlastHack Team <BlastHack.Net>. All rights reserved.
*/
#include "CVehiclePool.h"
SAMP::CVehiclePool::CVehiclePool() {
((void(__thiscall *)(CVehiclePool *))SAMP_ADDROF(0x1AF20))(this);
}
SAMP::CVehiclePool::~CVehiclePool() {
((void(__thiscall *)(CVehiclePool *))SAMP_ADDROF(0x1B570))(this);
}
BOOL SAMP::CVehiclePool::Create(Info *pVehicle) {
return ((BOOL(__thiscall *)(CVehiclePool *, Info *))SAMP_ADDROF(0x1B590))(this, pVehicle);
}
BOOL SAMP::CVehiclePool::Delete(ID nId) {
return ((BOOL(__thiscall *)(CVehiclePool *, ID))SAMP_ADDROF(0x1AF90))(this, nId);
}
void SAMP::CVehiclePool::AddToWaitingList(const Info *pVehicle) {
((void(__thiscall *)(CVehiclePool *, const Info *))SAMP_ADDROF(0x1B220))(this, pVehicle);
}
void SAMP::CVehiclePool::ProcessWaitingList() {
((void(__thiscall *)(CVehiclePool *))SAMP_ADDROF(0x1B810))(this);
}
void SAMP::CVehiclePool::SendDestroyNotification(ID nId) {
((void(__thiscall *)(CVehiclePool *, ID))SAMP_ADDROF(0x1B740))(this, nId);
}
SAMP::ID SAMP::CVehiclePool::GetNearest() {
return ((ID(__thiscall *)(CVehiclePool *))SAMP_ADDROF(0x1B110))(this);
}
SAMP::ID SAMP::CVehiclePool::Find(::CVehicle *pGameObject) {
return ((ID(__thiscall *)(CVehiclePool *, ::CVehicle *))SAMP_ADDROF(0x1B0A0))(this, pGameObject);
}
SAMP::GTAREF SAMP::CVehiclePool::GetRef(int nId) {
return ((GTAREF(__thiscall *)(CVehiclePool *, int))SAMP_ADDROF(0x1B0D0))(this, nId);
}
SAMP::GTAREF SAMP::CVehiclePool::GetRef(::CVehicle *pGameObject) {
return ((GTAREF(__thiscall *)(CVehiclePool *, ::CVehicle *))SAMP_ADDROF(0x1B0F0))(this, pGameObject);
}
void SAMP::CVehiclePool::Process() {
((void(__thiscall *)(CVehiclePool *))SAMP_ADDROF(0x1B8D0))(this);
}
void SAMP::CVehiclePool::ChangeInterior(ID nId, int nInteriorId) {
((void(__thiscall *)(CVehiclePool *, ID, char))SAMP_ADDROF(0x1B010))(this, nId, nInteriorId);
}
SAMP::ID SAMP::CVehiclePool::GetNearest(CVector point) {
return ((ID(__thiscall *)(CVehiclePool *, CVector))SAMP_ADDROF(0x1B180))(this, point);
}
void SAMP::CVehiclePool::ConstructLicensePlates() {
((void(__thiscall *)(CVehiclePool *))SAMP_ADDROF(0x1B280))(this);
}
void SAMP::CVehiclePool::ShutdownLicensePlates() {
((void(__thiscall *)(CVehiclePool *))SAMP_ADDROF(0x1B2F0))(this);
}
BOOL SAMP::CVehiclePool::DoesExist(ID nId) {
return ((BOOL(__thiscall *)(CVehiclePool *, ID))SAMP_ADDROF(0x1140))(this, nId);
}
SAMP::CVehicle *SAMP::CVehiclePool::GetObject(ID nId) {
return ((CVehicle *(__thiscall *)(CVehiclePool *, ID))SAMP_ADDROF(0x1110))(this, nId);
}
void SAMP::CVehiclePool::SetParams(ID nVehicle, bool bIsObjective, bool bIsLocked) {
((void(__thiscall *)(CVehiclePool *, ID, bool, bool))SAMP_ADDROF(0x1B040))(this, nVehicle, bIsObjective, bIsLocked);
}
void SAMP::CVehiclePool::UpdateCount() {
((void(__thiscall *)(CVehiclePool *))SAMP_ADDROF(0x1AEC0))(this);
} | 34.377778 | 118 | 0.701034 | DarkP1xel |
2334b3ea9ce2b60a25bef2bb98e769ef6cd63e4f | 2,683 | hpp | C++ | NWNXLib/API/API/CNWBaseItem.hpp | summonFox/unified | 47ab7d051fe52c26e2928b569e9fe7aec5aa8705 | [
"MIT"
] | 111 | 2018-01-16T18:49:19.000Z | 2022-03-13T12:33:54.000Z | NWNXLib/API/API/CNWBaseItem.hpp | summonFox/unified | 47ab7d051fe52c26e2928b569e9fe7aec5aa8705 | [
"MIT"
] | 636 | 2018-01-17T10:05:31.000Z | 2022-03-28T20:06:03.000Z | NWNXLib/API/API/CNWBaseItem.hpp | summonFox/unified | 47ab7d051fe52c26e2928b569e9fe7aec5aa8705 | [
"MIT"
] | 110 | 2018-01-16T19:05:54.000Z | 2022-03-28T03:44:16.000Z | #pragma once
#include "nwn_api.hpp"
#include "CExoString.hpp"
#include "CResRef.hpp"
#ifdef NWN_API_PROLOGUE
NWN_API_PROLOGUE(CNWBaseItem)
#endif
typedef int BOOL;
typedef uint32_t STRREF;
struct CNWBaseItem
{
uint32_t m_nName;
uint32_t m_nEquipableSlots;
uint8_t m_nWeaponWield;
uint8_t m_nWeaponType;
uint32_t m_nMinRange;
uint32_t m_nMaxRange;
uint8_t m_nInvSlotWidth;
uint8_t m_nInvSlotHeight;
uint8_t m_nModelType;
uint8_t m_nStartingCharges;
uint8_t m_nWeaponRanged;
uint8_t m_nWeaponSize;
uint8_t m_nNumDice;
uint8_t m_nDieToRoll;
uint8_t m_nCritThreat;
uint8_t m_nCritMult;
uint8_t m_nCategory;
float m_nBaseCost;
uint16_t m_nStackSize;
float m_nCostMultiplier;
uint32_t m_nDescription;
uint8_t m_nMinProperties;
uint8_t m_nMaxProperties;
uint8_t m_nPropColumn;
uint8_t m_nStorePanel;
uint8_t m_nStorePanelSort;
uint8_t m_nPercentageSlashL;
uint8_t m_nPercentageSlashR;
uint8_t m_nPercentageSlashS;
uint8_t m_nILRStackSize;
float m_fPreferredAttackDist;
char m_ItemClassResRefChunk[10+1];
BOOL m_bPartEnvMap[3];
CResRef m_DefaultIconResRef;
CResRef m_DefaultModelResRef;
BOOL m_bCanRotateIcon;
BOOL m_bContainer;
BOOL m_bGenderSpecific;
uint8_t m_InventorySoundType;
uint16_t * m_pRequiredFeats;
uint8_t m_nRequiredFeatCount;
STRREF m_nStatsString;
uint8_t m_nRotateOnGround;
int32_t m_nWeight;
uint8_t m_nBaseAC;
uint8_t m_nACEnchantmentType;
uint8_t m_nWeaponMaterialType;
char m_nArmorCheckPenalty;
char m_nAmmunitionType;
uint8_t m_nQBBehaviourType;
uint8_t m_nArcaneSpellFailure;
uint16_t m_nWeaponFocusFeat;
uint16_t m_nEpicWeaponFocusFeat;
uint16_t m_nWeaponSpecializationFeat;
uint16_t m_nEpicWeaponSpecializationFeat;
uint16_t m_nWeaponImprovedCriticalFeat;
uint16_t m_nEpicWeaponOverwhelmingCriticalFeat;
uint16_t m_nEpicWeaponDevastatingCriticalFeat;
uint16_t m_nWeaponOfChoiceFeat;
BOOL m_bIsMonkWeapon;
uint8_t m_nWeaponFinesseMinimumCreatureSize;
CNWBaseItem();
~CNWBaseItem();
CExoString GetNameText();
CResRef GetModelResRef(uint8_t nPart, int16_t nModelNumber, char nGender = 'm');
CResRef GetIconResRef(uint8_t nPart, int16_t nModelNumber, char nGender = 'm');
uint16_t GetRequiredFeat(uint8_t nReqFeatIndex);
void SetRequiredFeat(uint8_t nReqFeatIndex, uint16_t nFeat);
void SetRequiredFeatCount(uint8_t nReqFeatCount);
#ifdef NWN_CLASS_EXTENSION_CNWBaseItem
NWN_CLASS_EXTENSION_CNWBaseItem
#endif
};
#ifdef NWN_API_EPILOGUE
NWN_API_EPILOGUE(CNWBaseItem)
#endif
| 26.303922 | 84 | 0.77227 | summonFox |
2336d034c0392bb62b50ffa729c17855eb78c5ca | 45,212 | cpp | C++ | src/libs/socket/Server.cpp | mscoccimarro/1942-multiplayer | 58db747cf5d7519156c251dbbc37b1adeaa615d1 | [
"MIT"
] | null | null | null | src/libs/socket/Server.cpp | mscoccimarro/1942-multiplayer | 58db747cf5d7519156c251dbbc37b1adeaa615d1 | [
"MIT"
] | null | null | null | src/libs/socket/Server.cpp | mscoccimarro/1942-multiplayer | 58db747cf5d7519156c251dbbc37b1adeaa615d1 | [
"MIT"
] | null | null | null | #include "Server.h"
#include "../transmitter/Transmitter.h"
#include "../socket/sock_dep.h" /* socket dependencies */
#include "../../xml/parser/XMLParser.h"
#include "../palette/palette.h"
#include "../../utils/K.h"
#define DEBUG 1
#include "../debug/dg_msg.h"
#include <regex>
#include <thread>
#include <mutex>
#include <iostream>
#include "../../xml/parser/GameParser.h"
#include "../../xml/parser/XMLParser.h"
using namespace std;
Server::Server( const char* configFileName ) {
this->config = GameParser::parse("gameconf.xml");
this->socketFD = 0;
this->clientCount = 0;
this->readyPlayers = 0;
this->maxClientCount = this->config->maxClients;
this->listening = false;
this->connected = false;
this->processing = false;
this->eventQueue = new queue<map<int, Evento*>*>;
this->logger = Logger::instance();
this->running = false;
this->stageData = NULL;
this->posicionInicialX = 42;
this->posicionInicialY = 100;
this->createGameData();
// this->config = XMLParser::parseServerConf( configFileName );
this->alphaTeamScore = 0;
this->betaTeamScore = 0;
this->coopTeamScore = 0;
this->enemyID = 0;
this->powerUpID = 0;
this->numeroDeFlota = 1000;
this->resumePlayer = false;
}
Server::~Server() {
// Delete players if any
if( !( this->players.empty() ) ) {
for( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end();
++it ) {
delete it->second;
}
}
if( !( this->flotas.empty() ) ) {
for( map<int, FlotaObserver*>::iterator it2 = this->flotas.begin();
it2 != this->flotas.end(); ++it2 ) {
delete it2->second;
}
}
delete this->eventQueue;
}
void Server::initialize() {
if( this->connected ) {
this->logger->warn( CONNECTION_ACTIVE );
DEBUG_WARN( CONNECTION_ACTIVE );
return;
}
int cfd; // client file descriptor
struct sockaddr_storage client_addr; // client address information
struct addrinfo hints, *servinfo, *p; // configuration structs
int rv;
// init hints struct with 0
memset( &hints, 0, sizeof( hints ) );
// set hints struct values
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // use host IP
// fill configuration structs
// HARDCODEADO
if( ( rv = getaddrinfo( NULL, to_string( 8000 ).c_str(), &hints, &servinfo ) ) != 0 ) {
this->logger->error( "Error al obtener la direccion, " + string( gai_strerror( rv ) ) );
exit( -1 );
}
int yes = 1;
// loop through results and bind to one of them
for( p = servinfo; p != NULL; p = p->ai_next ) {
// try to create TCP socket
if( ( this->socketFD = socket( p->ai_family, p->ai_socktype, p->ai_protocol ) ) == -1 ) {
this->logger->error( SOCKET_ERROR );
continue; // try next one
}
// allow port reuse to avoid bind error
if( setsockopt( this->socketFD, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof( int ) ) == -1 ) {
this->logger->error( SOCKET_REUSE_ERROR );
exit( -1 );
}
// bind socket
if( bind( this->socketFD, p->ai_addr, p->ai_addrlen ) == -1 ) {
close( this->socketFD );
this->logger->error( BIND_ERROR );
continue; // try next one
}
break; // socket created and binded
}
freeaddrinfo( servinfo ); // free memory
if( p == NULL ) {
this->logger->error( BIND_CERROR );
exit( -1 );
}
// listen for connections
if( listen( this->socketFD, this->BACKLOG ) == -1 ) {
this->logger->error( LISTEN_ERROR );
exit( -1 );
}
this->listening = true;
this->connected = true;
this->processing = true;
thread processor( &Server::processQueue, this );
processor.detach();
this->logger->info( SERVER_START );
DEBUG_NOTICE( SERVER_START );
// accept connections
thread t2( &Server::listenForConnections, this, cfd, client_addr );
t2.detach();
}
void Server::listenForConnections( int cfd, struct sockaddr_storage client_addr ) {
socklen_t sinSize = sizeof client_addr;
while( this->listening ) {
char clientIP[ INET_ADDRSTRLEN ]; // connected client IP
// accept connection
if( ( cfd = accept( this->socketFD, (struct sockaddr*) (&client_addr), &sinSize ) ) == -1 ) {
this->logger->error( "Error al aceptar Cliente" );
continue;
}
this->clientCount++;
// if client slots left
if ( this->clientCount <= this->maxClientCount ) {
// get connected host IP in presentation format
inet_ntop( client_addr.ss_family,
this->getInAddr( (struct sockaddr*) (&client_addr) ), clientIP,
sizeof clientIP);
// notify client of established connection
cout << endl << notice( "Se inicio una conexion con el host: " ) << clientIP
<< endl;
this->logger->info( "Se inicio una conexion con el host: " + string( clientIP ) );
if( send( cfd, "Aceptado", 8, 0 ) == -1 ) {
this->logger->error( "Error al enviar que se acepto la conexion" );
}
usleep( 100 );
// send used planes and game data
this->sendPlanesActives( cfd );
this->sendGameData( cfd );
this->sendConf(cfd);
// create timeout check thread
thread tCheckAliveSend( &Server::checkAliveSend, this, cfd );
tCheckAliveSend.detach();
// create thread for receiving client data
thread process( &Server::receiveClientData, this, cfd, clientIP );
process.detach();
} else {
cout << endl << warning( "El cliente " ) << clientIP << warning( " se rechazo" ) << endl;
this->logger->warn( "El cliente " + string(clientIP) + " se rechazo" );
//usleep( 1000000 );
this->closeClient( cfd );
}
}
}
// get sockaddr, IPv4
void* Server::getInAddr( struct sockaddr* sa ) {
if( sa->sa_family == AF_INET ) {
return &( ( (struct sockaddr_in*) sa )->sin_addr );
}
}
void Server::updatePlayerStatus( PlayerStatus* data, int cfd ) {
if( data->status == 'I' ) {
this->players[ cfd ]->deactivate();
} else if ( data->status == 'D' ) {
this->players[ cfd ]->die();
// check if remaining players win or loose
if ( this->gameData->teamMode ) {
this->checkTeamWin();
} else {
this->checkCoopLose();
}
}
if (data->status == 'R' ){
this->players[ cfd ]->changeReady();
cout<<"Estado: cantidad de players - "<< this->players.size()<<endl;
if(this->players.size() == this->maxClientCount){
this->sendPlayersReady();
}
}
}
void Server::addPlayer(PlayerData* data, int cfd) {
string validName = "Y", validColor = "Y";
mutex theMutex;
string selectedName(data->name);
string selectedColor(data->color);
int selectedTeam = data->team;
int score = 0;
bool createPlayer = true;
bool encontrePlayer = false;
theMutex.lock();
for (map<int, Player*>::iterator it = this->players.begin() ; it != this->players.end() ; ++it) {
// if already a player with that name
if (selectedName == it->second->getName()) {
createPlayer = false;
validName = "N";
cout<<"Encuentro Player"<<endl;
// if running game and player with such name is not active
if ( this->running && !(it->second->isActive())) {
encontrePlayer = true;
this->resumePlayer = true;
// resume player game
cout<<"Resume Game"<<endl;
selectedColor = it->second->getColor();
cout << "RESUME SCORE: " << it->second->getScore() << endl;
score = it->second->getScore();
posicionInicialX = it->second->getX();
posicionInicialY = it->second->getY();
estacionamientoX = it->second->getEstacionamientoX();
estacionamientoY = it->second->getEstacionamientoY();
delete it->second;
this->players.erase(it);
createPlayer = true;
validName = "R";
validColor = "R";
break;
}
}
// if already a player with that color
if (selectedColor == it->second->getColor()) {
createPlayer = false;
validColor = "N";
}
}
theMutex.unlock();
if (createPlayer && (this->players.size() < this->maxClientCount) ) {
// Add new player
cout<<"Creo Jugador"<<endl;
Player* p;
if (encontrePlayer) {
p = new Player(selectedName, selectedColor, posicionInicialX, posicionInicialY, estacionamientoX, estacionamientoY, selectedTeam);
} else {
p = new Player(selectedName, selectedColor, posicionInicialX, posicionInicialY, selectedTeam);
}
p->addScore( score );
theMutex.lock();
this->players[cfd] = p;
posicionInicialX += 200;
theMutex.unlock();
} else {
cout<<"No creo jugador"<<endl;
createPlayer = false;
validName = "N";
validColor = "N";
}
// Create response
PlayerData* response = new PlayerData;
// Fill response struct
strcpy(response->name, validName.c_str());
strcpy(response->color, validColor.c_str());
cout<<"name :"<<validName<<" .Color: "<<validColor<<endl;
Transmitter* tmt = new Transmitter(cfd, this->logger);
if (!(tmt->sendData(response))) {
DEBUG_WARN("No se pude enviar respuesta a cliente. JOB: Server::addPlayer");
this->logger->error("No se pude enviar respuesta a cliente. JOB: Server::addPlayer");
}
delete response;
delete tmt;
theMutex.lock();
if (createPlayer && this->players.size() == this->maxClientCount) {
cout << "send players" << endl;
this->createPlayers();
if( !( this->running ) ) this->running = true;
if(this->resumePlayer) {
this->resumeClientEnemys();
this->resumeClientPowerUp();
this->resumePlayer = false;
}
}
theMutex.unlock();
}
void Server::queryCurrentStageOffset() {
if( this->stageData != NULL ) {
delete this->stageData;
this->stageData = NULL;
}
for( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end(); ++it ) {
if( it->second->isActive() ) {
Transmitter* tmt = new Transmitter( it->first, this->logger );
tmt->sendDataID( "SQ" );
delete tmt;
break;
}
}
}
void Server::sendCurrentStageOffset( int clientFD ) {
while( this->stageData == NULL );
Transmitter* tmt = new Transmitter( clientFD, this->logger );
tmt->sendData( this->stageData, "SD" );
delete tmt;
}
void Server::createPlayers() {
// reset player starting positions
this->posicionInicialX = 42;
this->posicionInicialY = 100;
map<int, Player*>::iterator it2 = this->players.begin();
for (int i = 0; i < this->players.size(); i++) {
// if player not active
cout << "Send " << i << endl;
// this->sendConf(it2->first);
if( !( it2->second->isActive() ) ) {
// send stage config
cout << "Send in if " << i << endl;
// if game already started
if( this->running ) {
// get stage offset
this->queryCurrentStageOffset();
// send stage offset to player
this->sendCurrentStageOffset( it2->first );
}
}
// send other players data
for (map<int, Player*>::iterator it = this->players.begin();
it != this->players.end(); ++it) {
Player* player = it->second;
Transmitter* tmt = new Transmitter(it2->first, this->logger);
PlayerData* pd = new PlayerData;
strcpy(pd->name, player->getName().c_str());
strcpy(pd->color, player->getColor().c_str());
pd->x = player->getX();
pd->y = player->getY();
pd->estacionamientoX = player->getEstacionamientoX();
pd->estacionamientoY = player->getEstacionamientoY();
pd->team = player->getTeam();
pd->score = player->getScore();
if ( it2->second->getName() == player->getName() ) {
pd->coopTeamScore = this->coopTeamScore;
pd->alphaTeamScore = this->alphaTeamScore;
pd->betaTeamScore = this->betaTeamScore;
}
while (!tmt->sendData(pd, "PR"));
delete pd;
delete tmt;
}
// activate player
it2->second->activate();
it2++;
}
}
void Server::sendPlanesActives(int cfd){
PlanesActives* planes = new PlanesActives;
planes->blue = true;
planes->red = true;
planes->green = true;
planes->yellow = true;
mutex theMutex;
theMutex.lock();
for( map<int, Player*>::iterator it = this->players.begin(); it != this->players.end(); ++it ) {
// if game is running and player is inactive, skip
if( this->running && !( it->second->isActive() ) ) continue;
// if already a player with that color
if( it->second->getColor() == "azul" ) {
planes->blue = false;
} else if( it->second->getColor() == "rojo" ) {
planes->red = false;
} else if( it->second->getColor() == "verde" ) {
planes->green = false;
} else if( it->second->getColor() == "amarillo" ) {
planes->yellow = false;
}
}
theMutex.unlock();
Transmitter* tmt = new Transmitter( cfd, this->logger );
if( !( tmt->sendData( planes ) ) ) {
DEBUG_WARN( "No se pude enviar respuesta a cliente. JOB: Server::addPlayer" );
this->logger->error( "No se pude enviar respuesta a cliente. JOB: Server::addPlayer" );
}
delete planes;
delete tmt;
}
void Server::sendConf(int cfd){
this->config = GameParser::parse("gameconf.xml");
Transmitter* tmt = new Transmitter( cfd, this->logger );
AvionConf* avion = this->config->avion;
if( !( tmt->sendData( avion ) ) ) {
DEBUG_WARN( "No se pude enviar respuesta a cliente. JOB: Server::send avion" );
this->logger->error( "No se pude enviar respuesta a cliente. JOB: Server::send avion" );
}
EscenarioConf* escenario = this->config->escenario;
if( !( tmt->sendData( escenario ) ) ) {
DEBUG_WARN( "No se pude enviar respuesta a cliente. JOB: Server::send escenario" );
this->logger->error( "No se pude enviar respuesta a cliente. JOB: Server::send escenario" );
}
vector<ElementoConf*> elementos = this->config->elementos;
for (int var = 0; var < elementos.size(); ++var) {
ElementoConf* elemento = elementos[var];
if( !( tmt->sendData( elemento ) ) ) {
DEBUG_WARN( "No se pude enviar respuesta a cliente. JOB: Server::send elementos" );
this->logger->error( "No se pude enviar respuesta a cliente. JOB: Server::send elementos" );
}
}
/*vector<PowerUpConf*> powerUps = this->config->powerUps;
for (int var = 0; var < powerUps.size(); ++var) {
PowerUpConf* powerUp = powerUps[var];
if( !( tmt->sendData( powerUp ) ) ) {
DEBUG_WARN( "No se pude enviar respuesta a cliente. JOB: Server::send powerUps" );
this->logger->error( "No se pude enviar respuesta a cliente. JOB: Server::send powerUps" );
}
}
*/
vector<EnemigoConf*> enemigos = this->config->enemigos;
cout << "MANDANDO ENEMIGOS " << endl;
for (int var = 0; var < enemigos.size(); var++) {
EnemigoConf* enemigo = enemigos[var];
if (!tmt->sendData(enemigo)) {
DEBUG_WARN( "No se pude enviar respuesta a cliente. JOB: Server::send enemigos" );
this->logger->error( "No se pude enviar respuesta a cliente. JOB: Server::send enemigos" );
}
}
vector<SpriteConf* > sprites = this->config->sprites;
cout << "MANDANDO SPRITES " << endl;
for (int var = 0; var < sprites.size(); ++var) {
SpriteConf* sprite = sprites[var];
if( !( tmt->sendData( sprite ) ) ) {
DEBUG_WARN( "No se pude enviar respuesta a cliente. JOB: Server::send Sprites" );
this->logger->error( "No se pude enviar respuesta a cliente. JOB: Server::send Sprites" );
}
}
cout << "VOY A ENVIAR EN SEND END" << endl;
while( !( tmt->sendEndDataConf(this->clientCount)) ) {
DEBUG_WARN( "No se pude enviar respuesta a cliente. JOB: Server::sendConf" );
this->logger->error( "No se pude enviar respuesta a cliente. JOB: Server::sendConf" );
}
cout << "YA TERMINE" << endl;
// cout<<"Envio toda la Configuracion"<<endl;
delete tmt;
}
void Server::receiveClientData( int cfd, string clientIP ) {
Evento* msgToRecv = new Evento;
mutex theMutex;
timeval timeout;
timeout.tv_sec = this->MAX_UNREACHABLE_TIME;
timeout.tv_usec = 0;
bool receiving = true;
int bytesReceived;
char id[3];
// Create transmitter for this client
Transmitter* tmt = new Transmitter( cfd, this->logger );
while( receiving ) {
// seteo el timeout de recepcion de mensajes
if( setsockopt( cfd, SOL_SOCKET, SO_RCVTIMEO, (char*) &timeout, sizeof( timeout ) ) < 0 ) {
cout << "Error sockopt" << endl;
exit( 1 );
}
// Get id of next data to receive
bytesReceived = tmt->receiveData( id, sizeof( id ));
if( bytesReceived > 0 ) {
string dataID( id );
// Receive data type based on fetched dataID
if( dataID == "PD" ) {
PlayerData* data = new PlayerData;
if( ( bytesReceived = tmt->receiveData( data )) > 0 ) {
// Process received data
cout << "Nombre del jugador: " << string( data->name ) << endl;
cout << "Color del jugador: " << string( data->color ) << endl;
this->addPlayer( data, cfd );
}
delete data;
} else if( dataID == "PS" ) {
PlayerStatus* data = new PlayerStatus;
if( ( bytesReceived = tmt->receiveData( data )) > 0 ) {
// Process received data
cout << "Player status: " << data->status << endl;
this->updatePlayerStatus( data, cfd );
}
delete data;
} else if (dataID == "EV") {
Evento* e = new Evento();
if (( bytesReceived = tmt->receiveData(e)) > 0 ) {
cout << "Evento: " << e->value << endl;
//Modo Practica
if (e->value == 'O'){
this->gameData->practiceMode = false;
}
theMutex.lock();
cout << endl << "FD cliente: " << notice(to_string(cfd)) << endl;
map<int, Evento*>* clientMsgFD = new map<int, Evento*>();
clientMsgFD->insert(pair<int, Evento*>(cfd, e));
this->eventQueue->push(clientMsgFD);
theMutex.unlock();
}
} else if ( dataID == "QG" ) {
// free player slot
this->freePlayerSlot( cfd );
} else if (dataID == "DP") {
PlayerData* data = new PlayerData;
if( ( bytesReceived = tmt->receiveData( data ) ) > 0 ) {
for (map<int, Player*>::iterator it = this->players.begin(); it != this->players.end(); ++it) {
if ( data->name == (it->second)->getName() ){
Player* p = it->second;
p->setX(data->x);
p->setY(data->y);
//cout<< "Jugador: " << p->getName() << endl<< "Color: " << p->getColor() << endl<<"Posiciones :" << p->getX() << " "<< p->getY()<<endl;
break;
}
}
}
delete data;
} else if(dataID == "CO" ){
cout<<"Reset cliente "<<cfd<<endl;
this->sendConf(cfd);
} else if( dataID == "SD" ) {
StageData* data = new StageData;
if( ( bytesReceived = tmt->receiveData( data ) ) > 0 ) {
// Process received data
cout << "Current stage offset: " << data->offset << endl;
this->stageData = data;
}
} else if( dataID == "SP" ) {
PlayerScore* data = new PlayerScore;
if( ( bytesReceived = tmt->receiveData( data ) ) > 0 ) {
// add score to corresponding player
this->addScoreToPlayer( data );
}
delete data;
} else if( dataID == "PQ" ) {
// send active players count
this->sendActivePlayers( cfd );
} else if( dataID == "RR" ) {
// increment player ready count
this->readyPlayers++;
if ( this->readyPlayers == this->getActivePlayersCount() ) {
this->sendStageReadySignal();
this->readyPlayers = 0;
}
} else if( dataID == "ST" ) {
// send score table
this->sendScoreTable( cfd );
} else if( dataID == "RS" ) {
// reset score
this->players[ cfd ]->resetScore();
this->coopTeamScore = 0;
this->alphaTeamScore = 0;
this->betaTeamScore = 0;
} else if( dataID == "GD" ) {
GameData* data = new GameData;
if( ( bytesReceived = tmt->receiveData( data ) ) > 0 ) {
// Process received data
this->gameData = data;
cout<<"cantidad team 1 "<<this->gameData->countPlayersTeam1<<endl;
cout<<"cantidad team 2 "<<this->gameData->countPlayersTeam2<<endl;
this->sendGameData( cfd );
}
} else if( dataID == "MT" ) {
if(!this->gameData->cooperativeMode && !this->gameData->teamMode){
this->gameData->teamMode = true;
// cout<<"modo team"<<endl;
this->sendGameDataAll();
}
} else if( dataID == "MC" ) {
if(!this->gameData->cooperativeMode && !this->gameData->teamMode){
this->gameData->cooperativeMode = true;
// cout<<"modo cooperativo"<<endl;
this->setTeamPlayer(0, cfd);
this->sendGameDataAll();
}
} else if( dataID == "MP" ) {
if(!this->gameData->practiceMode){
this->gameData->practiceMode = true;
// cout<<"modo cooperativo"<<endl;
this->sendGameDataAll();
}
} else if( dataID == "T1" ) {
cout<<"se suma al team 1"<<endl;
this->gameData->countPlayersTeam1++;
this->setTeamPlayer(1, cfd);
this->sendGameDataAll();
} else if( dataID == "T2" ) {
cout<<"se suma al team 2"<<endl;
this->gameData->countPlayersTeam2++;
this->setTeamPlayer(2, cfd);
this->sendGameDataAll();
} else if ( dataID == "SE" ) {
EnemyStatus* data = new EnemyStatus;
if( ( bytesReceived = tmt->receiveData( data ) ) > 0 ) {
cout << "ENEMY ID: " << to_string( data->id ) << endl;
cout << "ENEMY STATUS: " << data->status << endl;
mutex m;
if ( data->status == 'D' ) {
if ( data->id == -1 ) {
m.lock();
for( map<int, ServerAvionEnemigo*>::iterator it = this->enemys.begin();
it != this->enemys.end(); ) {
if ( it->second->isActive() ) {
PlayerScore* ps = new PlayerScore;
strcpy( ps->name, ( this->players[ cfd ]->getName() ).c_str() );
ps->team = this->players[ cfd ]->getTeam();
ps->score = this->enemys[ it->first ]->getKillScore();
this->addScoreToPlayer( ps );
delete ps;
delete it->second;
it = this->enemys.erase( it );
} else {
++it;
}
}
m.unlock();
} else {
m.lock();
this->removeEnemy( data->id );
m.unlock();
}
} else if (data->status == 'R') {
this->createEnemys();
this->createPowerUps();
} else if ( data->status == 'A' ) {
m.lock();
if (this->enemys.find(data->id) != this->enemys.end()) {
this->enemys[data->id]->activate();
}
m.unlock();
} else if ( data->status == 'P' ) {
m.lock();
//cout << "NEW POSITION X OF " << to_string( data->id ) << ": " << to_string( data->x ) << endl;
//cout << "NEW POSITION Y OF " << to_string( data->id ) << ": " << to_string( data->y ) << endl;
if ( this->enemys.find( data->id ) != this->enemys.end() )
this->enemys[ data->id ]->updatePosition( data->x, data->y );
m.unlock();
} else if ( data->status == 'H' ) {
m.lock();
if ( this->enemys.find( data->id ) != this->enemys.end() ) {
// Si es una Flota, analiza si la FlotaObserver detecto que era la ultima y si fue el mismo
// cfd el que lo mato
if (this->enemys[ data->id ]->getType() == 'f') {
ServerAvionEnemigoFlota* flota = (ServerAvionEnemigoFlota*)this->enemys[ data->id ];
flota->bajarHP(cfd);
if (this->flotas[ flota->getNumeroDeFlota() ]->ultimaFlotaYtodosPorElMismo()) {
PlayerScore* ps = new PlayerScore;
strcpy( ps->name, ( this->players[ cfd ]->getName() ).c_str() );
ps->team = this->players[ cfd ]->getTeam();
ps->score = 1000;
this->addScoreToPlayer( ps );
delete ps;
//cout << ">> BONUUUUS --> TODOS LOS AVIONES MATADOS POR: "<< cfd << endl;
}
} else {
if(this->enemys[data->id]->getType() == 'g') {
ServerAvionEnemyGrande* grande = (ServerAvionEnemyGrande*)this->enemys[data->id];
grande->bajarHP(cfd);
if(!grande->aunVive() && grande->mismoJugador) {
PlayerScore* bonus = new PlayerScore;
strcpy(bonus->name, (this->players[cfd]->getName()).c_str());
bonus->team = this->players[cfd]->getTeam();
bonus->score = 1500;
this->addScoreToPlayer(bonus);
cout << "BONUS POR MATAR AL GRANDE SOLO" << endl;
}
} else {
if (this->enemys[data->id]->getType() == 'm') {
ServerAvionEnemigoMedio* medio = (ServerAvionEnemigoMedio*)this->enemys[data->id];
medio->bajarHP(cfd);
if (!medio->aunVive() && medio->mismoJugador) {
PlayerScore* bonus = new PlayerScore;
strcpy(bonus->name, (this->players[cfd]->getName()).c_str());
bonus->team = this->players[cfd]->getTeam();
bonus->score = 500;
this->addScoreToPlayer(bonus);
cout << "BONUS POR MATAR AL MEDIANO SOLO" << endl;
}
}
else {
this->enemys[ data->id ]->bajarHP();
}
}
}
PlayerScore* ps = new PlayerScore;
strcpy( ps->name, ( this->players[ cfd ]->getName() ).c_str() );
ps->team = this->players[ cfd ]->getTeam();
ps->score = this->enemys[ data->id ]->getHitScore();
if ( ps->score > 0 ) {
this->addScoreToPlayer( ps );
}
// if enemy is still alive, send HP reduction
if ( this->enemys[ data->id ]->aunVive() ) {
this->sendEnemyUpdate( data, cfd );
// if enemy is dead, send enemy death
} else {
ps->score = this->enemys[ data->id ]->getKillScore();
this->addScoreToPlayer( ps );
this->removeEnemy( data->id );
this->sendEnemyDeath( data->id, cfd );
}
delete ps;
}
m.unlock();
}
}
delete data;
} else if ( dataID == "PU" ) {
PowerUpData* data = new PowerUpData;
mutex m;
if( ( bytesReceived = tmt->receiveData( data ) ) > 0 ) {
if ( data->status == 'H' ) {
m.lock();
this->activatePowerUp( data, cfd );
m.unlock();
} else if ( data->status == 'M' ) {
m.lock();
//cout << "NEW POSITION X OF " << to_string( data->id ) << ": " << to_string( data->x ) << endl;
//cout << "NEW POSITION Y OF " << to_string( data->id ) << ": " << to_string( data->y ) << endl;
if ( this->powerUps.find( data->id ) != this->powerUps.end() )
this->powerUps[ data->id ]->updatePosition( data->x, data->y );
m.unlock();
}
}
delete data;
}
}
// Check peer disconnection or timeout
if ( bytesReceived <= 0 ) {
receiving = false;
if ( this->running && ( this->clientCount > 1 ) && ( this->players.find( cfd ) != this->players.end() ) ) {
thread timedDisconnection( &Server::checkAliveClose, this, cfd );
timedDisconnection.detach();
} else {
this->closeClient( cfd );
}
// disconnection
if( bytesReceived == 0 ) {
cout << endl << warning( "El cliente " ) << clientIP
<< warning( " se desconecto" ) << endl;
this->logger->warn( "El Cliente " + string( clientIP ) + " se desconecto" );
// timeout
} else {
DEBUG_WARN( CONNECTION_TIMEOUT );
this->logger->warn( CONNECTION_TIMEOUT );
}
}
}
}
void Server::checkAliveClose( int clientFD ) {
this->avisarDesconexionDeAvion( clientFD );
this->closeClient( clientFD );
this->players[ clientFD ]->deactivate();
// 10 sec wait
usleep( 10000000 );
// if player didn't resume
if ( this->players.find( clientFD ) != this->players.end() ) {
this->freePlayerSlot( clientFD );
}
}
void Server::avisarDesconexionDeAvion(int cfd) {
// if player isn't playing yet, skip
map<int, Player*>::iterator it = this->players.find( cfd );
if( it == this->players.end() ) return;
CompanionEvent* ce = new CompanionEvent();
string disconnectedPlayerName = this->players[cfd]->getName();
if (!(this->players.empty())) {
for (map<int, Player*>::iterator itP = this->players.begin(); itP != this->players.end(); ++itP) {
if ((itP->first) != cfd) {
sendData(itP->first, ce->quit(disconnectedPlayerName));
}
}
}
delete ce;
}
void Server::checkAliveSend( int cfd ) {
char buf[1] = { '1' };
while( true ) {
if( !( this->connected ) ) return;
// 4s timed send
usleep(4000000);
send( cfd, &buf, 1, 0 );
}
}
void Server::processQueue() {
bool msgIsValid;
Evento* respuesta = new Evento;
mutex theMutex;
while (this->processing) {
if (!(this->eventQueue->empty())) {
theMutex.lock();
//cout << "Saco Msj de la cola" << endl;
map<int, Evento*>* data = this->eventQueue->front();
this->eventQueue->pop();
map<int, Evento*>::iterator it = data->begin();
cout << "FD cliente: " << it->first << " -- Mensaje: "
<< (it->second)->value << endl;
this->logger->info("Msj de cliente: " + to_string(it->second->value));
// msgIsValid = this->processMsg( string((it->second)->tipo), string(((it->second)->valor)) );
// if( msgIsValid ) {
respuesta->value = MENSAJE_CORRECTO;
this->logger->info(to_string(respuesta->value));
// } else {
// respuesta->value = MENSAJE_INCORRECTO;
// this->logger->warn( respuesta->value );
// }
//thread tSending( &Server::sendData, this, it->first, respuesta , sizeof(Evento) );
//tSending.detach();
if (!(this->players.empty())) {
for (map<int, Player*>::iterator itP = this->players.begin();
itP != this->players.end(); ++itP) {
if ((itP->first) != it->first) {
sendData(itP->first, it->second);
}
}
}
delete data;
theMutex.unlock();
}
}
//cout<<"Corto processor"<<endl;
delete respuesta;
}
void Server::sendData( int cfd, Evento* data ) {
Transmitter* tmt = new Transmitter( cfd, this->logger );
tmt->sendData( data );
}
void Server::closeClient( int cfd ) {
mutex theMutex;
close( cfd );
theMutex.lock();
this->clientCount--;
// if no more players connected
if ( this->clientCount == 0 ) {
// clear players hash
this->removeAllPlayers();
delete this->gameData;
this->createGameData();
this->running = false;
// reset scores
this->alphaTeamScore = 0;
this->betaTeamScore = 0;
this->coopTeamScore = 0;
this->enemyID = 0;
}
cout << "Cantidad de clientes conectados: " << this->clientCount << endl;
this->logger->info( "Cantidad de Clientes Conectados: " + to_string( this->clientCount ) );
theMutex.unlock();
}
void Server::removeAllPlayers() {
for( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end();
++it ) {
delete it->second;
}
this->players.clear();
}
void Server::shutdown() {
if( this->connected )
this->closeConnection();
logger->warn( SERVER_CLOSE );
DEBUG_WARN( SERVER_CLOSE );
exit( 0 );
}
void Server::closeConnection() {
close( this->socketFD );
this->listening = false;
this->connected = false;
this->processing = false;
this->logger->warn( SERVER_DISCONNECT );
DEBUG_WARN( SERVER_DISCONNECT );
}
void Server::addScoreToPlayer( PlayerScore* data ) {
for ( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end();
++it ) {
Transmitter* tmt = new Transmitter( it->first, this->logger );
if ( it->second->getName() == string( data->name ) ) {
it->second->addScore( data->score );
tmt->sendData( data, "SA" );
}
if( it->second->isActive() ) {
// send team score
tmt->sendData( data, "TS" );
}
delete tmt;
}
if ( this->gameData->teamMode ) {
// alpha team
if ( data->team == 1 ) {
this->alphaTeamScore += data->score;
// beta team
} else {
this->betaTeamScore += data->score;
}
} else {
this->coopTeamScore += data->score;
}
}
void Server::sendScoreTable( int clientFD ) {
Transmitter* tmt = new Transmitter( clientFD, this->logger );
for ( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end();
++it ) {
Player* player = it->second;
// create player score data
PlayerScore* ps = new PlayerScore;
strcpy( ps->name, ( player->getName() ).c_str() );
strcpy( ps->color, ( player->getColor() ).c_str() );
ps->score = player->getScore();
ps->team = player->getTeam();
// send score data
tmt->sendData( ps );
delete ps;
}
if ( this->gameData->teamMode ) {
PlayerScore* as = new PlayerScore;
PlayerScore* bs = new PlayerScore;
strcpy( as->name, "alphaTotal" );
as->score = this->alphaTeamScore;
strcpy( bs->name, "betaTotal" );
bs->score = this->betaTeamScore;
tmt->sendData( as );
tmt->sendData( bs );
delete as;
delete bs;
} else {
PlayerScore* ts = new PlayerScore;
strcpy( ts->name, "total" );
ts->score = this->coopTeamScore;
tmt->sendData( ts );
delete ts;
}
delete tmt;
}
void Server::sendActivePlayers( int clientFD ) {
ActivePlayers* data = new ActivePlayers;
data->playerCount = this->players.size();
Transmitter* tmt = new Transmitter( clientFD, this->logger );
tmt->sendData( data );
delete tmt;
delete data;
}
void Server::sendStageReadySignal() {
for ( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end();
++it ) {
Transmitter* tmt = new Transmitter( it->first, this->logger );
tmt->sendDataID( "RR" );
delete tmt;
}
}
int Server::getActivePlayersCount() {
int playerCount = 0;
for ( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end();
++it ) {
Player* player = it->second;
// if player is connected
if ( player->isActive() ) {
playerCount++;
}
}
return playerCount;
}
void Server::sendGameData(int clientFD){
Transmitter* tmt = new Transmitter( clientFD, this->logger );
tmt->sendData( this->gameData );
delete tmt;
}
void Server::sendGameDataAll(){
for( map<int, Player*>::iterator it = this->players.begin(); it != this->players.end(); ++it ) {
this->sendGameData(it->first);
}
}
void Server::createGameData(){
this->gameData = new GameData();
this->gameData->cooperativeMode = false;
this->gameData->countPlayersTeam1 = 0;
this->gameData->countPlayersTeam2 = 0;
this->gameData->practiceMode = false;
this->gameData->teamMode = false;
this->gameData->maxPlayersTeams = this->config->jugadoresPorEquipo;
}
void Server::sendPlayersReady(){
bool playerReady = true;
mutex theMutex;
theMutex.lock();
for( map<int, Player*>::iterator it = this->players.begin(); it != this->players.end(); ++it ) {
// if game is running and player is inactive, skip
if( this->running && !( it->second->isActive() ) ) continue;
// if already a player with that color
if( !it->second->isReady()){
playerReady = false;
// cout<<"player no ready"<<it->second->getName()<<endl;
}
}
theMutex.unlock();
if ( playerReady ){
// thread tCreateEnemys( &Server::createEnemys, this);
// tCreateEnemys.detach();
//
// thread tCreatePU( &Server::createPowerUps, this);
// tCreatePU.detach();
this->createEnemys();
this->createPowerUps();
thread tMoveEnemy( &Server::makeEnemyMove, this);
tMoveEnemy.detach();
cout<<"Iniciando la Partida"<<endl;
cout<<"Equipos Configurados "<<endl;
// send other players data
for (map<int, Player*>::iterator it = this->players.begin();
it != this->players.end(); ++it) {
cout <<"Jugador: "<<it->second->getName()<<" - Equipo: "<<it->second->getTeam()<<endl;
Transmitter* tmt = new Transmitter(it->first, this->logger);
tmt->sendDataID("OK");
delete tmt;
}
}
}
void Server::createEnemys() {
this->enemyID = 0;
this->enemys.clear();
vector<EnemigoConf*> enemigosConf = this->config->enemigos;
for (int i = 0; i < enemigosConf.size(); i++) {
EnemigoConf* enemigoConf = enemigosConf[i];
this->createEnemy(*enemigoConf->tipo, enemigoConf->x, enemigoConf->y, enemigoConf->apareceEn);
}
}
void Server::createPowerUps() {
this->powerUpID = 0;
vector<PowerUpConf*> powerUpsConf = this->config->powerUps;
for ( vector<PowerUpConf*>::iterator it = powerUpsConf.begin();
it != powerUpsConf.end();
++it ) {
PowerUpConf* puc = *it;
this->createPowerUp( *puc->tipo, puc->x, puc->y, puc->apareceEn );
}
}
void Server::createPowerUp( char type, int x, int y, int offset ) {
this->powerUpID++;
this->powerUps[ powerUpID ] = new ServerPowerUp( type, new Posicion( x, y ) );
this->powerUps[ powerUpID ]->setApareceEn(offset);
PowerUpData* data = new PowerUpData;
data->id = this->powerUpID;
data->type = type;
data->x = x;
data->y = y;
data->offset = offset;
data->status = 'C';
this->sendPowerUpCreation( data );
}
void Server::sendPowerUpCreation( PowerUpData* data ) {
for ( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end();
++it ) {
if ( it->second->isActive() ) {
Transmitter* tmt = new Transmitter( it->first, this->logger );
tmt->sendData( data );
delete tmt;
}
}
delete data;
}
void Server::createEnemy( char type, int x, int y, int offset ) {
this->enemyID++;
ServerAvionEnemigo* enemy = NULL;
if (type == 'g'){
enemy = new ServerAvionEnemyGrande( this->enemyID, new Posicion(x, y));
enemy->setApareceEn(offset);
this->enemys[ enemyID ] = enemy;
this->preparingAndSendingEnemyCreation(type, x, y, offset);
} else if (type == 'f'){
this->createFlota(type, x, y, offset);
} else if ( type == 'r' ) {
enemy = new ServerAvionEnemigoRandom( this->enemyID, new Posicion(x, y));
enemy->setApareceEn(offset);
this->enemys[ enemyID ] = enemy;
this->preparingAndSendingEnemyCreation(type, x, y, offset);
} else if ( type == 'm' ) {
enemy = new ServerAvionEnemigoMedio( this->enemyID, new Posicion(x, y));
enemy->setApareceEn(offset);
this->enemys[ enemyID ] = enemy;
this->preparingAndSendingEnemyCreation(type, x, y, offset);
}
}
void Server::resumeClientEnemys() {
for ( map<int, ServerAvionEnemigo*>::iterator it = enemys.begin();it != enemys.end(); ++it) {
EnemyStatus* data = new EnemyStatus;
data->id = it->first;
data->type = it->second->getType();
data->x = it->second->getX();
data->y = it->second->getY();
data->offset = it->second->getApareceEn();
data->status = 'C';
strcpy( data->playerID, ( this->shootPlayerID() ).c_str() );
this->sendEnemyCreation( data );
}
}
void Server::resumeClientPowerUp() {
for ( map<int, ServerPowerUp*>::iterator it = powerUps.begin();it != powerUps.end(); ++it) {
PowerUpData* data = new PowerUpData;
data->id = it->first;
data->type = it->second->getType();
data->x = it->second->getX();
data->y = it->second->getY();
data->offset = it->second->getApareceEn();
data->status = 'C';
this->sendPowerUpCreation( data );
}
}
void Server::preparingAndSendingEnemyCreation(char type, int x, int y, int offset) {
EnemyStatus* data = new EnemyStatus;
data->id = this->enemyID;
data->type = type;
data->x = x;
data->y = y;
data->offset = offset;
data->status = 'C';
strcpy( data->playerID, ( this->shootPlayerID() ).c_str() );
this->sendEnemyCreation( data );
}
void Server::createFlota(char type, int x, int y, int offset) {
FlotaObserver* fo = new FlotaObserver();
this->flotas[ numeroDeFlota ] = fo;
for (int ordenAparicionFlota = 0 ; ordenAparicionFlota < 5 ; ordenAparicionFlota++ ){
ServerAvionEnemigo* enemy = new ServerAvionEnemigoFlota( this->enemyID, new Posicion(x, y), ordenAparicionFlota, this->numeroDeFlota);
((ServerAvionEnemigoFlota*)enemy)->addObserver(fo);
enemy->setApareceEn(offset);
this->enemys[ enemyID ] = enemy;
this->preparingAndSendingEnemyCreation(type, x, y, offset);
this->enemyID++;
}
this->numeroDeFlota++;
}
void Server::sendEnemyCreation( EnemyStatus* data ) {
for ( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end();
++it ) {
if ( it->second->isActive() ) {
Transmitter* tmt = new Transmitter( it->first, this->logger );
tmt->sendData( data );
delete tmt;
}
}
delete data;
}
void Server::makeEnemyMove() {
mutex m;
EnemyData* data;
map<int, ServerAvionEnemigo*>::iterator it;
while (this->running) {
usleep( 1000000 );
m.lock();
for ( it = this->enemys.begin(); it != this->enemys.end(); ++it ) {
// send movements if enemy is active
if ( it->second->isActive() ) {
data = it->second->vivir();
if ( data->direction != 'Z' ) {
// set player to shoot
strcpy( data->playerID, ( this->shootPlayerID() ).c_str() );
this->sendEnemyData( data );
}
}
}
m.unlock();
}
}
void Server::sendEnemyData( EnemyData* data ) {
for ( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end();
++it ) {
if ( it->second->isActive() ) {
Transmitter* tmt = new Transmitter( it->first, this->logger );
tmt->sendData( data );
delete tmt;
}
}
delete data;
}
void Server::setTeamPlayer(int team, int cliendFd){
for( map<int, Player*>::iterator it = this->players.begin(); it != this->players.end(); ++it ) {
if (it->first == cliendFd){
// cout <<"Set team: "<<team<<endl;
it->second->setTeam(team);
}
}
}
void Server::freePlayerSlot( int clientFD ) {
string playerName;
map<int, Player*>::iterator it = this->players.find( clientFD );
// if player exists
if ( it != this->players.end() ) {
playerName = this->players[ clientFD ]->getName();
// delete player
delete this->players[ clientFD ];
// free player slot in hash
this->players.erase( it );
}
// if game is running
if ( this->running ) {
Evento* ev = new Evento;
ev->value = QUITGAME;
strcpy( ev->name, playerName.c_str() );
for ( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end();
++it ) {
Transmitter* tmt = new Transmitter( it->first, this->logger );
tmt->sendData( ev );
delete tmt;
}
delete ev;
// if playing on team mode, check if remaining players win
if ( this->gameData->teamMode ) {
this->checkTeamWin();
}
}
}
void Server::checkTeamWin() {
int teamAlpha = 0, teamBeta = 0;
for ( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end();
++it ) {
Player* player = it->second;
// if player is alive, check player team
if ( player->isAlive() ) {
if ( player->getTeam() == 1 ) {
teamAlpha++;
} else if ( player->getTeam() == 2 ) {
teamBeta++;
}
}
}
if ( teamAlpha == 0 ) {
this->sendTeamWin( "BW" );
} else if ( teamBeta == 0 ) {
this->sendTeamWin( "AW" );
}
}
void Server::checkCoopLose() {
int alivePlayersCount = 0;
for ( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end();
++it ) {
Player* player = it->second;
// check if player is alive
if ( player->isAlive() ) {
alivePlayersCount++;
}
}
if ( alivePlayersCount == 0 ) {
this->sendCoopLose();
}
}
void Server::sendCoopLose() {
for ( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end();
++it ) {
Transmitter* tmt = new Transmitter( it->first, this->logger );
tmt->sendDataID( "CL" );
delete tmt;
}
}
void Server::sendTeamWin( string winningTeam ) {
for ( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end();
++it ) {
Transmitter* tmt = new Transmitter( it->first, this->logger );
tmt->sendDataID( winningTeam.c_str() );
delete tmt;
}
}
string Server::shootPlayerID() {
if ( this->players.size() == 0 ) return "NA";
if ( this->players.size() == 1 ) {
return ( this->players.begin() )->second->getName();
} else {
map<int, Player*> p;
for (map<int, Player*>::iterator it = this->players.begin(); it != this->players.end(); ++it) {
if (it->second->isAlive()) {
p[it->first] = it->second;
}
}
srand( time( NULL ) );
int offset = rand() % ( p.size() );
map<int, Player*>::iterator it = p.begin();
for ( int i = 0; i < offset; i++ ) {
++it;
}
return it->second->getName();
}
}
void Server::removeEnemy( int id ) {
delete this->enemys[ id ];
this->enemys.erase( this->enemys.find( id ) );
}
void Server::sendEnemyDeath( int id, int clientFD ) {
EnemyStatus* data = new EnemyStatus;
data->id = id;
data->status = 'D';
for ( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end();
++it ) {
Transmitter* tmt = new Transmitter( it->first, this->logger );
tmt->sendData( data );
delete tmt;
}
delete data;
}
void Server::sendEnemyUpdate( EnemyStatus* data, int clientFD ) {
for ( map<int, Player*>::iterator it = this->players.begin();
it != this->players.end();
++it ) {
Transmitter* tmt = new Transmitter( it->first, this->logger );
tmt->sendData( data );
delete tmt;
}
}
void Server::activatePowerUp( PowerUpData* data, int clientFD ) {
if ( this->powerUps.find( data->id ) == this->powerUps.end() ) return;
switch ( this->powerUps[ data->id ]->getType() ) {
case 's':
break;
case 'b':{
PlayerScore* ps = new PlayerScore;
strcpy( ps->name, ( this->players[ clientFD ]->getName() ).c_str() );
ps->team = this->players[ clientFD ]->getTeam();
ps->score = 250;
this->addScoreToPlayer( ps );
delete ps;
break;
}
case 'w':
break;
case 'd':
break;
}
delete this->powerUps[ data->id ];
this->powerUps.erase( this->powerUps.find( data->id ) );
}
| 30.323273 | 141 | 0.603114 | mscoccimarro |
233c9c480f700fba9c3e66d0f880bfca1f8354b5 | 265 | hpp | C++ | source/parlex/include/parlex/detail/permutation.hpp | dlin172/Plange | 4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04 | [
"BSD-3-Clause"
] | null | null | null | source/parlex/include/parlex/detail/permutation.hpp | dlin172/Plange | 4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04 | [
"BSD-3-Clause"
] | null | null | null | source/parlex/include/parlex/detail/permutation.hpp | dlin172/Plange | 4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04 | [
"BSD-3-Clause"
] | null | null | null | #ifndef PERMUTATION_HPP
#define PERMUTATION_HPP
#include <vector>
#include "parlex/detail/match.hpp"
#include "transition.hpp"
namespace parlex {
namespace detail {
typedef std::vector<transition> permutation;
}
} // namespace parlex
#endif //PERMUTATION_HPP
| 14.722222 | 44 | 0.769811 | dlin172 |
23400a64e6fd4e51c1b5d9a6718cedc9a604f465 | 3,160 | cpp | C++ | patched/WKString.cpp | paulwratt/phantomjs-2.1.1-multi | 9a2b739a0636af919ebdf25ddd7018a8558301d1 | [
"BSD-3-Clause"
] | null | null | null | patched/WKString.cpp | paulwratt/phantomjs-2.1.1-multi | 9a2b739a0636af919ebdf25ddd7018a8558301d1 | [
"BSD-3-Clause"
] | null | null | null | patched/WKString.cpp | paulwratt/phantomjs-2.1.1-multi | 9a2b739a0636af919ebdf25ddd7018a8558301d1 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WKString.h"
#include "WKStringPrivate.h"
#include "WKAPICast.h"
using namespace WebKit;
WKTypeID WKStringGetTypeID()
{
return toAPI(WebString::APIType);
}
WKStringRef WKStringCreateWithUTF8CString(const char* string)
{
RefPtr<WebString> webString = WebString::createFromUTF8String(string);
return toAPI(webString.release().leakRef());
}
bool WKStringIsEmpty(WKStringRef stringRef)
{
return toImpl(stringRef)->isEmpty();
}
size_t WKStringGetLength(WKStringRef stringRef)
{
return toImpl(stringRef)->length();
}
size_t WKStringGetCharacters(WKStringRef stringRef, WKChar* buffer, size_t bufferLength)
{
COMPILE_ASSERT(sizeof(WKChar) == sizeof(UChar), WKStringGetCharacters_sizeof_WKChar_matches_UChar);
return (toImpl(stringRef)->getCharacters(reinterpret_cast<UChar*>(buffer), bufferLength));
}
size_t WKStringGetMaximumUTF8CStringSize(WKStringRef stringRef)
{
return toImpl(stringRef)->maximumUTF8CStringSize();
}
size_t WKStringGetUTF8CString(WKStringRef stringRef, char* buffer, size_t bufferSize)
{
return toImpl(stringRef)->getUTF8CString(buffer, bufferSize);
}
bool WKStringIsEqual(WKStringRef aRef, WKStringRef bRef)
{
return toImpl(aRef)->equal(toImpl(bRef));
}
bool WKStringIsEqualToUTF8CString(WKStringRef aRef, const char* b)
{
return toImpl(aRef)->equalToUTF8String(b);
}
bool WKStringIsEqualToUTF8CStringIgnoringCase(WKStringRef aRef, const char* b)
{
return toImpl(aRef)->equalToUTF8StringIgnoringCase(b);
}
WKStringRef WKStringCreateWithJSString(JSStringRef jsStringRef)
{
RefPtr<WebString> webString = WebString::create(jsStringRef);
return toAPI(webString.release().leakRef());
}
JSStringRef WKStringCopyJSString(WKStringRef stringRef)
{
return toImpl(stringRef)->createJSString();
}
| 32.916667 | 103 | 0.772468 | paulwratt |
2347b660a12c275135e6b678ba762254a56d4a7c | 1,532 | cpp | C++ | scugog_project/frontend_src/ErrorScreen.cpp | akinshonibare/Food-Fight-Game | cad246c5e29dab32c94d52ab97804575edd2233c | [
"MIT"
] | null | null | null | scugog_project/frontend_src/ErrorScreen.cpp | akinshonibare/Food-Fight-Game | cad246c5e29dab32c94d52ab97804575edd2233c | [
"MIT"
] | null | null | null | scugog_project/frontend_src/ErrorScreen.cpp | akinshonibare/Food-Fight-Game | cad246c5e29dab32c94d52ab97804575edd2233c | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "ErrorScreen.h"
void ErrorScreen::Show(sf::RenderWindow & renderWindow)
{
//sf::Image image;
sf::Texture texture;
if (texture.loadFromFile("../scugog_project/resources/images/error_screen.png") != true)
{
return;
}
sf::Font font;
if (!font.loadFromFile("../scugog_project/resources/fonts/BerlinSansFBDemiBold.ttf")) {
return;
}
sf::Vector2u windowSize = renderWindow.getSize();
sf::Text text;
text.setFont(font);
text.setString("The city is encroaching on your farm, stand your ground!");
text.setCharacterSize(60);
text.setFillColor(sf::Color::Black);
text.setStyle(sf::Text::Style::Italic);
sf::Rect<float> tsize = text.getGlobalBounds();
text.setPosition(sf::Vector2f(windowSize.x - tsize.width - 75, 100));
sf::Text text1;
text1.setFont(font);
text1.setString("You are missing files, redownload the game");
text1.setCharacterSize(60);
text1.setFillColor(sf::Color::White);
text1.setStyle(sf::Text::Style::Italic);
sf::Rect<float> tsize_text1 = text1.getGlobalBounds();
text1.setPosition(sf::Vector2f(windowSize.x - tsize_text1.width - 65, windowSize.y - tsize_text1.height - 75));
//texture.update(image);
sf::Sprite sprite(texture);
renderWindow.draw(sprite);
renderWindow.draw(text1);
renderWindow.draw(text);
renderWindow.display();
sf::Event event;
while (true)
{
while (renderWindow.pollEvent(event))
{
if (event.type == sf::Event::EventType::MouseButtonPressed
|| event.type == sf::Event::EventType::Closed)
{
return;
}
}
}
}
| 27.357143 | 112 | 0.713446 | akinshonibare |
2348a6637fe6137b7efaa8c1675f64716b18bdfa | 232 | cpp | C++ | AtCoder/abc143/a/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | AtCoder/abc143/a/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | 1 | 2021-10-19T08:47:23.000Z | 2022-03-07T05:23:56.000Z | AtCoder/abc143/a/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int A, B; cin >> A >> B;
int ans = A - B * 2;
if (ans < 0) printf("%d\n", 0);
else printf("%d\n", ans);
}
| 19.333333 | 35 | 0.556034 | H-Tatsuhiro |
054e59a6877fcaf9fd6a681fbf78cae7f400de73 | 416 | cpp | C++ | Lab2April/permutation.cpp | forkkr/Assembly-Lab | e038fb965e45a88aa670a1158bf99a4b62ac374f | [
"MIT"
] | null | null | null | Lab2April/permutation.cpp | forkkr/Assembly-Lab | e038fb965e45a88aa670a1158bf99a4b62ac374f | [
"MIT"
] | null | null | null | Lab2April/permutation.cpp | forkkr/Assembly-Lab | e038fb965e45a88aa670a1158bf99a4b62ac374f | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int ar[111];
int n;
int cnt = 0;
void perm(int pos)
{
if(pos > n)
{
for(int i = 1; i <= n; i++)
{
cout<<ar[i]<<" ";
}
cout<<endl;
cnt +=1;
}
for(int i = pos; i <= n; i++)
{
swap(ar[i], ar[pos]);
perm(pos+1);
swap(ar[i] , ar[pos]);
}
return;
}
int main()
{
cin>>n;
for(int i = 1; i <= n; i++)
{
ar[i] = i;
}
perm(1);
cout<<cnt<<endl;
}
| 11.243243 | 30 | 0.46875 | forkkr |
054f94db4c1f90c0803bf4520127701c70bbb744 | 2,336 | cpp | C++ | DataStructure/code/HW6/HW6_1.cpp | yuanyangwangTJ/algorithm | ab7a959a00f290a0adc9af278f9a5de60be22af1 | [
"MIT"
] | null | null | null | DataStructure/code/HW6/HW6_1.cpp | yuanyangwangTJ/algorithm | ab7a959a00f290a0adc9af278f9a5de60be22af1 | [
"MIT"
] | null | null | null | DataStructure/code/HW6/HW6_1.cpp | yuanyangwangTJ/algorithm | ab7a959a00f290a0adc9af278f9a5de60be22af1 | [
"MIT"
] | null | null | null | // 先序遍历线索二叉树
#include <iostream>
#define OVERFLOW -2
using namespace std;
typedef enum{Link, Thread} PointerTag;
// Link = 0:指针,指向孩子结点
// Thread = 1:线索,指向前驱或后继结点
typedef char TElemType;
typedef struct BiThrNode {
TElemType data;
struct BiThrNode *lchild, *rchild;
PointerTag LTag, RTag;
} BiThrNode, *BiThrTree;
//使用先序遍历创建二叉树
void BuildBiTree (BiThrTree &T) {
TElemType ch;
cin >> ch;
if (ch == '#') T = NULL;
else {
T = new(nothrow) BiThrNode;
if (!T) exit(OVERFLOW);
T->data = ch;
BuildBiTree (T->lchild);
BuildBiTree (T->rchild);
}
}// BuildBiTree
//先序线索化
void PreThreading (BiThrTree &P, BiThrTree &pre)
{
if (P) {
if (!P->lchild) {
P->LTag = Thread; P->lchild = pre;
} else {
P->LTag = Link;
}
if (!P->rchild) {
P->RTag = Thread;
} else {
P->RTag = Link;
}
if (pre && pre->rchild == NULL) {
pre->rchild = P;
}
pre = P;
if (P->LTag == Link) PreThreading(P->lchild, pre);
if (P->RTag == Link) PreThreading(P->rchild, pre);
}
}// PreThreading
//创建先序线索化二叉树
void CreatPreThread (BiThrTree &T)
{
BiThrTree pre = NULL;
if (T != NULL) {
PreThreading(T, pre);
pre->rchild = NULL;
pre->RTag = Thread;
}
}
//输出二叉树的树型图(逆时针旋转90度)
void PrintBiTree (BiThrTree T, int n) {
int i; char ch = ' ';
if (T) {
if (T->RTag == Link) PrintBiTree (T->rchild, n + 1);
for (i = 1; i <= n; i++) printf("%5c", ch);
cout << T->data << T->LTag << T->RTag << endl;
if (T->LTag == Link) PrintBiTree (T->lchild, n + 1);
}
}// PrintBiTree
void PrintElement (TElemType e) {
cout << e;
return;
}// PrintElement
//先序遍历二叉树
void PreOrderTraverse (BiThrTree T, void (*Visit)(TElemType)) {
if (T) {
Visit(T->data);
if (T->LTag == Link) PreOrderTraverse(T->lchild, Visit);
if (T->RTag == Link) PreOrderTraverse(T->rchild, Visit);
}
}// PreOrderTraverse
int main()
{
BiThrTree P;
BuildBiTree(P);
CreatPreThread(P);
PrintBiTree(P, 0);
PreOrderTraverse(P, PrintElement);
return 0;
} | 22.461538 | 65 | 0.514555 | yuanyangwangTJ |
055ab1789bbb499c12e4c23dc4e2c5f0b8a84a7e | 1,409 | cpp | C++ | system-test/schemarouter/mxs1849_table_sharding.cpp | sdrik/MaxScale | c6c318b36dde0a25f22ac3fd59c9d33d774fe37a | [
"BSD-3-Clause"
] | 1,157 | 2015-01-06T15:44:47.000Z | 2022-03-28T02:52:37.000Z | system-test/schemarouter/mxs1849_table_sharding.cpp | sdrik/MaxScale | c6c318b36dde0a25f22ac3fd59c9d33d774fe37a | [
"BSD-3-Clause"
] | 80 | 2015-02-13T11:49:05.000Z | 2022-01-17T09:00:11.000Z | system-test/schemarouter/mxs1849_table_sharding.cpp | sdrik/MaxScale | c6c318b36dde0a25f22ac3fd59c9d33d774fe37a | [
"BSD-3-Clause"
] | 361 | 2015-01-14T03:01:00.000Z | 2022-03-28T00:14:04.000Z | /**
* MXS-1849: Table family sharding router test
*
* https://jira.mariadb.org/browse/MXS-1849
*/
#include <iostream>
#include <maxtest/testconnections.hh>
int main(int argc, char* argv[])
{
TestConnections test(argc, argv);
test.reset_timeout();
test.repl->execute_query_all_nodes("STOP SLAVE");
test.repl->execute_query_all_nodes("DROP DATABASE IF EXISTS shard_db");
test.repl->execute_query_all_nodes("CREATE DATABASE shard_db");
MYSQL* conn;
for (int i = 0; i < test.repl->N; i++)
{
conn = open_conn_db(test.repl->port[i],
test.repl->ip4(i),
"shard_db",
test.repl->user_name(),
test.repl->password(),
test.maxscale_ssl);
execute_query(conn, "CREATE TABLE table%d (x1 int, fl int)", i);
mysql_close(conn);
}
conn = test.maxscale->open_rwsplit_connection();
// Check that queries are routed to the right shards
for (int i = 0; i < test.repl->N; i++)
{
test.add_result(execute_query(conn, "SELECT * FROM shard_db.table%d", i), "Query should succeed.");
}
mysql_close(conn);
// Cleanup
test.repl->execute_query_all_nodes("DROP DATABASE IF EXISTS shard_db");
test.repl->execute_query_all_nodes("START SLAVE");
sleep(1);
return test.global_result;
}
| 31.311111 | 107 | 0.597587 | sdrik |
0561370ec0ad11fa6e714182395c898c45336dd0 | 557 | cpp | C++ | solutions/1541.minimum-insertions-to-balance-a-parentheses-string.378711414.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 78 | 2020-10-22T11:31:53.000Z | 2022-02-22T13:27:49.000Z | solutions/1541.minimum-insertions-to-balance-a-parentheses-string.378711414.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | null | null | null | solutions/1541.minimum-insertions-to-balance-a-parentheses-string.378711414.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 26 | 2020-10-23T15:10:44.000Z | 2021-11-07T16:13:50.000Z | class Solution {
public:
int minInsertions(string s) {
int ans = 0;
int count = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(')
count++;
else {
if (i + 1 < s.size() && s[i + 1] == ')') {
i++;
if (count > 0) {
count--;
} else {
ans++;
}
} else {
if (count > 0) {
count--;
ans++;
} else {
ans += 2;
}
}
}
}
ans += count * 2;
return ans;
}
};
| 17.967742 | 50 | 0.29623 | satu0king |
056ea8d1617f1d6d505623edaa68c922fc291e33 | 128 | cpp | C++ | Core/DataModel/Entities/Commitment.cpp | ITBear/SolanaCPP | 9c98d72564a3fa174ba2c6dd59217676069b4997 | [
"Apache-2.0"
] | 6 | 2021-06-13T19:21:22.000Z | 2022-03-26T14:31:22.000Z | Core/DataModel/Entities/Commitment.cpp | ITBear/SolanaCPP | 9c98d72564a3fa174ba2c6dd59217676069b4997 | [
"Apache-2.0"
] | 5 | 2021-07-15T10:33:08.000Z | 2021-07-15T11:55:13.000Z | Core/DataModel/Entities/Commitment.cpp | ITBear/SolanaCPP | 9c98d72564a3fa174ba2c6dd59217676069b4997 | [
"Apache-2.0"
] | 2 | 2021-07-09T20:05:53.000Z | 2022-03-22T01:00:08.000Z | #include "Commitment.hpp"
namespace Sol::Core::DataModel {
GP_ENUM_IMPL(Commitment)
}//namespace Sol::Core::DataModel
| 16 | 34 | 0.71875 | ITBear |
056fa6044fa00dc1ae673db57d48c49b31c9f752 | 1,863 | hpp | C++ | include/argot/concepts/trivially_destructible.hpp | mattcalabrese/argot | 97349baaf27659c9dc4d67cf8963b2e871eaedae | [
"BSL-1.0"
] | 49 | 2018-05-09T23:17:45.000Z | 2021-07-21T10:05:19.000Z | include/argot/concepts/trivially_destructible.hpp | mattcalabrese/argot | 97349baaf27659c9dc4d67cf8963b2e871eaedae | [
"BSL-1.0"
] | null | null | null | include/argot/concepts/trivially_destructible.hpp | mattcalabrese/argot | 97349baaf27659c9dc4d67cf8963b2e871eaedae | [
"BSL-1.0"
] | 2 | 2019-08-04T03:51:36.000Z | 2020-12-28T06:53:29.000Z | /*==============================================================================
Copyright (c) 2018, 2019 Matt Calabrese
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef ARGOT_CONCEPTS_TRIVIALLY_DESTRUCTIBLE_HPP_
#define ARGOT_CONCEPTS_TRIVIALLY_DESTRUCTIBLE_HPP_
//[description
/*`
TriviallyDestructible is an [argot_gen_concept] that is satisfied by Object
types that have a trivial destructor.
*/
//]
#include <argot/concepts/detail/concepts_preprocessing_helpers.hpp>
#include <argot/concepts/nothrow_destructible.hpp>
#include <argot/gen/explicit_concept.hpp>
#ifndef ARGOT_GENERATE_PREPROCESSED_CONCEPTS
#include <argot/detail/detection.hpp>
#include <argot/gen/make_concept_map.hpp>
#include <type_traits>
#endif // ARGOT_GENERATE_PREPROCESSED_CONCEPTS
namespace argot {
#define ARGOT_DETAIL_PREPROCESSED_CONCEPT_HEADER_NAME() \
s/trivially_destructible.h
#ifdef ARGOT_CONCEPTS_DETAIL_SHOULD_INCLUDE_PREPROCESSED_HEADER
#include ARGOT_CONCEPTS_DETAIL_PREPROCESSED_HEADER
#else
#include <argot/concepts/detail/preprocess_header_begin.hpp>
ARGOT_CONCEPTS_DETAIL_CREATE_LINE_DIRECTIVE( __LINE__ )
template< class T >
ARGOT_EXPLICIT_CONCEPT( TriviallyDestructible )
(
NothrowDestructible< T >
);
#include <argot/concepts/detail/preprocess_header_end.hpp>
#endif // ARGOT_CONCEPTS_DETAIL_SHOULD_INCLUDE_PREPROCESSED_HEADER
template< class T >
struct make_concept_map
< TriviallyDestructible< T >
, typename call_detail::detached_fast_enable_if
< std::is_trivially_destructible_v< T > >::_::template and_
< std::is_object_v< T > >::void_
> {};
} // namespace argot
#endif // ARGOT_CONCEPTS_TRIVIALLY_DESTRUCTIBLE_HPP_
| 28.661538 | 80 | 0.73591 | mattcalabrese |
0572610cdee5ad65c071c75f908cfa1c54486e4f | 1,362 | cpp | C++ | Fibonacci/Fibonacci.cpp | UtkarshMish/Data-Structures | 15425704d7a0f1a665e39bd9ca2e9f370b8a835b | [
"Unlicense"
] | null | null | null | Fibonacci/Fibonacci.cpp | UtkarshMish/Data-Structures | 15425704d7a0f1a665e39bd9ca2e9f370b8a835b | [
"Unlicense"
] | null | null | null | Fibonacci/Fibonacci.cpp | UtkarshMish/Data-Structures | 15425704d7a0f1a665e39bd9ca2e9f370b8a835b | [
"Unlicense"
] | null | null | null | #include "iostream"
using namespace std;
// Using loops :: ==>>>
// void fibonacci(int &n)
// {
// double firstElement = 0, secondElement = 1, newElement;
// if (n > 250)
// {
// cout << "Too long to Compute !!";
// return;
// }
// for (int index = 0; index < n; index++)
// {
// if (index == 0)
// {
// cout << firstElement << " ";
// }
// else if (index == 1)
// {
// cout << secondElement << " ";
// }
// else
// {
// newElement = firstElement + secondElement;
// cout << newElement << " ";
// firstElement = secondElement;
// secondElement = newElement;
// }
// }
// }
int fibonacci(int n, int values[])
{
if (n <= 1)
{
values[n] = n;
return n;
}
else
{
if (values[n - 2] == -1)
{
values[n - 2] = fibonacci(n - 2, values);
}
if (values[n - 1] == -1)
{
values[n - 1] = fibonacci(n - 1, values);
}
values[n] = values[n - 2] + values[n - 1];
return values[n];
}
}
int main()
{
int n;
cout << "Enter the N for Fibonacci ==>";
cin >> n;
cout << endl;
int *values;
values= new int[n];
for (int i = 0; i < n; i++)
{
values[i] = -1;
}
int result = fibonacci(n, values);
cout << result << endl;
for (int i = 0; i < n; i++)
{
cout << values[i] << " ";
}
return 0;
} | 18.405405 | 60 | 0.45815 | UtkarshMish |
05799ac29a43effeda0899e398015a5e1dbc5ba6 | 2,239 | hpp | C++ | LOGGER_sample/setup.hpp | hirakuni45/RX | 3fb91bfc8d5282cde7aa00b8bd37f4aad32582d0 | [
"BSD-3-Clause"
] | 56 | 2015-06-04T14:15:38.000Z | 2022-03-01T22:58:49.000Z | LOGGER_sample/setup.hpp | hirakuni45/RX | 3fb91bfc8d5282cde7aa00b8bd37f4aad32582d0 | [
"BSD-3-Clause"
] | 30 | 2019-07-27T11:03:14.000Z | 2021-12-14T09:59:57.000Z | LOGGER_sample/setup.hpp | hirakuni45/RX | 3fb91bfc8d5282cde7aa00b8bd37f4aad32582d0 | [
"BSD-3-Clause"
] | 15 | 2017-06-24T11:33:39.000Z | 2021-12-07T07:26:58.000Z | #pragma once
//=====================================================================//
/*! @file
@brief セットアップ
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/scene.hpp"
#include "common/format.hpp"
#include "scenes_base.hpp"
namespace app {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief セットアップ・クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
class setup : public utils::scene {
typedef scenes_base::RENDER RENDER;
typedef graphics::def_color DEF_COLOR;
gui::button button_;
gui::check lap_button_check_;
public:
//-------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-------------------------------------------------------------//
setup() noexcept :
button_(vtx::srect( 30, 20, 80, 30), "Exit"),
lap_button_check_(vtx::srect( 30, 70 + 40*0, 0, 0), "LAP Button")
{
}
//-------------------------------------------------------------//
/*!
@brief 初期化
*/
//-------------------------------------------------------------//
void init() noexcept override
{
at_scenes_base().at_render().clear(DEF_COLOR::Black);
button_.enable();
button_.at_select_func() = [this](uint32_t id) {
change_scene(scene_id::root_menu);
};
lap_button_check_.enable();
// check_.at_select_func() = [this](bool ena) {
// utils::format("Check: %d\n") % static_cast<int>(ena);
// };
}
//-------------------------------------------------------------//
/*!
@brief サービス
*/
//-------------------------------------------------------------//
void service() noexcept override
{
}
//-------------------------------------------------------------//
/*!
@brief シーンの終了
*/
//-------------------------------------------------------------//
void exit() noexcept override
{
button_.enable(false);
lap_button_check_.enable(false);
}
};
}
| 26.341176 | 74 | 0.374721 | hirakuni45 |
0579ff4821695788e20f5e3d82305342250fb214 | 2,695 | cc | C++ | sw/src/connection_manager.cc | varungohil/Dagger | b063e19a3a89a944caefb2bcbcb89b3bfaad466e | [
"MIT"
] | 1 | 2022-03-31T22:29:52.000Z | 2022-03-31T22:29:52.000Z | sw/src/connection_manager.cc | varungohil/Dagger | b063e19a3a89a944caefb2bcbcb89b3bfaad466e | [
"MIT"
] | null | null | null | sw/src/connection_manager.cc | varungohil/Dagger | b063e19a3a89a944caefb2bcbcb89b3bfaad466e | [
"MIT"
] | null | null | null | #include "connection_manager.h"
#include <algorithm>
#include <cassert>
#include <iostream>
#include<tuple>
#include "logger.h"
namespace dagger {
ConnectionManager::ConnectionManager() : max_connections_(0) {}
ConnectionManager::ConnectionManager(size_t max_connections)
: max_connections_(max_connections) {
for (size_t i = 0; i < max_connections; ++i) {
c_id_pool_.push_back(i);
}
}
int ConnectionManager::open_connection(ConnectionId& c_id,
const IPv4& dest_addr,
ConnectionFlowId flow_id, uint16_t remote_qp_num, uint16_t p_key, uint32_t q_key) {
if (open_connections_.size() == max_connections_) {
FRPC_ERROR(
"Failed to open connection, max number of open connections is "
"reached\n");
return 1;
}
assert(c_id_pool_.size() != 0);
c_id = c_id_pool_.front();
c_id_pool_.pop_front();
assert(open_connections_.find(c_id) == open_connections_.end());
open_connections_.insert(
std::make_pair(c_id, std::make_tuple(dest_addr, flow_id, remote_qp_num, p_key, q_key)));
return 0;
}
int ConnectionManager::add_connection(ConnectionId c_id, const IPv4& dest_addr,
ConnectionFlowId flow_id, uint16_t remote_qp_num, uint16_t p_key, uint32_t q_key ) {
if (open_connections_.size() == max_connections_) {
FRPC_ERROR(
"Failed to add connection, max number of open connections is "
"reached\n");
return 1;
}
assert(c_id_pool_.size() != 0);
auto it = std::find(c_id_pool_.begin(), c_id_pool_.end(), c_id);
if (it == c_id_pool_.end()) {
FRPC_ERROR("Failed to add connection, such connection already exists\n");
return 1;
}
c_id_pool_.erase(it);
assert(open_connections_.find(c_id) == open_connections_.end());
open_connections_.insert(
std::make_pair(c_id, std::make_tuple(dest_addr, flow_id, remote_qp_num, p_key, q_key)));
return 0;
}
int ConnectionManager::close_connection(ConnectionId c_id) {
auto it = open_connections_.find(c_id);
if (it == open_connections_.end()) {
FRPC_ERROR("Failed to close connection, the connection is not open\n");
return 1;
}
open_connections_.erase(it);
c_id_pool_.push_back(c_id);
return 0;
}
void ConnectionManager::dump_open_connections() const {
std::cout << "*** Open connections ***" << std::endl;
std::cout << "<connection_id, dest_ip, dest_port, flow_id>" << std::endl;
for (auto c : open_connections_) {
std::cout << c.first << std::get<0>(c.second).get_addr()
<< std::get<0>(c.second).get_port() << std::get<1>(c.second) << std::endl;
}
}
} // namespace dagger
| 28.978495 | 122 | 0.664935 | varungohil |
057bea574378d4318fa0bb9faca67d09d21df0d2 | 20,602 | cpp | C++ | workers/unreal/Source/Engineers/Commandlets/ExportSnapshotCommandlet.cpp | spatialos/ue4-demo-dusk | f07f03cde0bd66a8478e34390512fcfd3c5cb2e7 | [
"MIT"
] | 51 | 2017-03-29T18:20:43.000Z | 2021-04-19T06:05:03.000Z | workers/unreal/Source/Engineers/Commandlets/ExportSnapshotCommandlet.cpp | spatialos/DuskPreview | f07f03cde0bd66a8478e34390512fcfd3c5cb2e7 | [
"MIT"
] | null | null | null | workers/unreal/Source/Engineers/Commandlets/ExportSnapshotCommandlet.cpp | spatialos/DuskPreview | f07f03cde0bd66a8478e34390512fcfd3c5cb2e7 | [
"MIT"
] | 29 | 2017-05-12T08:57:49.000Z | 2021-08-06T08:55:53.000Z | // Fill out your copyright notice in the Description page of Project Settings.
#include "Engineers.h"
#include "ExportSnapshotCommandlet.h"
#include "ConversionsFunctionLibrary.h"
#include "improbable/collections.h"
#include "improbable/math/coordinates.h"
#include "improbable/math/vector3d.h"
#include "improbable/math/vector3f.h"
#include <improbable/worker.h>
#include "improbable/standard_library.h"
#include "improbable/transform/transformInfo.h"
#include "improbable/character/character_controller.h"
#include "improbable/character/character_movement_info.h"
#include "improbable/health/health.h"
#include "improbable/level/day_night_cycle.h"
#include "improbable/animation/animationinfo.h"
#include "improbable/forcefield/forcefieldinfo.h"
#include "../SpatialEntities/EntityFactory.h"
using namespace improbable;
using namespace improbable::math;
using namespace improbable::transform;
using namespace improbable::character;
using namespace improbable::level;
using namespace improbable::health;
using namespace improbable::animation;
using namespace improbable::spawner;
using namespace improbable::forcefield;
namespace {
// Snapshot entity ID start values
const int SPAWNER_ID = 200;
const int MANTIS_SPAWNER_ID = 300;
const int DAY_NIGHT_CYCLE_ID = 600;
const int PIG_ID = 700;
const int MANTIS_ID_START = 800;
const int ROCK_ID_START = 900;
const int GENERATOR_ID_START = 1000;
const int HQBASE_ID_START = 1100;
const int BATTERY_ID_START = 1200;
// quantity defines
const int SPHERICAL_NR_MANTIS_ENTITIES_TO_STORE = 3;
const TArray<FVector> MANTIS_START_SPAWNPOINTS = {
{-21868.0f, -10473.0f, 33600.0f}
,{-19187.0f, -4148.0f, 32955.0f}
,{ -20220.0f, 4343.0f, 34454.0f}
,{ -8368.0f, 4343.0f, 34454.0f }
,{ 2168.0f, 4343.0f, 31730.0f }
,{ 11932.0f, 7281.0f, 34166.0f }
,{ 9137.0f, -9519.0f, 32258.0f }
,{ 154.0f, -30167.0f, 33885.0f }
,{ -6747.0f, -32372.0f, 33712.0f }
,{ -16101.0f, -32927.0f, 35637.0f }
};
const int NR_MANTIS_PER_SPAWNPOINT = 1;
const int NR_ROCKS_TO_SPAWN = 30;
const float ROCK_SPAWN_AREA_RADIUS = 10000.0;
const TArray<std::string> ROCK_ASSET_NAMES = {
"RawResource_Irridium",
"RawResource_Metal"
};
improbable::transform::Quaternion IdentityQuaternion{ 1.0f, 0.0f, 0.0f, 0.0f };
} // ::
// #define SPAWN_MANTIS_SPHERICAL 1
UExportSnapshotCommandlet::UExportSnapshotCommandlet()
{
}
UExportSnapshotCommandlet::~UExportSnapshotCommandlet()
{
}
int32 UExportSnapshotCommandlet::Main(const FString& Params)
{
FString combinedPath = FPaths::Combine(*FPaths::GetPath(FPaths::GetProjectFilePath()), TEXT("../../snapshots"));
TArray<FString> Args;
Params.ParseIntoArrayWS(Args);
// FVector Vec(FCString::Atof(*Args[1]), FCString::Atof(*Args[2]), FCString::Atof(*Args[3]));
float startTimeInSeconds = FCString::Atof(*Args[1]);
FString snapshotName = Args[2];
UE_LOG(LogTemp, Display, TEXT("Combined path %s"), *combinedPath);
if (FPaths::CollapseRelativeDirectories(combinedPath))
{
FString fullPath = FPaths::Combine(*combinedPath, snapshotName);
std::unordered_map<worker::EntityId, worker::SnapshotEntity> entityMap;
// -- Add Spawner
entityMap.emplace(SPAWNER_ID, CreateSpawnerSnapshotEntity());
entityMap.emplace(MANTIS_SPAWNER_ID, CreateMantisSpawnerSnapshotEntity());
// -- Add Mantis NPCs
#ifdef SPAWN_MANTIS_SPHERICAL
FVector sphericalBaseLocation(-3960, -13880, 31670);
CreateMantisNPCEntitiesSpherical(entityMap, sphericalBaseLocation);
#else
CreateMantisNPCSpawnPoints(entityMap);
#endif
FVector RockSpawnBaseLocation(-3960, -13880, 31670);
CreateRockSpawnPoints(entityMap, RockSpawnBaseLocation);
// -- Add Day Night Cycle
UE_LOG(LogTemp, Display, TEXT("Adding DayAndNightCycle Entity to Snapshot..."));
entityMap.emplace(DAY_NIGHT_CYCLE_ID, CreateDayNightCycleSnapshotEntity(startTimeInSeconds));
UE_LOG(LogTemp, Display, TEXT("Adding PIG Entity to Snapshot..."));
entityMap.emplace(PIG_ID, CreateHQObjectSnapshotEntity(FVector(-7794.8f, -10651.0f, 31643.7f), FRotator{-0.75f, 80.0f, -4.30f}.Quaternion(), "Blender", 1000.0f, 1000.0f));
UE_LOG(LogTemp, Display, TEXT("Adding Generator Entities to Snapshot..."));
entityMap.emplace(GENERATOR_ID_START, CreateGeneratorSnapshotEntity(FVector(-2893.553223f, -11379.129883f, 31593.0f), FVector{ 0.0f, 169.999908f, 0.0f}.Rotation().Quaternion(), "GeneratorBP", "Forcefield2", 0.0f, 100.0f));
entityMap.emplace(GENERATOR_ID_START+1, CreateGeneratorSnapshotEntity(FVector(-7840.0f, -14060.0f, 31771.0f), FQuat::Identity, "GeneratorBP", "Forcefield3", 0.0f, 100.0f));
entityMap.emplace(GENERATOR_ID_START+2, CreateGeneratorSnapshotEntity(FVector(-5620.0f, -17400.0f, 32180.0f), FQuat::Identity, "GeneratorBP", "Forcefield_236", 0.0f, 100.0f));
UE_LOG(LogTemp, Display, TEXT("Adding HQ Entity to Snapshot..."));
entityMap.emplace(HQBASE_ID_START, CreateHQObjectSnapshotEntity(FVector(-4172.493652f, -12631.717773f, 32086.000000f), FVector{ 0.0f, 104.375053f, 0.0f }.Rotation().Quaternion(), "Base_BP", 5000.0f, 5000.0f));
UE_LOG(LogTemp, Display, TEXT("Adding a couple of Battery Entities to Snapshot..."));
entityMap.emplace(BATTERY_ID_START, CreateHQObjectSnapshotEntity(FVector(-5020.0f, -17400.0f, 33180.0), FQuat::Identity, "Battery_BP", 100.0f, 100.0f));
entityMap.emplace(BATTERY_ID_START+1, CreateHQObjectSnapshotEntity(FVector(-5990.0f, -16400.0f, 33180.0), FQuat::Identity, "Battery_BP", 100.0f, 100.0f));
entityMap.emplace(BATTERY_ID_START+2, CreateHQObjectSnapshotEntity(FVector(-7000.0f, -13510.0f, 32881.0f), FQuat::Identity, "Battery_BP", 100.0f, 100.0f));
entityMap.emplace(BATTERY_ID_START+3, CreateHQObjectSnapshotEntity(FVector(-7700.0f, -11510.0f, 32881.0f), FQuat::Identity, "Battery_BP", 100.0f, 100.0f));
entityMap.emplace(BATTERY_ID_START+4, CreateHQObjectSnapshotEntity(FVector(-2093.553223f, -11379.129883f, 32593.0f), FQuat::Identity, "Battery_BP", 100.0f, 100.0f));
entityMap.emplace(BATTERY_ID_START+5, CreateHQObjectSnapshotEntity(FVector(-2993.553223f, -12379.129883f, 32593.0f), FQuat::Identity, "Battery_BP", 100.0f, 100.0f));
// -- Write the snapshot to disc
UE_LOG(LogTemp, Display, TEXT("Trying to write Snapshot to the path %s with %d entries"), *fullPath, entityMap.size());
auto result = worker::SaveSnapshot(TCHAR_TO_UTF8(*fullPath), entityMap);
if (result.empty())
{
UE_LOG(LogTemp, Display, TEXT("Snapshot exported to the path %s"), *fullPath);
}
else
{
UE_LOG(LogTemp, Display, TEXT("ERROR writing Snapshot. Error message: %s"), *result->data());
}
/* worker::SaveSnapshot(TCHAR_TO_UTF8(*fullPath), {
// {454, CreateBlueprintTestSnapshotEntity(Vec)},
//{500, CreateNPCSnapshotEntity() },
{600, CreateDayNightCycleSnapshotEntity() }
});
*/
//worker::SaveSnapshot(TCHAR_TO_UTF8(*fullPath), { { 500, CreateNPCSnapshotEntity() } });
}
else
{
UE_LOG(LogTemp, Display, TEXT("bye world!"));
}
return 0;
}
void UExportSnapshotCommandlet::CreateMantisNPCEntitiesSpherical(std::unordered_map<worker::EntityId, worker::SnapshotEntity>& EntityMap, const FVector& RootSpawnLocation) const
{
UE_LOG(LogTemp, Display, TEXT("Adding %d Mantis NPCs spherically to Snapshot..."), SPHERICAL_NR_MANTIS_ENTITIES_TO_STORE);
float SpawnCircleRadius = 10000;
for (int i = 0; i < SPHERICAL_NR_MANTIS_ENTITIES_TO_STORE; ++i)
{
float angle = (360.0 * i) / ((float)SPHERICAL_NR_MANTIS_ENTITIES_TO_STORE);
float spawnX = RootSpawnLocation.X + SpawnCircleRadius * FMath::Cos(angle);
float spawnY = RootSpawnLocation.Y + SpawnCircleRadius * FMath::Sin(angle);
FVector spawnLocation = FVector(spawnX, spawnY, RootSpawnLocation.Z + 50000);
EntityMap.emplace(MANTIS_ID_START + i, CreateMantisNPCSnapshotEntity(spawnLocation));
}
}
void UExportSnapshotCommandlet::CreateMantisNPCSpawnPoints(std::unordered_map<worker::EntityId, worker::SnapshotEntity>& EntityMap) const
{
UE_LOG(LogTemp, Display, TEXT("Adding %d Mantis NPCs from spawnpoints position to Snapshot..."), NR_MANTIS_PER_SPAWNPOINT * MANTIS_START_SPAWNPOINTS.Num());
int idIndex = 0;
for (int i = 0; i < MANTIS_START_SPAWNPOINTS.Num(); ++i)
{
for (int x = 0; x < NR_MANTIS_PER_SPAWNPOINT; ++x)
{
FVector randomPos = MANTIS_START_SPAWNPOINTS[i] + (FMath::VRand() * 1000.0f);
randomPos.Z = MANTIS_START_SPAWNPOINTS[i].Z;
EntityMap.emplace(MANTIS_ID_START + idIndex, CreateMantisNPCSnapshotEntity(randomPos));
++idIndex;
}
}
}
void UExportSnapshotCommandlet::CreateRockSpawnPoints(std::unordered_map<worker::EntityId, worker::SnapshotEntity>& EntityMap, FVector SpawnOrigin) const
{
UE_LOG(LogTemp, Display, TEXT("Adding %d rocks to snapshot..."), NR_ROCKS_TO_SPAWN);
int idIndex = 0;
for (int i = 0; i < NR_ROCKS_TO_SPAWN; ++i)
{
FVector randomPos;
randomPos.X = FMath::FRandRange(SpawnOrigin.X - ROCK_SPAWN_AREA_RADIUS, SpawnOrigin.X + ROCK_SPAWN_AREA_RADIUS);
randomPos.Y = FMath::FRandRange(SpawnOrigin.Y - ROCK_SPAWN_AREA_RADIUS, SpawnOrigin.Y + ROCK_SPAWN_AREA_RADIUS);
randomPos.Z = 34000;
std::string RockType = ROCK_ASSET_NAMES[FMath::RandHelper(ROCK_ASSET_NAMES.Num() - 1)];
EntityMap.emplace(ROCK_ID_START + i, CreateAsteroidSnapshotEntity(randomPos, RockType));
}
}
worker::SnapshotEntity UExportSnapshotCommandlet::CreateBlueprintTestSnapshotEntity(const FVector& SpawnLoc) const
{
auto snapshotEntity = worker::SnapshotEntity();
snapshotEntity.Prefab = "BIGSUIT_character_class";
snapshotEntity.Add<TransformInfo>(
TransformInfo::Data{ UConversionsFunctionLibrary::FVectorToImprobableMathCoordinates(SpawnLoc),
IdentityQuaternion, 0.0f });
improbable::WorkerRequirementSet serverRequirementSet({{{{{"UnrealWorker"}}}}});
improbable::WorkerRequirementSet clientRequirementSet({{{{{"UnrealClient"}}}}});
// -- All ACLs
// Handle all authority delegations below.
worker::Map<std::uint32_t, improbable::WorkerRequirementSet> componentAuthority;
// Assign authority of TransformInfo component to UnrealClient
componentAuthority.emplace(TransformInfo::ComponentId, clientRequirementSet);
improbable::ComponentAcl componentAcl(componentAuthority);
// -- All Requirements
auto serverAttributeList = worker::List<improbable::WorkerAttribute>({worker::Option<std::string>("UnrealWorker")});
auto clientAttributeList = worker::List<improbable::WorkerAttribute>({worker::Option<std::string>("UnrealClient")});
// Combine the server and client attribute lists into a set.
// Pas sthe set as the combined requirements for all workers.
auto combinedAttributeSets = worker::List<improbable::WorkerAttributeSet>({{serverAttributeList}, {clientAttributeList}});
improbable::WorkerRequirementSet combinedRequirementSet(combinedAttributeSets);
// -- Set ACLs and Requirements on the Entity
snapshotEntity.Add<EntityAcl>(EntityAcl::Data(combinedRequirementSet, componentAcl));
return snapshotEntity;
}
worker::SnapshotEntity UExportSnapshotCommandlet::CreateDayNightCycleSnapshotEntity(float startTimeInSeconds) const
{
auto snapshotEntity = worker::SnapshotEntity();
// Prefab / Blueprint
snapshotEntity.Prefab = "DayNightCycleEntity";
// Components
snapshotEntity.Add<TransformInfo>(TransformInfo::Data{ UConversionsFunctionLibrary::FVectorToImprobableMathCoordinates(FVector::ZeroVector), IdentityQuaternion, 0.0f });
// (((Time_In_Seconds / 3600) mod 0.666) / 0.666) * 24
snapshotEntity.Add<DayNightCycle>(DayNightCycle::Data(startTimeInSeconds));
// Read Authority
auto read_access = UEntityFactory::UnrealClientOrUnrealWorker();
// Write Authority
worker::Map<std::uint32_t, improbable::WorkerRequirementSet> write_access;
write_access.emplace(TransformInfo::ComponentId, UEntityFactory::UnrealClientOnly());
write_access.emplace(DayNightCycle::ComponentId, UEntityFactory::UnrealWorkerOnly());
// -- Set ACLs and Requirements on the Entity
snapshotEntity.Add<EntityAcl>(EntityAcl::Data(
read_access,
improbable::ComponentAcl(write_access)
));
return snapshotEntity;
}
worker::SnapshotEntity UExportSnapshotCommandlet::CreateNPCSnapshotEntity() const
{
auto snapshotEntity = worker::SnapshotEntity();
snapshotEntity.Prefab = "BIGSUIT_NPC";
snapshotEntity.Add<TransformInfo>(
TransformInfo::Data{ UConversionsFunctionLibrary::FVectorToImprobableMathCoordinates(FVector(-5000, -15000, 35000)),
IdentityQuaternion, 0.0f});
snapshotEntity.Add<CharacterMovementInfo>(
CharacterMovementInfo::Data{ UConversionsFunctionLibrary::FVectorToImprobableMathVector3d(FVector()), 0.0f , 0.0f });
improbable::WorkerRequirementSet serverRequirementSet({ { { { { "UnrealWorker" } } } } });
improbable::WorkerRequirementSet clientRequirementSet({ { { { { "UnrealClient" } } } } });
// -- All ACLs
// Handle all authority delegations below.
worker::Map<std::uint32_t, improbable::WorkerRequirementSet> componentAuthority;
// Assign authority of TransformInfo compone to UnrealClient
componentAuthority.emplace(TransformInfo::ComponentId, serverRequirementSet);
componentAuthority.emplace(CharacterMovementInfo::ComponentId, serverRequirementSet);
improbable::ComponentAcl componentAcl(componentAuthority);
// -- All Requirements
auto serverAttributeList = worker::List<improbable::WorkerAttribute>({ worker::Option<std::string>("UnrealWorker") });
auto clientAttributeList = worker::List<improbable::WorkerAttribute>({ worker::Option<std::string>("UnrealClient") });
// Combine the server and client attribute lists into a set.
// Pas sthe set as the combined requirements for all workers.
auto combinedAttributeSets = worker::List<improbable::WorkerAttributeSet>({ { serverAttributeList },{ clientAttributeList } });
improbable::WorkerRequirementSet combinedRequirementSet(combinedAttributeSets);
// -- Set ACLs and Requirements on the Entity
snapshotEntity.Add<EntityAcl>(EntityAcl::Data(combinedRequirementSet, componentAcl));
return snapshotEntity;
}
worker::SnapshotEntity UExportSnapshotCommandlet::CreateMantisNPCSnapshotEntity(const FVector& SpawnLocation) const
{
auto snapshotEntity = worker::SnapshotEntity();
// Prefab / Blueprint
snapshotEntity.Prefab = "Mantis_v2";
// Components
snapshotEntity.Add<TransformInfo>(TransformInfo::Data{ UConversionsFunctionLibrary::FVectorToImprobableMathCoordinates(SpawnLocation), improbable::transform::Quaternion{1.0f, 0.0f, 0.0f, 0.0f}, 0.0f });
snapshotEntity.Add<CharacterMovementInfo>(CharacterMovementInfo::Data{ UConversionsFunctionLibrary::FVectorToImprobableMathVector3d(FVector()), 0.0f, 0.0f});
snapshotEntity.Add<HealthInfo>(HealthInfo::Data(100.0f, 100.0f));
snapshotEntity.Add<AnimationInfo>(AnimationInfo::Data{ "", 0.0f});
// Read Authority
auto read_access = UEntityFactory::UnrealClientOrUnrealWorker();
// Write Authority
worker::Map<std::uint32_t, improbable::WorkerRequirementSet> write_access;
write_access.emplace(TransformInfo::ComponentId, UEntityFactory::UnrealWorkerOnly());
write_access.emplace(CharacterMovementInfo::ComponentId, UEntityFactory::UnrealWorkerOnly());
write_access.emplace(HealthInfo::ComponentId, UEntityFactory::UnrealWorkerOnly());
write_access.emplace(AnimationInfo::ComponentId, UEntityFactory::UnrealWorkerOnly());
// -- Set ACLs and Requirements on the Entity
snapshotEntity.Add<EntityAcl>(EntityAcl::Data(read_access, improbable::ComponentAcl(write_access)));
return snapshotEntity;
}
worker::SnapshotEntity UExportSnapshotCommandlet::CreateSpawnerSnapshotEntity() const
{
auto snapshotEntity = worker::SnapshotEntity();
snapshotEntity.Prefab = "Spawner";
snapshotEntity.Add<TransformInfo>(TransformInfo::Data{ UConversionsFunctionLibrary::FVectorToImprobableMathCoordinates(FVector::ZeroVector), improbable::transform::Quaternion{1.0f, 0.0f, 0.0f, 0.0f}, 0.0f });
snapshotEntity.Add<spawner::Spawner>(spawner::Spawner::Data{});
// Read Authority
auto read_access = UEntityFactory::UnrealClientOrUnrealWorker();
// Write Authority
worker::Map<std::uint32_t, improbable::WorkerRequirementSet> write_access;
write_access.emplace(TransformInfo::ComponentId, UEntityFactory::UnrealWorkerOnly());
write_access.emplace(Spawner::ComponentId, UEntityFactory::UnrealWorkerOnly());
// -- Set ACLs and Requirements on the Entity
snapshotEntity.Add<EntityAcl>(EntityAcl::Data(read_access, improbable::ComponentAcl(write_access)));
return snapshotEntity;
}
worker::SnapshotEntity UExportSnapshotCommandlet::CreateAsteroidSnapshotEntity(const FVector& SpawnLocation, std::string RockAssetName) const
{
auto snapshotEntity = worker::SnapshotEntity();
// Prefab / Blueprint
snapshotEntity.Prefab = RockAssetName;
// Components
snapshotEntity.Add<TransformInfo>(TransformInfo::Data{ UConversionsFunctionLibrary::FVectorToImprobableMathCoordinates(SpawnLocation), improbable::transform::Quaternion{1.0f, 0.0f, 0.0f, 0.0f}, 0.0f });
// Read Authority
auto read_access = UEntityFactory::UnrealClientOrUnrealWorker();
// Write Authority
worker::Map<std::uint32_t, improbable::WorkerRequirementSet> write_access;
write_access.emplace(TransformInfo::ComponentId, UEntityFactory::UnrealWorkerOnly());
// -- Set ACLs and Requirements on the Entity
snapshotEntity.Add<EntityAcl>(EntityAcl::Data(read_access, improbable::ComponentAcl(write_access)));
return snapshotEntity;
}
worker::SnapshotEntity UExportSnapshotCommandlet::CreateHQObjectSnapshotEntity(const FVector& SpawnLocation, const FQuat& SpawnRotation, const std::string& PrefabName, float InitialHealth, float MaxHealth) const
{
auto snapshotEntity = worker::SnapshotEntity();
// Prefab / Blueprint
snapshotEntity.Prefab = PrefabName;
// Components
snapshotEntity.Add<TransformInfo>(TransformInfo::Data(UConversionsFunctionLibrary::FVectorToImprobableMathCoordinates(SpawnLocation), UConversionsFunctionLibrary::FQuatToImprobableQuaternion(SpawnRotation), 0.0f));
snapshotEntity.Add<HealthInfo>(HealthInfo::Data(InitialHealth, MaxHealth));
// Read Authority
auto read_access = UEntityFactory::UnrealClientOrUnrealWorker();
// Write Authority
worker::Map<std::uint32_t, improbable::WorkerRequirementSet> write_access;
write_access.emplace(TransformInfo::ComponentId, UEntityFactory::UnrealWorkerOnly());
write_access.emplace(HealthInfo::ComponentId, UEntityFactory::UnrealWorkerOnly());
// -- Set ACLs and Requirements on the Entity
snapshotEntity.Add<EntityAcl>(EntityAcl::Data(read_access, improbable::ComponentAcl(write_access)));
return snapshotEntity;
}
worker::SnapshotEntity UExportSnapshotCommandlet::CreateGeneratorSnapshotEntity(const FVector& SpawnLocation, const FQuat& SpawnRotation, const std::string& PrefabName, const std::string& ForcefieldName, float InitialHealth, float MaxHealth) const
{
auto snapshotEntity = worker::SnapshotEntity();
// Prefab / Blueprint
snapshotEntity.Prefab = PrefabName;
// Components
snapshotEntity.Add<TransformInfo>(TransformInfo::Data(UConversionsFunctionLibrary::FVectorToImprobableMathCoordinates(SpawnLocation), UConversionsFunctionLibrary::FQuatToImprobableQuaternion(SpawnRotation), 0.0f));
snapshotEntity.Add<HealthInfo>(HealthInfo::Data(InitialHealth, MaxHealth));
snapshotEntity.Add<ForcefieldInfo>(ForcefieldInfo::Data(ForcefieldName));
// Read Authority
auto read_access = UEntityFactory::UnrealClientOrUnrealWorker();
// Write Authority
worker::Map<std::uint32_t, improbable::WorkerRequirementSet> write_access;
write_access.emplace(TransformInfo::ComponentId, UEntityFactory::UnrealWorkerOnly());
write_access.emplace(HealthInfo::ComponentId, UEntityFactory::UnrealWorkerOnly());
write_access.emplace(ForcefieldInfo::ComponentId, UEntityFactory::UnrealWorkerOnly());
// -- Set ACLs and Requirements on the Entity
snapshotEntity.Add<EntityAcl>(EntityAcl::Data(read_access, improbable::ComponentAcl(write_access)));
return snapshotEntity;
}
worker::SnapshotEntity UExportSnapshotCommandlet::CreateMantisSpawnerSnapshotEntity() const
{
auto snapshotEntity = worker::SnapshotEntity();
snapshotEntity.Prefab = "Mantis_Spawner";
snapshotEntity.Add<TransformInfo>(TransformInfo::Data{ UConversionsFunctionLibrary::FVectorToImprobableMathCoordinates(FVector::ZeroVector), improbable::transform::Quaternion{1.0f, 0.0f, 0.0f, 0.0f}, 0.0f });
// Read Authority
auto read_access = UEntityFactory::UnrealClientOrUnrealWorker();
// Write Authority
worker::Map<std::uint32_t, improbable::WorkerRequirementSet> write_access;
write_access.emplace(TransformInfo::ComponentId, UEntityFactory::UnrealWorkerOnly());
// -- Set ACLs and Requirements on the Entity
snapshotEntity.Add<EntityAcl>(EntityAcl::Data(read_access, improbable::ComponentAcl(write_access)));
return snapshotEntity;
}
| 43.281513 | 247 | 0.779342 | spatialos |
057d5896ff677d9e0ec6d401c783d6f1b12e7591 | 1,251 | hpp | C++ | src/umpire/strategy/DefaultAllocationStrategy.hpp | aaroncblack/Umpire | 5089a55aeed8b269112125e917f08b10e1797ae5 | [
"MIT"
] | null | null | null | src/umpire/strategy/DefaultAllocationStrategy.hpp | aaroncblack/Umpire | 5089a55aeed8b269112125e917f08b10e1797ae5 | [
"MIT"
] | null | null | null | src/umpire/strategy/DefaultAllocationStrategy.hpp | aaroncblack/Umpire | 5089a55aeed8b269112125e917f08b10e1797ae5 | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2018-2019, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory
//
// Created by David Beckingsale, david@llnl.gov
// LLNL-CODE-747640
//
// All rights reserved.
//
// This file is part of Umpire.
//
// For details, see https://github.com/LLNL/Umpire
// Please also see the LICENSE file for MIT license.
//////////////////////////////////////////////////////////////////////////////
#ifndef UMPIRE_DefaultAllocationStrategy_HPP
#define UMPIRE_DefaultAllocationStrategy_HPP
#include "umpire/strategy/AllocationStrategy.hpp"
namespace umpire {
namespace strategy {
class DefaultAllocationStrategy :
public AllocationStrategy
{
public:
DefaultAllocationStrategy(strategy::AllocationStrategy* allocator);
void* allocate(size_t bytes);
/*!
* \brief Free the memory at ptr.
*
* \param ptr Pointer to free.
*/
void deallocate(void* ptr);
long getCurrentSize() const;
long getHighWatermark() const;
Platform getPlatform();
protected:
strategy::AllocationStrategy* m_allocator;
};
} // end of namespace strategy
} // end of namespace umpire
#endif
| 24.529412 | 78 | 0.635492 | aaroncblack |
057e9500cb7f275501dc7cb5863db7988b245203 | 2,506 | cpp | C++ | Game/Cards/Magic/DarkLight.cpp | CrusaderCrab/YugiohPhantomRealm | 79bd1e9948d2d2d29acf042fd412804c30562a8e | [
"Zlib"
] | 13 | 2018-04-13T22:10:00.000Z | 2022-01-01T08:26:23.000Z | Game/Cards/Magic/DarkLight.cpp | CrusaderCrab/YugiohPhantomRealm | 79bd1e9948d2d2d29acf042fd412804c30562a8e | [
"Zlib"
] | null | null | null | Game/Cards/Magic/DarkLight.cpp | CrusaderCrab/YugiohPhantomRealm | 79bd1e9948d2d2d29acf042fd412804c30562a8e | [
"Zlib"
] | 3 | 2017-02-22T16:35:06.000Z | 2019-12-21T20:39:23.000Z | #include <Game\Cards\Magic\DarkLight.h>
#include <Utility\Clock.h>
#include <Game\Cards\Magic\MagicUnit.h>
#include <Game\Animation\ParticlesUnit.h>
#include <Game\Duel\Board.h>
#include <Game\Animation\FadeUnit.h>
#include <Utility\SoundUnit.h>
#define ZYUG_GO 0
#define ZYUG_GLOW 1
#define ZYUG_FLASH 2
#define ZYUG_FADE 3
#define ZYUG_FIN 4
namespace Card{
void DarkLight::startup(){
Game::WaitUnit::startup();
chain = ZYUG_GO;
theBoard.magicBeforeParticles = true;
centreGlow.startup(YUG_PLANE_FILE_PATH,
"GameData/textures/particles/glowingorb.png");
centreGlow.ignoreCamera = true;
centreGlow.position = glm::vec3(0.0f,0.0f,-0.8f);
centreGlow.amtran = glm::vec4(1,1,1,0);
centreGlow.scale = glm::vec3(0,0,1);
centreGlow.doRender = false;
}
void DarkLight::cleanup(){
centreGlow.cleanup();
theBoard.magicBeforeParticles = false;
}
void DarkLight::render(){
centreGlow.render();
}
void DarkLight::update(){
centreGlow.update();
if(!isWaiting){
switch(chain){
case ZYUG_GO:
startUpdate();
break;
case ZYUG_GLOW:
glowUpdate();
break;
case ZYUG_FLASH:
flashUpdate();
break;
case ZYUG_FADE:
fadeUpdate();
break;
case ZYUG_FIN:
finishUpdate();
break;
default:
break;
}
}else{
continueWaiting();
}
}
void DarkLight::startUpdate(){
soundUnit.playOnce("GameData/sounds/magic/darkLightNoise.wav");
centreGlow.doRender = true;
centreGlow.interpolateAmtran(glm::vec4(1,1,1,1),0.75f);
centreGlow.scaleInterpolate(glm::vec3(0.2f,0.2f,1.0f),1.0f);
wait(0.9f);
chain = ZYUG_FLASH;
}
void DarkLight::glowUpdate(){
wait(0.1f);
chain = ZYUG_FLASH;
}
void DarkLight::flashUpdate(){
fadeUnit.sheet.amtran = glm::vec4(1,1,1,0);
fadeUnit.fadeTo(glm::vec4(1,1,1,1),0.05f);
for(unsigned int i = 0; i<5; i++){
if(!theBoard.board[i][YUG_BOARD_PLAYER_MON_ROW].faceUp){
theBoard.flipCard(i,YUG_BOARD_PLAYER_MON_ROW);
}
if(!theBoard.board[i][YUG_BOARD_ENEMY_MON_ROW].faceUp){
theBoard.flipCard(i,YUG_BOARD_ENEMY_MON_ROW);
}
}
chain = ZYUG_FADE;
wait(0.05f);
}
void DarkLight::fadeUpdate(){
particleUnit.ignoreCamera = true;
particleUnit.doRender = true;
glm::vec3 v = centreGlow.position;
v.z = -1.1f;
particleUnit.particleBang(v,0.2f);
centreGlow.doRender = false;
fadeUnit.fadeTo(glm::vec4(1,1,1,0),0.2f);
wait(0.3f);
chain = ZYUG_FIN;
}
void DarkLight::finishUpdate(){
magicUnit.chain = YUG_MAG_CH_SPECIFC_FINISHED;
}
}
| 21.982456 | 65 | 0.689545 | CrusaderCrab |
05869f3dc417acaca91576137455e83baa482028 | 50,999 | cpp | C++ | Targets/STM32F7xx/STM32F7_Display.cpp | valoni/TinyCLR-Ports | 2c8c510aaa6f1ee26ecf12c13fcea678de31545e | [
"Apache-2.0"
] | 30 | 2017-07-18T10:03:36.000Z | 2021-05-20T12:35:06.000Z | Targets/STM32F7xx/STM32F7_Display.cpp | valoni/TinyCLR-Ports | 2c8c510aaa6f1ee26ecf12c13fcea678de31545e | [
"Apache-2.0"
] | 294 | 2017-07-09T23:06:04.000Z | 2019-07-23T18:26:28.000Z | Targets/STM32F7xx/STM32F7_Display.cpp | valoni/TinyCLR-Ports | 2c8c510aaa6f1ee26ecf12c13fcea678de31545e | [
"Apache-2.0"
] | 28 | 2017-07-08T07:52:54.000Z | 2022-03-13T19:35:34.000Z | // Copyright Microsoft Corporation
// Copyright GHI Electronics, 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
//
// 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 <string.h>
#include "STM32F7.h"
#ifdef INCLUDE_DISPLAY
#define MAX_LAYER 2
/**
* @brief LTDC color structure definition
*/
typedef struct {
uint8_t Blue; /*!< Configures the blue value.
This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */
uint8_t Green; /*!< Configures the green value.
This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */
uint8_t Red; /*!< Configures the red value.
This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */
uint8_t Reserved; /*!< Reserved 0xFF */
} LTDC_ColorTypeDef;
/**
* @brief LTDC Init structure definition
*/
typedef struct {
uint32_t HSPolarity; /*!< configures the horizontal synchronization polarity.
This parameter can be one value of @ref LTDC_HS_POLARITY */
uint32_t VSPolarity; /*!< configures the vertical synchronization polarity.
This parameter can be one value of @ref LTDC_VS_POLARITY */
uint32_t DEPolarity; /*!< configures the data enable polarity.
This parameter can be one of value of @ref LTDC_DE_POLARITY */
uint32_t PCPolarity; /*!< configures the pixel clock polarity.
This parameter can be one of value of @ref LTDC_PC_POLARITY */
uint32_t HorizontalSync; /*!< configures the number of Horizontal synchronization width.
This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */
uint32_t VerticalSync; /*!< configures the number of Vertical synchronization height.
This parameter must be a number between Min_Data = 0x000 and Max_Data = 0x7FF. */
uint32_t AccumulatedHBP; /*!< configures the accumulated horizontal back porch width.
This parameter must be a number between Min_Data = LTDC_HorizontalSync and Max_Data = 0xFFF. */
uint32_t AccumulatedVBP; /*!< configures the accumulated vertical back porch height.
This parameter must be a number between Min_Data = LTDC_VerticalSync and Max_Data = 0x7FF. */
uint32_t AccumulatedActiveW; /*!< configures the accumulated active width.
This parameter must be a number between Min_Data = LTDC_AccumulatedHBP and Max_Data = 0xFFF. */
uint32_t AccumulatedActiveH; /*!< configures the accumulated active height.
This parameter must be a number between Min_Data = LTDC_AccumulatedVBP and Max_Data = 0x7FF. */
uint32_t TotalWidth; /*!< configures the total width.
This parameter must be a number between Min_Data = LTDC_AccumulatedActiveW and Max_Data = 0xFFF. */
uint32_t TotalHeigh; /*!< configures the total height.
This parameter must be a number between Min_Data = LTDC_AccumulatedActiveH and Max_Data = 0x7FF. */
LTDC_ColorTypeDef Backcolor; /*!< Configures the background color. */
} LTDC_InitTypeDef;
/**
* @brief LTDC Layer structure definition
*/
typedef struct {
uint32_t WindowX0; /*!< Configures the Window Horizontal Start Position.
This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */
uint32_t WindowX1; /*!< Configures the Window Horizontal Stop Position.
This parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF. */
uint32_t WindowY0; /*!< Configures the Window vertical Start Position.
This parameter must be a number between Min_Data = 0x000 and Max_Data = 0x7FF. */
uint32_t WindowY1; /*!< Configures the Window vertical Stop Position.
This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0x7FF. */
uint32_t PixelFormat; /*!< Specifies the pixel format.
This parameter can be one of value of @ref LTDC_Pixelformat */
uint32_t Alpha; /*!< Specifies the constant alpha used for blending.
This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */
uint32_t Alpha0; /*!< Configures the default alpha value.
This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. */
uint32_t BlendingFactor1; /*!< Select the blending factor 1.
This parameter can be one of value of @ref LTDC_BlendingFactor1 */
uint32_t BlendingFactor2; /*!< Select the blending factor 2.
This parameter can be one of value of @ref LTDC_BlendingFactor2 */
uint32_t FBStartAdress; /*!< Configures the color frame buffer address */
uint32_t ImageWidth; /*!< Configures the color frame buffer line length.
This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0x1FFF. */
uint32_t ImageHeight; /*!< Specifies the number of line in frame buffer.
This parameter must be a number between Min_Data = 0x000 and Max_Data = 0x7FF. */
LTDC_ColorTypeDef Backcolor; /*!< Configures the layer background color. */
} LTDC_LayerCfgTypeDef;
/**
* @brief LTDC handle Structure definition
*/
typedef struct {
LTDC_TypeDef *Instance; /*!< LTDC Register base address */
LTDC_InitTypeDef Init; /*!< LTDC parameters */
LTDC_LayerCfgTypeDef LayerCfg[MAX_LAYER]; /*!< LTDC Layers parameters */
} LTDC_HandleTypeDef;
/**
* @}
*/
/** @defgroup LTDC_HS_POLARITY LTDC HS POLARITY
* @{
*/
#define LTDC_HSPOLARITY_AL ((uint32_t)0x00000000) /*!< Horizontal Synchronization is active low. */
#define LTDC_HSPOLARITY_AH LTDC_GCR_HSPOL /*!< Horizontal Synchronization is active high. */
/**
* @}
*/
/** @defgroup LTDC_VS_POLARITY LTDC VS POLARITY
* @{
*/
#define LTDC_VSPOLARITY_AL ((uint32_t)0x00000000) /*!< Vertical Synchronization is active low. */
#define LTDC_VSPOLARITY_AH LTDC_GCR_VSPOL /*!< Vertical Synchronization is active high. */
/**
* @}
*/
/** @defgroup LTDC_DE_POLARITY LTDC DE POLARITY
* @{
*/
#define LTDC_DEPOLARITY_AL ((uint32_t)0x00000000) /*!< Data Enable, is active low. */
#define LTDC_DEPOLARITY_AH LTDC_GCR_DEPOL /*!< Data Enable, is active high. */
/**
* @}
*/
/** @defgroup LTDC_PC_POLARITY LTDC PC POLARITY
* @{
*/
#define LTDC_PCPOLARITY_IPC ((uint32_t)0x00000000) /*!< input pixel clock. */
#define LTDC_PCPOLARITY_IIPC LTDC_GCR_PCPOL /*!< inverted input pixel clock. */
/** @defgroup LTDC_Pixelformat LTDC Pixel format
* @{
*/
#define LTDC_PIXEL_FORMAT_ARGB8888 ((uint32_t)0x00000000) /*!< ARGB8888 LTDC pixel format */
#define LTDC_PIXEL_FORMAT_RGB888 ((uint32_t)0x00000001) /*!< RGB888 LTDC pixel format */
#define LTDC_PIXEL_FORMAT_RGB565 ((uint32_t)0x00000002) /*!< RGB565 LTDC pixel format */
#define LTDC_PIXEL_FORMAT_ARGB1555 ((uint32_t)0x00000003) /*!< ARGB1555 LTDC pixel format */
#define LTDC_PIXEL_FORMAT_ARGB4444 ((uint32_t)0x00000004) /*!< ARGB4444 LTDC pixel format */
#define LTDC_PIXEL_FORMAT_L8 ((uint32_t)0x00000005) /*!< L8 LTDC pixel format */
#define LTDC_PIXEL_FORMAT_AL44 ((uint32_t)0x00000006) /*!< AL44 LTDC pixel format */
#define LTDC_PIXEL_FORMAT_AL88 ((uint32_t)0x00000007) /*!< AL88 LTDC pixel format */
/**
* @}
*/
/** @defgroup LTDC_BlendingFactor1 LTDC Blending Factor1
* @{
*/
#define LTDC_BLENDING_FACTOR1_CA ((uint32_t)0x00000400) /*!< Blending factor : Cte Alpha */
#define LTDC_BLENDING_FACTOR1_PAxCA ((uint32_t)0x00000600) /*!< Blending factor : Cte Alpha x Pixel Alpha*/
/**
* @}
*/
/** @defgroup LTDC_BlendingFactor2 LTDC Blending Factor2
* @{
*/
#define LTDC_BLENDING_FACTOR2_CA ((uint32_t)0x00000005) /*!< Blending factor : Cte Alpha */
#define LTDC_BLENDING_FACTOR2_PAxCA ((uint32_t)0x00000007) /*!< Blending factor : Cte Alpha x Pixel Alpha*/
/**
* @}
*/
#define LTDC_LAYER(__HANDLE__, __LAYER__) ((LTDC_Layer_TypeDef *)((uint32_t)(((uint32_t)((__HANDLE__)->Instance)) + 0x84 + (0x80*(__LAYER__)))))
const uint8_t characters[129][5] = {
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00, /* Espace 0x20 */
0x00,0x00,0x4f,0x00,0x00, /* ! */
0x00,0x07,0x00,0x07,0x00, /* " */
0x14,0x7f,0x14,0x7f,0x14, /* # */
0x24,0x2a,0x7f,0x2a,0x12, /* 0x */
0x23,0x13,0x08,0x64,0x62, /* % */
0x36,0x49,0x55,0x22,0x20, /* & */
0x00,0x05,0x03,0x00,0x00, /* ' */
0x00,0x1c,0x22,0x41,0x00, /* ( */
0x00,0x41,0x22,0x1c,0x00, /* ) */
0x14,0x08,0x3e,0x08,0x14, /* // */
0x08,0x08,0x3e,0x08,0x08, /* + */
0x50,0x30,0x00,0x00,0x00, /* , */
0x08,0x08,0x08,0x08,0x08, /* - */
0x00,0x60,0x60,0x00,0x00, /* . */
0x20,0x10,0x08,0x04,0x02, /* / */
0x3e,0x51,0x49,0x45,0x3e, /* 0 0x30 */
0x00,0x42,0x7f,0x40,0x00, /* 1 */
0x42,0x61,0x51,0x49,0x46, /* 2 */
0x21,0x41,0x45,0x4b,0x31, /* 3 */
0x18,0x14,0x12,0x7f,0x10, /* 4 */
0x27,0x45,0x45,0x45,0x39, /* 5 */
0x3c,0x4a,0x49,0x49,0x30, /* 6 */
0x01,0x71,0x09,0x05,0x03, /* 7 */
0x36,0x49,0x49,0x49,0x36, /* 8 */
0x06,0x49,0x49,0x29,0x1e, /* 9 */
0x00,0x36,0x36,0x00,0x00, /* : */
0x00,0x56,0x36,0x00,0x00, /* ; */
0x08,0x14,0x22,0x41,0x00, /* < */
0x14,0x14,0x14,0x14,0x14, /* = */
0x00,0x41,0x22,0x14,0x08, /* > */
0x02,0x01,0x51,0x09,0x06, /* ? */
0x3e,0x41,0x5d,0x55,0x1e, /* @ 0x40 */
0x7e,0x11,0x11,0x11,0x7e, /* A */
0x7f,0x49,0x49,0x49,0x36, /* B */
0x3e,0x41,0x41,0x41,0x22, /* C */
0x7f,0x41,0x41,0x22,0x1c, /* D */
0x7f,0x49,0x49,0x49,0x41, /* E */
0x7f,0x09,0x09,0x09,0x01, /* F */
0x3e,0x41,0x49,0x49,0x7a, /* G */
0x7f,0x08,0x08,0x08,0x7f, /* H */
0x00,0x41,0x7f,0x41,0x00, /* I */
0x20,0x40,0x41,0x3f,0x01, /* J */
0x7f,0x08,0x14,0x22,0x41, /* K */
0x7f,0x40,0x40,0x40,0x40, /* L */
0x7f,0x02,0x0c,0x02,0x7f, /* M */
0x7f,0x04,0x08,0x10,0x7f, /* N */
0x3e,0x41,0x41,0x41,0x3e, /* O */
0x7f,0x09,0x09,0x09,0x06, /* P 0x50 */
0x3e,0x41,0x51,0x21,0x5e, /* Q */
0x7f,0x09,0x19,0x29,0x46, /* R */
0x26,0x49,0x49,0x49,0x32, /* S */
0x01,0x01,0x7f,0x01,0x01, /* T */
0x3f,0x40,0x40,0x40,0x3f, /* U */
0x1f,0x20,0x40,0x20,0x1f, /* V */
0x3f,0x40,0x38,0x40,0x3f, /* W */
0x63,0x14,0x08,0x14,0x63, /* X */
0x07,0x08,0x70,0x08,0x07, /* Y */
0x61,0x51,0x49,0x45,0x43, /* Z */
0x00,0x7f,0x41,0x41,0x00, /* [ */
0x02,0x04,0x08,0x10,0x20, /* \ */
0x00,0x41,0x41,0x7f,0x00, /* ] */
0x04,0x02,0x01,0x02,0x04, /* ^ */
0x40,0x40,0x40,0x40,0x40, /* _ */
0x00,0x00,0x03,0x05,0x00, /* ` 0x60 */
0x20,0x54,0x54,0x54,0x78, /* a */
0x7F,0x44,0x44,0x44,0x38, /* b */
0x38,0x44,0x44,0x44,0x44, /* c */
0x38,0x44,0x44,0x44,0x7f, /* d */
0x38,0x54,0x54,0x54,0x18, /* e */
0x04,0x04,0x7e,0x05,0x05, /* f */
0x08,0x54,0x54,0x54,0x3c, /* g */
0x7f,0x08,0x04,0x04,0x78, /* h */
0x00,0x44,0x7d,0x40,0x00, /* i */
0x20,0x40,0x44,0x3d,0x00, /* j */
0x7f,0x10,0x28,0x44,0x00, /* k */
0x00,0x41,0x7f,0x40,0x00, /* l */
0x7c,0x04,0x7c,0x04,0x78, /* m */
0x7c,0x08,0x04,0x04,0x78, /* n */
0x38,0x44,0x44,0x44,0x38, /* o */
0x7c,0x14,0x14,0x14,0x08, /* p 0x70 */
0x08,0x14,0x14,0x14,0x7c, /* q */
0x7c,0x08,0x04,0x04,0x00, /* r */
0x48,0x54,0x54,0x54,0x24, /* s */
0x04,0x04,0x3f,0x44,0x44, /* t */
0x3c,0x40,0x40,0x20,0x7c, /* u */
0x1c,0x20,0x40,0x20,0x1c, /* v */
0x3c,0x40,0x30,0x40,0x3c, /* w */
0x44,0x28,0x10,0x28,0x44, /* x */
0x0c,0x50,0x50,0x50,0x3c, /* y */
0x44,0x64,0x54,0x4c,0x44, /* z */
0x08,0x36,0x41,0x41,0x00, /* { */
0x00,0x00,0x77,0x00,0x00, /* | */
0x00,0x41,0x41,0x36,0x08, /* } */
0x08,0x08,0x2a,0x1c,0x08, /* <- */
0x08,0x1c,0x2a,0x08,0x08, /* -> */
0xff,0xff,0xff,0xff,0xff, /* 0x80 */
};
#define LCD_MAX_ROW 32
#define LCD_MAX_COLUMN 70
enum STM32F7xx_LCD_Rotation {
rotateNormal_0,
rotateCW_90,
rotate_180,
rotateCCW_90,
};
uint32_t m_STM32F7_DisplayWidth = 0;
uint32_t m_STM32F7_DisplayHeight = 0;
uint32_t m_STM32F7_DisplayPixelClockRateKHz = 0;
uint32_t m_STM32F7_DisplayHorizontalSyncPulseWidth = 0;
uint32_t m_STM32F7_DisplayHorizontalFrontPorch = 0;
uint32_t m_STM32F7_DisplayHorizontalBackPorch = 0;
uint32_t m_STM32F7_DisplayVerticalSyncPulseWidth = 0;
uint32_t m_STM32F7_DisplayVerticalFrontPorch = 0;
uint32_t m_STM32F7_DisplayVerticalBackPorch = 0;
uint32_t m_STM32F7_Display_TextRow = 0;
uint32_t m_STM32F7_Display_TextColumn = 0;
bool m_STM32F7_DisplayOutputEnableIsFixed = false;
bool m_STM32F7_DisplayOutputEnablePolarity = false;
bool m_STM32F7_DisplayPixelPolarity = false;
bool m_STM32F7_DisplayHorizontalSyncPolarity = false;
bool m_STM32F7_DisplayVerticalSyncPolarity = false;
bool m_STM32F7_DisplayEnable = false;
uint32_t displayInitializeCount = 0;
uint16_t* m_STM32F7_Display_VituralRam = nullptr;
uint32_t* m_STM32F7_Display_buffer = nullptr;
size_t m_STM32F7_DisplayBufferSize = 0;
uint8_t m_STM32F7_Display_TextBuffer[LCD_MAX_COLUMN][LCD_MAX_ROW];
STM32F7xx_LCD_Rotation m_STM32F7_Display_CurrentRotation = STM32F7xx_LCD_Rotation::rotateNormal_0;
bool STM32F7_Display_Initialize();
bool STM32F7_Display_Uninitialize();
bool STM32F7_Display_SetPinConfiguration(int32_t controllerIndex, bool enable);
void STM32F7_Display_WriteFormattedChar(uint8_t c);
void STM32F7_Display_WriteChar(uint8_t c, int32_t row, int32_t col);
void STM32F7_Display_BitBltEx(int32_t x, int32_t y, int32_t width, int32_t height, uint32_t data[]);
void STM32F7_Display_PaintPixel(uint32_t x, uint32_t y, uint8_t c);
void STM32F7_Display_Paint8HorizontalPixels(uint32_t x, uint32_t y, uint8_t p);
void STM32F7_Display_TextEnterClearMode();
void STM32F7_Display_PrintChracter(uint32_t x, uint32_t y, uint8_t c);
void STM32F7_Display_TextShiftColUp();
void STM32F7_Display_Clear();
void STM32F7_Display_GetRotatedDimensions(int32_t *screenWidth, int32_t *screenHeight);
int32_t STM32F7_Display_GetWidth();
int32_t STM32F7_Display_GetHeight();
int32_t STM32F7_Display_BitPerPixel();
uint32_t STM32F7_Display_GetPixelClockDivider();
int32_t STM32F7_Display_GetOrientation();
uint32_t* STM32F7_Display_GetFrameBuffer();
#define TOTAL_DISPLAY_CONTROLLERS 1
static TinyCLR_Display_Controller displayControllers[TOTAL_DISPLAY_CONTROLLERS];
static TinyCLR_Api_Info displayApi[TOTAL_DISPLAY_CONTROLLERS];
bool STM32F7_Ltdc_Initialize(LTDC_HandleTypeDef *hltdc) {
uint32_t tmp = 0, tmp1 = 0;
/* Check the LTDC peripheral state */
if (hltdc == nullptr) {
return false;
}
/* Configures the HS, VS, DE and PC polarity */
hltdc->Instance->GCR &= ~(LTDC_GCR_HSPOL | LTDC_GCR_VSPOL | LTDC_GCR_DEPOL | LTDC_GCR_PCPOL);
hltdc->Instance->GCR |= (uint32_t)(hltdc->Init.HSPolarity | hltdc->Init.VSPolarity | \
hltdc->Init.DEPolarity | hltdc->Init.PCPolarity);
/* Sets Synchronization size */
hltdc->Instance->SSCR &= ~(LTDC_SSCR_VSH | LTDC_SSCR_HSW);
tmp = (hltdc->Init.HorizontalSync << 16);
hltdc->Instance->SSCR |= (tmp | hltdc->Init.VerticalSync);
/* Sets Accumulated Back porch */
hltdc->Instance->BPCR &= ~(LTDC_BPCR_AVBP | LTDC_BPCR_AHBP);
tmp = (hltdc->Init.AccumulatedHBP << 16);
hltdc->Instance->BPCR |= (tmp | hltdc->Init.AccumulatedVBP);
/* Sets Accumulated Active Width */
hltdc->Instance->AWCR &= ~(LTDC_AWCR_AAH | LTDC_AWCR_AAW);
tmp = (hltdc->Init.AccumulatedActiveW << 16);
hltdc->Instance->AWCR |= (tmp | hltdc->Init.AccumulatedActiveH);
/* Sets Total Width */
hltdc->Instance->TWCR &= ~(LTDC_TWCR_TOTALH | LTDC_TWCR_TOTALW);
tmp = (hltdc->Init.TotalWidth << 16);
hltdc->Instance->TWCR |= (tmp | hltdc->Init.TotalHeigh);
/* Sets the background color value */
tmp = ((uint32_t)(hltdc->Init.Backcolor.Green) << 8);
tmp1 = ((uint32_t)(hltdc->Init.Backcolor.Red) << 16);
hltdc->Instance->BCCR &= ~(LTDC_BCCR_BCBLUE | LTDC_BCCR_BCGREEN | LTDC_BCCR_BCRED);
hltdc->Instance->BCCR |= (tmp1 | tmp | hltdc->Init.Backcolor.Blue);
/* Enable the transfer Error interrupt */
hltdc->Instance->IER |= LTDC_IER_TERRIE;
/* Enable the FIFO underrun interrupt */
hltdc->Instance->IER |= LTDC_IER_FUIE;
/* Enable LTDC by setting LTDCEN bit */
hltdc->Instance->GCR |= LTDC_GCR_LTDCEN;
return true;
}
void STM32F7_Ltdc_SetConfiguration(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, uint32_t LayerIdx) {
uint32_t tmp = 0;
uint32_t tmp1 = 0;
uint32_t tmp2 = 0;
/* Configures the horizontal start and stop position */
tmp = ((pLayerCfg->WindowX1 + ((hltdc->Instance->BPCR & LTDC_BPCR_AHBP) >> 16)) << 16);
LTDC_LAYER(hltdc, LayerIdx)->WHPCR &= ~(LTDC_LxWHPCR_WHSTPOS | LTDC_LxWHPCR_WHSPPOS);
LTDC_LAYER(hltdc, LayerIdx)->WHPCR = ((pLayerCfg->WindowX0 + ((hltdc->Instance->BPCR & LTDC_BPCR_AHBP) >> 16) + 1) | tmp);
/* Configures the vertical start and stop position */
tmp = ((pLayerCfg->WindowY1 + (hltdc->Instance->BPCR & LTDC_BPCR_AVBP)) << 16);
LTDC_LAYER(hltdc, LayerIdx)->WVPCR &= ~(LTDC_LxWVPCR_WVSTPOS | LTDC_LxWVPCR_WVSPPOS);
LTDC_LAYER(hltdc, LayerIdx)->WVPCR = ((pLayerCfg->WindowY0 + (hltdc->Instance->BPCR & LTDC_BPCR_AVBP) + 1) | tmp);
/* Specifies the pixel format */
LTDC_LAYER(hltdc, LayerIdx)->PFCR &= ~(LTDC_LxPFCR_PF);
LTDC_LAYER(hltdc, LayerIdx)->PFCR = (pLayerCfg->PixelFormat);
/* Configures the default color values */
tmp = ((uint32_t)(pLayerCfg->Backcolor.Green) << 8);
tmp1 = ((uint32_t)(pLayerCfg->Backcolor.Red) << 16);
tmp2 = (pLayerCfg->Alpha0 << 24);
LTDC_LAYER(hltdc, LayerIdx)->DCCR &= ~(LTDC_LxDCCR_DCBLUE | LTDC_LxDCCR_DCGREEN | LTDC_LxDCCR_DCRED | LTDC_LxDCCR_DCALPHA);
LTDC_LAYER(hltdc, LayerIdx)->DCCR = (pLayerCfg->Backcolor.Blue | tmp | tmp1 | tmp2);
/* Specifies the constant alpha value */
LTDC_LAYER(hltdc, LayerIdx)->CACR &= ~(LTDC_LxCACR_CONSTA);
LTDC_LAYER(hltdc, LayerIdx)->CACR = (pLayerCfg->Alpha);
/* Specifies the blending factors */
LTDC_LAYER(hltdc, LayerIdx)->BFCR &= ~(LTDC_LxBFCR_BF2 | LTDC_LxBFCR_BF1);
LTDC_LAYER(hltdc, LayerIdx)->BFCR = (pLayerCfg->BlendingFactor1 | pLayerCfg->BlendingFactor2);
/* Configures the color frame buffer start address */
LTDC_LAYER(hltdc, LayerIdx)->CFBAR &= ~(LTDC_LxCFBAR_CFBADD);
LTDC_LAYER(hltdc, LayerIdx)->CFBAR = (pLayerCfg->FBStartAdress);
if (pLayerCfg->PixelFormat == LTDC_PIXEL_FORMAT_ARGB8888) {
tmp = 4;
}
else if (pLayerCfg->PixelFormat == LTDC_PIXEL_FORMAT_RGB888) {
tmp = 3;
}
else if ((pLayerCfg->PixelFormat == LTDC_PIXEL_FORMAT_ARGB4444) || \
(pLayerCfg->PixelFormat == LTDC_PIXEL_FORMAT_RGB565) || \
(pLayerCfg->PixelFormat == LTDC_PIXEL_FORMAT_ARGB1555) || \
(pLayerCfg->PixelFormat == LTDC_PIXEL_FORMAT_AL88)) {
tmp = 2;
}
else {
tmp = 1;
}
/* Configures the color frame buffer pitch in byte */
LTDC_LAYER(hltdc, LayerIdx)->CFBLR &= ~(LTDC_LxCFBLR_CFBLL | LTDC_LxCFBLR_CFBP);
LTDC_LAYER(hltdc, LayerIdx)->CFBLR = (((pLayerCfg->ImageWidth * tmp) << 16) | (((pLayerCfg->WindowX1 - pLayerCfg->WindowX0) * tmp) + 3));
/* Configures the frame buffer line number */
LTDC_LAYER(hltdc, LayerIdx)->CFBLNR &= ~(LTDC_LxCFBLNR_CFBLNBR);
LTDC_LAYER(hltdc, LayerIdx)->CFBLNR = (pLayerCfg->ImageHeight);
/* Enable LTDC_Layer by setting LEN bit */
LTDC_LAYER(hltdc, LayerIdx)->CR |= (uint32_t)LTDC_LxCR_LEN;
}
void STM32F7_Ltdc_LayerConfiguration(LTDC_HandleTypeDef *hltdc, LTDC_LayerCfgTypeDef *pLayerCfg, uint32_t LayerIdx) {
/* Copy new layer configuration into handle structure */
hltdc->LayerCfg[LayerIdx] = *pLayerCfg;
/* Configure the LTDC Layer */
STM32F7_Ltdc_SetConfiguration(hltdc, pLayerCfg, LayerIdx);
/* Sets the Reload type */
hltdc->Instance->SRCR = LTDC_SRCR_IMR;
}
bool STM32F7_Display_Initialize() {
// InitializeConfiguration
static LTDC_HandleTypeDef hltdc_F;
LTDC_LayerCfgTypeDef pLayerCfg;
const uint32_t STM32F7_DISPLAY_CLOCKDIVS[4] = { 2, 4, 8, 16 };
uint32_t pll_saiIn;
uint32_t pll_saiQ;
uint32_t pll_saiP;
uint32_t pll_saiR;
uint32_t div;
uint32_t clockMHz;
RCC->CR &= ~(RCC_CR_PLLSAION);
pll_saiQ = (RCC->PLLSAICFGR >> 24) & 0x0F;
pll_saiP = (RCC->PLLSAICFGR >> 16) & 0x03;
pll_saiR = 2;
div = 0;
pll_saiIn = STM32F7_SYSTEM_CLOCK_HZ / 1000000; // In MHz
while (true) {
clockMHz = (pll_saiIn / pll_saiR) / STM32F7_DISPLAY_CLOCKDIVS[div];
if (clockMHz > (STM32F7_Display_GetPixelClockDivider() / 1000)) {
pll_saiR++;
if (pll_saiR > 7) {
pll_saiR = 7;
div++;
}
if (div > 3) {
// clk is not in range, set default
// 216 / 5 / STM32F7_DISPLAY_CLOCKDIVS[div] = 216 / 5 / 4 = 10.8MHz
div = 1;
pll_saiR = 5;
break;
}
}
else {
// Found good clk
break;
}
}
STM32F7_Time_Delay(nullptr, 0x10000);
RCC->PLLSAICFGR = ((pll_saiIn) << 6) | ((pll_saiP) << 16) | ((pll_saiQ) << 24) | ((pll_saiR) << 28);
MODIFY_REG(RCC->DCKCFGR1, RCC_DCKCFGR1_PLLSAIDIVR, (uint32_t)(div << 16));
RCC->CR |= (RCC_CR_PLLSAION);
STM32F7_Time_Delay(nullptr, 0x10000);
RCC->APB2ENR |= RCC_APB2ENR_LTDCEN;
//HorizontalSyncPolarity
if (m_STM32F7_DisplayHorizontalSyncPolarity == false)
hltdc_F.Init.HSPolarity = LTDC_HSPOLARITY_AL;
else
hltdc_F.Init.HSPolarity = LTDC_HSPOLARITY_AH;
//VerticalSyncPolarity
if (m_STM32F7_DisplayVerticalSyncPolarity == false)
hltdc_F.Init.VSPolarity = LTDC_VSPOLARITY_AL;
else
hltdc_F.Init.VSPolarity = LTDC_VSPOLARITY_AH;
//OutputEnablePolarity
if (m_STM32F7_DisplayOutputEnablePolarity == false)
hltdc_F.Init.DEPolarity = LTDC_DEPOLARITY_AL;
else
hltdc_F.Init.DEPolarity = LTDC_DEPOLARITY_AH;
//OutputEnablePolarity
if (m_STM32F7_DisplayPixelPolarity == false)
hltdc_F.Init.PCPolarity = LTDC_PCPOLARITY_IPC;
else
hltdc_F.Init.PCPolarity = LTDC_GCR_PCPOL;
/* The RK043FN48H LCD 480x272 is selected */
/* Timing Configuration */
hltdc_F.Init.HorizontalSync = (m_STM32F7_DisplayHorizontalSyncPulseWidth - 1);
hltdc_F.Init.VerticalSync = (m_STM32F7_DisplayVerticalSyncPulseWidth - 1);
hltdc_F.Init.AccumulatedHBP = (m_STM32F7_DisplayHorizontalSyncPulseWidth + m_STM32F7_DisplayHorizontalBackPorch - 1);
hltdc_F.Init.AccumulatedVBP = (m_STM32F7_DisplayVerticalSyncPulseWidth + m_STM32F7_DisplayVerticalBackPorch - 1);
hltdc_F.Init.AccumulatedActiveH = (m_STM32F7_DisplayHeight + m_STM32F7_DisplayVerticalSyncPulseWidth + m_STM32F7_DisplayVerticalBackPorch - 1);
hltdc_F.Init.AccumulatedActiveW = (m_STM32F7_DisplayWidth + m_STM32F7_DisplayHorizontalSyncPulseWidth + m_STM32F7_DisplayHorizontalBackPorch - 1);
hltdc_F.Init.TotalHeigh = (m_STM32F7_DisplayHeight + m_STM32F7_DisplayVerticalSyncPulseWidth + m_STM32F7_DisplayVerticalBackPorch + m_STM32F7_DisplayVerticalFrontPorch - 1);
hltdc_F.Init.TotalWidth = (m_STM32F7_DisplayWidth + m_STM32F7_DisplayHorizontalSyncPulseWidth + m_STM32F7_DisplayHorizontalBackPorch + m_STM32F7_DisplayHorizontalFrontPorch - 1);
/* Layer1 Configuration ------------------------------------------------------*/
/* Windowing configuration */
/* In this case all the active display area is used to display a picture then :
Horizontal start = horizontal synchronization + Horizontal back porch = 43
Vertical start = vertical synchronization + vertical back porch = 12
Horizontal stop = Horizontal start + window width -1 = 43 + 480 -1
Vertical stop = Vertical start + window height -1 = 12 + 272 -1 */
pLayerCfg.WindowX0 = 0;
pLayerCfg.WindowX1 = m_STM32F7_DisplayWidth;
pLayerCfg.WindowY0 = 0;
pLayerCfg.WindowY1 = m_STM32F7_DisplayHeight;
/* Configure R,G,B component values for LCD background color : all black background */
hltdc_F.Init.Backcolor.Blue = 0;
hltdc_F.Init.Backcolor.Green = 0;
hltdc_F.Init.Backcolor.Red = 0;
hltdc_F.Instance = LTDC;
/* Pixel Format configuration*/
pLayerCfg.PixelFormat = LTDC_PIXEL_FORMAT_RGB565;
/* Start Address configuration : frame buffer is located at FLASH memory */
if (m_STM32F7_Display_VituralRam == nullptr)
return false;
pLayerCfg.FBStartAdress = (uint32_t)m_STM32F7_Display_VituralRam;
/* Alpha constant (255 == totally opaque) */
pLayerCfg.Alpha = 255;
/* Default Color configuration (configure A,R,G,B component values) : no background color */
pLayerCfg.Alpha0 = 0; /* fully transparent */
pLayerCfg.Backcolor.Blue = 0;
pLayerCfg.Backcolor.Green = 0;
pLayerCfg.Backcolor.Red = 0;
/* Configure blending factors */
pLayerCfg.BlendingFactor1 = LTDC_BLENDING_FACTOR1_CA;
pLayerCfg.BlendingFactor2 = LTDC_BLENDING_FACTOR2_CA;
/* Configure the number of lines and number of pixels per line */
pLayerCfg.ImageWidth = pLayerCfg.WindowX1;
pLayerCfg.ImageHeight = pLayerCfg.WindowY1;
/* Configure the LTDC */
if (!STM32F7_Ltdc_Initialize(&hltdc_F)) {
return false;
}
/* Configure the Layer*/
STM32F7_Ltdc_LayerConfiguration(&hltdc_F, &pLayerCfg, 1);
return true;
}
bool STM32F7_Display_Uninitialize() {
RCC->APB2ENR &= ~RCC_APB2ENR_LTDCEN;
return true;
}
//====================================================
void STM32F7_Display_WriteFormattedChar(uint8_t c) {
if (m_STM32F7_DisplayEnable == false)
return;
if (c == '\f') {
STM32F7_Display_Clear();
STM32F7_Display_TextEnterClearMode();
m_STM32F7_Display_TextColumn = 0;
return;
}
if (c == '\r') {
m_STM32F7_Display_TextColumn = 0;
return;
}
if (c == '\n') {
m_STM32F7_Display_TextColumn = 0;
if (++m_STM32F7_Display_TextRow >= LCD_MAX_ROW) {
m_STM32F7_Display_TextRow = LCD_MAX_ROW - 1;
STM32F7_Display_TextShiftColUp();
}
// clean the new line
for (c = 0; c < (LCD_MAX_COLUMN - 1); c++) {
m_STM32F7_Display_TextBuffer[c][m_STM32F7_Display_TextRow] = ' ';
}
return;
}
STM32F7_Display_PrintChracter(m_STM32F7_Display_TextColumn * 6, m_STM32F7_Display_TextRow * 8, c);
m_STM32F7_Display_TextBuffer[m_STM32F7_Display_TextColumn][m_STM32F7_Display_TextRow] = c;
if (++m_STM32F7_Display_TextColumn >= (LCD_MAX_COLUMN - 1)) {
m_STM32F7_Display_TextColumn = 0;
if (++m_STM32F7_Display_TextRow >= LCD_MAX_ROW) {
m_STM32F7_Display_TextRow = LCD_MAX_ROW - 1;
STM32F7_Display_TextShiftColUp();
}
else {
// clean the new line
for (c = 0; c < LCD_MAX_COLUMN; c++) {
m_STM32F7_Display_TextBuffer[c][m_STM32F7_Display_TextRow] = ' ';
}
}
}
}
//=======================================================
void STM32F7_Display_PaintPixel(uint32_t x, uint32_t y, uint8_t c) {
volatile uint16_t * loc;
if (m_STM32F7_DisplayEnable == false)
return;
if (x >= m_STM32F7_DisplayWidth)
return;
if (y >= m_STM32F7_DisplayHeight)
return;
loc = m_STM32F7_Display_VituralRam + (y *m_STM32F7_DisplayWidth) + (x);
if (c)
*loc = 0x0fff;
else
*loc = 0;
}
//=======================================================
void STM32F7_Display_Paint8HorizontalPixels(uint32_t x, uint32_t y, uint8_t p) {
if (m_STM32F7_DisplayEnable == false)
return;
for (int32_t i = 0; i < 8; i++) {
if (p&(1 << i))
STM32F7_Display_PaintPixel(x, y + i, 1);
else
STM32F7_Display_PaintPixel(x, y + i, 0);//clear
}
}
//===========================================================
void STM32F7_Display_TextEnterClearMode() {
uint32_t r, c;
if (m_STM32F7_DisplayEnable == false)
return;
STM32F7_Display_Clear();
m_STM32F7_Display_TextRow = 0;
m_STM32F7_Display_TextColumn = 0;
for (r = 0; r < LCD_MAX_ROW; r++) {
for (c = 0; c < (LCD_MAX_COLUMN - 1); c++) {
m_STM32F7_Display_TextBuffer[c][r] = '1';
}
}
}
//===========================================================
void STM32F7_Display_PrintChracter(uint32_t x, uint32_t y, uint8_t c) {
uint8_t i;
if (m_STM32F7_DisplayEnable == false)
return;
for (i = 0; i < 5; i++)
STM32F7_Display_Paint8HorizontalPixels(x + i, y, characters[c][i]);
STM32F7_Display_Paint8HorizontalPixels(x + i, y, 0);
}
void STM32F7_Display_TextShiftColUp() {
uint32_t r, c;
if (m_STM32F7_DisplayEnable == false)
return;
// refresh with new data
STM32F7_Display_Clear();
m_STM32F7_Display_TextRow = 0;
m_STM32F7_Display_TextColumn = 0;
for (r = 0; r < (LCD_MAX_ROW - 1); r++) {
for (c = 0; c < LCD_MAX_COLUMN - 1; c++) {
m_STM32F7_Display_TextBuffer[c][r] = m_STM32F7_Display_TextBuffer[c][r + 1];
STM32F7_Display_WriteFormattedChar(m_STM32F7_Display_TextBuffer[c][r]);
}
}
}
void STM32F7_Display_Clear() {
if (m_STM32F7_DisplayEnable == false || m_STM32F7_Display_VituralRam == nullptr)
return;
memset((uint32_t*)m_STM32F7_Display_VituralRam, 0, m_STM32F7_DisplayBufferSize);
}
struct DisplayPins {
STM32F7_Gpio_Pin red[5];
STM32F7_Gpio_Pin green[6];
STM32F7_Gpio_Pin blue[5];
STM32F7_Gpio_Pin hsync;
STM32F7_Gpio_Pin vsync;
STM32F7_Gpio_Pin clock;
STM32F7_Gpio_Pin enable;
};
const DisplayPins displayPins = {
STM32F7_DISPLAY_CONTROLLER_RED_PINS,
STM32F7_DISPLAY_CONTROLLER_GREEN_PINS,
STM32F7_DISPLAY_CONTROLLER_BLUE_PINS,
STM32F7_DISPLAY_CONTROLLER_HSYNC_PIN,
STM32F7_DISPLAY_CONTROLLER_VSYNC_PIN,
STM32F7_DISPLAY_CONTROLLER_CLOCK_PIN,
STM32F7_DISPLAY_CONTROLLER_DATA_ENABLE_PIN,
};
bool STM32F7_Display_SetPinConfiguration(int32_t controllerIndex, bool enable) {
if (enable) {
bool openFailed = false;
// Open red pins
for (auto i = 0; i < 5; i++) {
openFailed |= !STM32F7_GpioInternal_OpenPin(displayPins.red[i].number);
}
// Open green pins
for (auto i = 0; i < 6; i++) {
openFailed |= !STM32F7_GpioInternal_OpenPin(displayPins.green[i].number);
}
// Open blue pins
for (auto i = 0; i < 5; i++) {
openFailed |= !STM32F7_GpioInternal_OpenPin(displayPins.blue[i].number);
}
// Open hsync, vsync, clock pins
openFailed |= !STM32F7_GpioInternal_OpenPin(displayPins.hsync.number);
openFailed |= !STM32F7_GpioInternal_OpenPin(displayPins.vsync.number);
openFailed |= !STM32F7_GpioInternal_OpenPin(displayPins.clock.number);
// Open enable pin
if (displayPins.enable.number != PIN_NONE) {
openFailed |= !STM32F7_GpioInternal_OpenPin(displayPins.enable.number);
}
if (openFailed) {
// Force to close all pin
STM32F7_Display_SetPinConfiguration(controllerIndex, false);
return false;
}
//Config all pins except for Enable pin, (for this pin, only do OpenPin Enable pin to reserve)
//Config Enable pin when SetActive.
for (auto i = 0; i < 5; i++) {
STM32F7_GpioInternal_ConfigurePin(displayPins.red[i].number, STM32F7_Gpio_PortMode::AlternateFunction, STM32F7_Gpio_OutputType::PushPull, STM32F7_Gpio_OutputSpeed::High, STM32F7_Gpio_PullDirection::None, displayPins.red[i].alternateFunction);
}
for (auto i = 0; i < 6; i++) {
STM32F7_GpioInternal_ConfigurePin(displayPins.green[i].number, STM32F7_Gpio_PortMode::AlternateFunction, STM32F7_Gpio_OutputType::PushPull, STM32F7_Gpio_OutputSpeed::High, STM32F7_Gpio_PullDirection::None, displayPins.green[i].alternateFunction);
}
for (auto i = 0; i < 5; i++) {
STM32F7_GpioInternal_ConfigurePin(displayPins.blue[i].number, STM32F7_Gpio_PortMode::AlternateFunction, STM32F7_Gpio_OutputType::PushPull, STM32F7_Gpio_OutputSpeed::High, STM32F7_Gpio_PullDirection::None, displayPins.blue[i].alternateFunction);
}
STM32F7_GpioInternal_ConfigurePin(displayPins.hsync.number, STM32F7_Gpio_PortMode::AlternateFunction, STM32F7_Gpio_OutputType::PushPull, STM32F7_Gpio_OutputSpeed::High, STM32F7_Gpio_PullDirection::None, displayPins.hsync.alternateFunction);
STM32F7_GpioInternal_ConfigurePin(displayPins.vsync.number, STM32F7_Gpio_PortMode::AlternateFunction, STM32F7_Gpio_OutputType::PushPull, STM32F7_Gpio_OutputSpeed::High, STM32F7_Gpio_PullDirection::None, displayPins.vsync.alternateFunction);
STM32F7_GpioInternal_ConfigurePin(displayPins.clock.number, STM32F7_Gpio_PortMode::AlternateFunction, STM32F7_Gpio_OutputType::PushPull, STM32F7_Gpio_OutputSpeed::High, STM32F7_Gpio_PullDirection::None, displayPins.clock.alternateFunction);
}
else {
for (auto i = 0; i < 5; i++) {
STM32F7_GpioInternal_ClosePin(displayPins.red[i].number);
}
for (auto i = 0; i < 6; i++) {
STM32F7_GpioInternal_ClosePin(displayPins.green[i].number);
}
for (auto i = 0; i < 5; i++) {
STM32F7_GpioInternal_ClosePin(displayPins.blue[i].number);
}
STM32F7_GpioInternal_ClosePin(displayPins.hsync.number);
STM32F7_GpioInternal_ClosePin(displayPins.vsync.number);
STM32F7_GpioInternal_ClosePin(displayPins.clock.number);
STM32F7_GpioInternal_ClosePin(displayPins.enable.number);
}
return true;
}
uint32_t* STM32F7_Display_GetFrameBuffer() {
return (uint32_t*)m_STM32F7_Display_VituralRam;
}
int32_t STM32F7_Display_GetWidth() {
int32_t width = m_STM32F7_DisplayWidth;
int32_t height = m_STM32F7_DisplayHeight;
STM32F7_Display_GetRotatedDimensions(&width, &height);
return width;
}
int32_t STM32F7_Display_GetHeight() {
int32_t width = m_STM32F7_DisplayWidth;
int32_t height = m_STM32F7_DisplayHeight;
STM32F7_Display_GetRotatedDimensions(&width, &height);
return height;
}
uint32_t STM32F7_Display_GetPixelClockDivider() {
return m_STM32F7_DisplayPixelClockRateKHz;
}
int32_t STM32F7_Display_GetOrientation() {
return m_STM32F7_Display_CurrentRotation;
}
void STM32F7_Display_BitBltEx(int32_t x, int32_t y, int32_t width, int32_t height, uint32_t data[]) {
int32_t xTo, yTo, xFrom, yFrom;
int32_t xOffset = x;
int32_t yOffset = y;
uint16_t *from = (uint16_t *)data;
uint16_t *to = (uint16_t *)m_STM32F7_Display_VituralRam;
int32_t screenWidth = m_STM32F7_DisplayWidth;
int32_t screenHeight = m_STM32F7_DisplayHeight;
int32_t startPx, toAddition;
if (m_STM32F7_DisplayEnable == false)
return;
switch (m_STM32F7_Display_CurrentRotation) {
case STM32F7xx_LCD_Rotation::rotateNormal_0:
if (xOffset == 0 && yOffset == 0 &&
width == screenWidth && height == screenHeight) {
memcpy(to, from, (screenWidth*screenHeight * 2));
}
else {
for (yTo = yOffset; yTo < (yOffset + height); yTo++) {
memcpy((void*)(to + yTo * screenWidth + xOffset), (void*)(from), (width * 2));
from += width;
}
}
break;
case STM32F7xx_LCD_Rotation::rotateCCW_90:
startPx = yOffset * screenHeight;
xFrom = xOffset + width;
yTo = screenHeight - xOffset - width;
xTo = yOffset;
to += yTo * screenWidth + xTo;
toAddition = screenWidth - height;
for (; yTo < (screenHeight - xOffset); yTo++) {
xFrom--;
yFrom = startPx + xFrom;
for (xTo = yOffset; xTo < (yOffset + height); xTo++) {
*to++ = from[yFrom];
yFrom += screenHeight;
}
to += toAddition;
}
break;
case STM32F7xx_LCD_Rotation::rotateCW_90:
startPx = (yOffset + height - 1) * screenHeight;
xFrom = xOffset;
yTo = xOffset;
xTo = screenWidth - yOffset - height;
to += yTo * screenWidth + xTo;
toAddition = screenWidth - height;
for (; yTo < (xOffset + width); yTo++) {
yFrom = startPx + xFrom;
for (xTo = screenWidth - yOffset - height; xTo < (screenWidth - yOffset); xTo++) {
*to++ = from[yFrom];
yFrom -= screenHeight;
}
to += toAddition;
xFrom++;
}
break;
case STM32F7xx_LCD_Rotation::rotate_180:
xFrom = (yOffset + height - 1) * screenWidth + xOffset + width;
yTo = screenHeight - yOffset - height;
xTo = screenWidth - xOffset - width;
to += yTo * screenWidth + xTo;
toAddition = screenWidth - width;
for (; yTo < (screenHeight - yOffset); yTo++) {
for (xTo = screenWidth - xOffset - width; xTo < (screenWidth - xOffset); xTo++) {
xFrom--;
*to++ = from[xFrom];
}
to += toAddition;
xFrom -= toAddition;
}
break;
}
}
void STM32F7_Display_WriteChar(uint8_t c, int32_t row, int32_t col) {
m_STM32F7_Display_TextRow = row;
m_STM32F7_Display_TextColumn = col;
STM32F7_Display_WriteFormattedChar(c);
}
void STM32F7_Display_GetRotatedDimensions(int32_t *screenWidth, int32_t *screenHeight) {
switch (m_STM32F7_Display_CurrentRotation) {
case STM32F7xx_LCD_Rotation::rotateNormal_0:
case STM32F7xx_LCD_Rotation::rotate_180:
*screenWidth = m_STM32F7_DisplayWidth;
*screenHeight = m_STM32F7_DisplayHeight;
break;
case STM32F7xx_LCD_Rotation::rotateCCW_90:
case STM32F7xx_LCD_Rotation::rotateCW_90:
*screenWidth = m_STM32F7_DisplayHeight;
*screenHeight = m_STM32F7_DisplayWidth;
break;
}
}
TinyCLR_Result STM32F7_Display_Acquire(const TinyCLR_Display_Controller* self) {
if (displayInitializeCount == 0) {
m_STM32F7_Display_CurrentRotation = STM32F7xx_LCD_Rotation::rotateNormal_0;
auto controllerIndex = 0;
if (!STM32F7_Display_SetPinConfiguration(controllerIndex, true)) {
return TinyCLR_Result::SharingViolation;
}
}
displayInitializeCount++;
return TinyCLR_Result::Success;
}
TinyCLR_Result STM32F7_Display_Release(const TinyCLR_Display_Controller* self) {
if (displayInitializeCount == 0) return TinyCLR_Result::InvalidOperation;
displayInitializeCount--;
if (displayInitializeCount == 0) {
STM32F7_Display_Uninitialize();
auto controllerIndex = 0;
STM32F7_Display_SetPinConfiguration(controllerIndex, false);
m_STM32F7_DisplayEnable = false;
if (m_STM32F7_Display_buffer != nullptr) {
auto memoryProvider = (const TinyCLR_Memory_Manager*)apiManager->FindDefault(apiManager, TinyCLR_Api_Type::MemoryManager);
memoryProvider->Free(memoryProvider, m_STM32F7_Display_buffer);
m_STM32F7_Display_buffer = nullptr;
}
}
return TinyCLR_Result::Success;
}
TinyCLR_Result STM32F7_Display_Enable(const TinyCLR_Display_Controller* self) {
if (m_STM32F7_DisplayEnable || STM32F7_Display_Initialize()) {
m_STM32F7_DisplayEnable = true;
return TinyCLR_Result::Success;
}
return TinyCLR_Result::InvalidOperation;
}
TinyCLR_Result STM32F7_Display_Disable(const TinyCLR_Display_Controller* self) {
STM32F7_Display_Uninitialize();
m_STM32F7_DisplayEnable = false;
return TinyCLR_Result::Success;
}
TinyCLR_Result STM32F7_Display_SetConfiguration(const TinyCLR_Display_Controller* self, TinyCLR_Display_DataFormat dataFormat, uint32_t width, uint32_t height, const void* configuration) {
if (dataFormat != TinyCLR_Display_DataFormat::Rgb565) return TinyCLR_Result::NotSupported;
m_STM32F7_DisplayWidth = width;
m_STM32F7_DisplayHeight = height;
if (configuration != nullptr) {
auto& cfg = *(const TinyCLR_Display_ParallelConfiguration*)configuration;
m_STM32F7_DisplayOutputEnableIsFixed = cfg.DataEnableIsFixed;
m_STM32F7_DisplayOutputEnablePolarity = cfg.DataEnablePolarity;
m_STM32F7_DisplayPixelPolarity = cfg.PixelPolarity;
m_STM32F7_DisplayPixelClockRateKHz = cfg.PixelClockRate / 1000;
m_STM32F7_DisplayHorizontalSyncPolarity = cfg.HorizontalSyncPolarity;
m_STM32F7_DisplayHorizontalSyncPulseWidth = cfg.HorizontalSyncPulseWidth;
m_STM32F7_DisplayHorizontalFrontPorch = cfg.HorizontalFrontPorch;
m_STM32F7_DisplayHorizontalBackPorch = cfg.HorizontalBackPorch;
m_STM32F7_DisplayVerticalSyncPolarity = cfg.VerticalSyncPolarity;
m_STM32F7_DisplayVerticalSyncPulseWidth = cfg.VerticalSyncPulseWidth;
m_STM32F7_DisplayVerticalFrontPorch = cfg.VerticalFrontPorch;
m_STM32F7_DisplayVerticalBackPorch = cfg.VerticalBackPorch;
switch (dataFormat) {
case TinyCLR_Display_DataFormat::Rgb565:
m_STM32F7_DisplayBufferSize = width * height * 2;
break;
default:
// TODO 8 - 24 - 32 bits
break;
}
auto memoryProvider = (const TinyCLR_Memory_Manager*)apiManager->FindDefault(apiManager, TinyCLR_Api_Type::MemoryManager);
if (m_STM32F7_Display_buffer != nullptr) {
memoryProvider->Free(memoryProvider, m_STM32F7_Display_buffer);
m_STM32F7_Display_buffer = nullptr;
}
m_STM32F7_Display_buffer = (uint32_t*)memoryProvider->Allocate(memoryProvider, m_STM32F7_DisplayBufferSize + 8);
if (m_STM32F7_Display_buffer == nullptr) {
return TinyCLR_Result::OutOfMemory;
}
m_STM32F7_Display_VituralRam = (uint16_t*)((((uint32_t)m_STM32F7_Display_buffer) + (7)) & (~((uint32_t)(7))));
// Set displayPins.enable following m_STM32F7_DisplayOutputEnableIsFixed
if (displayPins.enable.number != PIN_NONE) {
if (m_STM32F7_DisplayOutputEnableIsFixed) {
STM32F7_GpioInternal_ConfigurePin(displayPins.enable.number, STM32F7_Gpio_PortMode::GeneralPurposeOutput, STM32F7_Gpio_OutputType::PushPull, STM32F7_Gpio_OutputSpeed::High, STM32F7_Gpio_PullDirection::None, STM32F7_Gpio_AlternateFunction::AF0);
STM32F7_GpioInternal_WritePin(displayPins.enable.number, m_STM32F7_DisplayOutputEnablePolarity);
}
else {
STM32F7_GpioInternal_ConfigurePin(displayPins.enable.number, STM32F7_Gpio_PortMode::AlternateFunction, STM32F7_Gpio_OutputType::PushPull, STM32F7_Gpio_OutputSpeed::High, STM32F7_Gpio_PullDirection::None, displayPins.enable.alternateFunction);
}
}
}
return TinyCLR_Result::Success;
}
TinyCLR_Result STM32F7_Display_GetConfiguration(const TinyCLR_Display_Controller* self, TinyCLR_Display_DataFormat& dataFormat, uint32_t& width, uint32_t& height, void* configuration) {
dataFormat = TinyCLR_Display_DataFormat::Rgb565;
width = m_STM32F7_DisplayWidth;
height = m_STM32F7_DisplayHeight;
if (configuration != nullptr) {
auto& cfg = *(TinyCLR_Display_ParallelConfiguration*)configuration;
cfg.DataEnableIsFixed = m_STM32F7_DisplayOutputEnableIsFixed;
cfg.DataEnablePolarity = m_STM32F7_DisplayOutputEnablePolarity;
cfg.PixelPolarity = m_STM32F7_DisplayPixelPolarity;
cfg.PixelClockRate = m_STM32F7_DisplayPixelClockRateKHz * 1000;
cfg.HorizontalSyncPolarity = m_STM32F7_DisplayHorizontalSyncPolarity;
cfg.HorizontalSyncPulseWidth = m_STM32F7_DisplayHorizontalSyncPulseWidth;
cfg.HorizontalFrontPorch = m_STM32F7_DisplayHorizontalFrontPorch;
cfg.HorizontalBackPorch = m_STM32F7_DisplayHorizontalBackPorch;
cfg.VerticalSyncPolarity = m_STM32F7_DisplayVerticalSyncPolarity;
cfg.VerticalSyncPulseWidth = m_STM32F7_DisplayVerticalSyncPulseWidth;
cfg.VerticalFrontPorch = m_STM32F7_DisplayVerticalFrontPorch;
cfg.VerticalBackPorch = m_STM32F7_DisplayVerticalBackPorch;
return TinyCLR_Result::Success;
}
return TinyCLR_Result::InvalidOperation;
}
TinyCLR_Result STM32F7_Display_DrawBuffer(const TinyCLR_Display_Controller* self, uint32_t x, uint32_t y, uint32_t width, uint32_t height, const uint8_t* data) {
STM32F7_Display_BitBltEx(x, y, width, height, (uint32_t*)data);
return TinyCLR_Result::Success;
}
TinyCLR_Result STM32F7_Display_DrawPixel(const TinyCLR_Display_Controller* self, uint32_t x, uint32_t y, uint64_t color) {
volatile uint16_t * loc;
if (m_STM32F7_DisplayEnable == false || x >= m_STM32F7_DisplayWidth || y >= m_STM32F7_DisplayHeight)
return TinyCLR_Result::InvalidOperation;
loc = m_STM32F7_Display_VituralRam + (y *m_STM32F7_DisplayWidth) + (x);
*loc = static_cast<uint16_t>(color & 0xFFFF);
return TinyCLR_Result::Success;
}
TinyCLR_Result STM32F7_Display_DrawString(const TinyCLR_Display_Controller* self, const char* data, size_t length) {
for (size_t i = 0; i < length; i++)
STM32F7_Display_WriteFormattedChar(data[i]);
return TinyCLR_Result::Success;
}
TinyCLR_Display_DataFormat dataFormats[] = { TinyCLR_Display_DataFormat::Rgb565 };
TinyCLR_Result STM32F7_Display_GetCapabilities(const TinyCLR_Display_Controller* self, TinyCLR_Display_InterfaceType& type, const TinyCLR_Display_DataFormat*& supportedDataFormats, size_t& supportedDataFormatCount) {
type = TinyCLR_Display_InterfaceType::Parallel;
supportedDataFormatCount = SIZEOF_ARRAY(dataFormats);
supportedDataFormats = dataFormats;
return TinyCLR_Result::Success;
}
const char* displayApiNames[TOTAL_DISPLAY_CONTROLLERS] = {
"GHIElectronics.TinyCLR.NativeApis.STM32F7.DisplayController\\0"
};
void STM32F7_Display_AddApi(const TinyCLR_Api_Manager* apiManager) {
for (auto i = 0; i < TOTAL_DISPLAY_CONTROLLERS; i++) {
displayControllers[i].ApiInfo = &displayApi[i];
displayControllers[i].Acquire = &STM32F7_Display_Acquire;
displayControllers[i].Release = &STM32F7_Display_Release;
displayControllers[i].Enable = &STM32F7_Display_Enable;
displayControllers[i].Disable = &STM32F7_Display_Disable;
displayControllers[i].SetConfiguration = &STM32F7_Display_SetConfiguration;
displayControllers[i].GetConfiguration = &STM32F7_Display_GetConfiguration;
displayControllers[i].GetCapabilities = &STM32F7_Display_GetCapabilities;
displayControllers[i].DrawBuffer = &STM32F7_Display_DrawBuffer;
displayControllers[i].DrawPixel = &STM32F7_Display_DrawPixel;
displayControllers[i].DrawString = &STM32F7_Display_DrawString;
displayApi[i].Author = "GHI Electronics, LLC";
displayApi[i].Name = displayApiNames[i];
displayApi[i].Type = TinyCLR_Api_Type::DisplayController;
displayApi[i].Version = 0;
displayApi[i].Implementation = &displayControllers[i];
displayApi[i].State = nullptr;
apiManager->Add(apiManager, &displayApi[i]);
}
displayInitializeCount = 0;
m_STM32F7_Display_buffer = nullptr;
m_STM32F7_DisplayEnable = false;
apiManager->SetDefaultName(apiManager, TinyCLR_Api_Type::DisplayController, displayApi[0].Name);
}
void STM32F7_Display_Reset() {
STM32F7_Display_Clear();
if (m_STM32F7_DisplayEnable)
STM32F7_Display_Release(&displayControllers[0]);
m_STM32F7_DisplayEnable = false;
displayInitializeCount = 0;
m_STM32F7_Display_buffer = nullptr;
m_STM32F7_Display_TextRow = 0;
m_STM32F7_Display_TextColumn = 0;
}
#endif
| 39.109663 | 260 | 0.659582 | valoni |
0589e4961678090c69690fa004d11e4d14338115 | 12,390 | cpp | C++ | tests/helics/core/InfoClass-tests.cpp | corinnegroth/HELICS | b8eda371b081a7d391d019c14bba5cf5042ae590 | [
"BSD-3-Clause"
] | null | null | null | tests/helics/core/InfoClass-tests.cpp | corinnegroth/HELICS | b8eda371b081a7d391d019c14bba5cf5042ae590 | [
"BSD-3-Clause"
] | null | null | null | tests/helics/core/InfoClass-tests.cpp | corinnegroth/HELICS | b8eda371b081a7d391d019c14bba5cf5042ae590 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2017-2020,
Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See
the top-level NOTICE for additional details. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
*/
#include "helics/core/BasicHandleInfo.hpp"
#include "helics/core/EndpointInfo.hpp"
#include "helics/core/FilterInfo.hpp"
#include "helics/core/NamedInputInfo.hpp"
#include "gtest/gtest.h"
TEST(InfoClass_tests, basichandleinfo_test)
{
// All default values
helics::BasicHandleInfo defHnd;
EXPECT_TRUE(!defHnd.handle.isValid());
EXPECT_TRUE(!defHnd.local_fed_id.isValid());
EXPECT_TRUE(defHnd.handleType == helics::handle_type::unknown);
EXPECT_EQ(defHnd.flags, 0);
EXPECT_TRUE(defHnd.key.empty());
EXPECT_TRUE(defHnd.type.empty());
EXPECT_TRUE(defHnd.units.empty());
// Constructor with last parameter default value
helics::BasicHandleInfo hnd1(
helics::global_federate_id(15),
helics::interface_handle(10),
helics::handle_type::endpoint,
"key",
"type",
"units");
EXPECT_EQ(hnd1.getInterfaceHandle().baseValue(), 10);
EXPECT_EQ(hnd1.getFederateId().baseValue(), 15);
EXPECT_TRUE(!hnd1.local_fed_id.isValid());
EXPECT_TRUE(hnd1.handleType == helics::handle_type::endpoint);
EXPECT_EQ(hnd1.flags, 0);
EXPECT_EQ(hnd1.key, "key");
EXPECT_EQ(hnd1.type, "type");
EXPECT_EQ(hnd1.units, "units");
// Constructor overriding last parameter default value
helics::BasicHandleInfo hnd2(
helics::global_federate_id(1500),
helics::interface_handle(100),
helics::handle_type::endpoint,
"key",
"type",
"units");
EXPECT_EQ(hnd2.getInterfaceHandle().baseValue(), 100);
EXPECT_EQ(hnd2.getFederateId().baseValue(), 1500);
EXPECT_TRUE(!hnd2.local_fed_id.isValid());
EXPECT_TRUE(hnd2.handleType == helics::handle_type::endpoint);
EXPECT_EQ(hnd1.flags, 0);
EXPECT_EQ(hnd2.key, "key");
EXPECT_EQ(hnd2.type, "type");
EXPECT_EQ(hnd2.units, "units");
// Test handles created with HANDLE_FILTER
// Source filter handle
// destFilter should be false, and target should be equal to what was passed in for units
helics::BasicHandleInfo srcFiltHnd(
helics::global_federate_id(2),
helics::interface_handle(1),
helics::handle_type::filter,
"key",
"type_in",
"type_out");
EXPECT_EQ(srcFiltHnd.getInterfaceHandle().baseValue(), 1);
EXPECT_EQ(srcFiltHnd.getFederateId().baseValue(), 2);
EXPECT_TRUE(!srcFiltHnd.local_fed_id.isValid());
EXPECT_TRUE(srcFiltHnd.handleType == helics::handle_type::filter);
EXPECT_EQ(hnd1.flags, 0);
EXPECT_EQ(srcFiltHnd.key, "key");
EXPECT_EQ(srcFiltHnd.type_in, "type_in");
EXPECT_EQ(srcFiltHnd.type_out, "type_out");
// Destination filter handle
// destFilter should be true, and target should be equal to what was passed in for units
helics::BasicHandleInfo dstFiltHnd(
helics::global_federate_id(3),
helics::interface_handle(7),
helics::handle_type::filter,
"key",
"type_in",
"type_out");
EXPECT_EQ(dstFiltHnd.getInterfaceHandle().baseValue(), 7);
EXPECT_EQ(dstFiltHnd.getFederateId().baseValue(), 3);
EXPECT_TRUE(!dstFiltHnd.local_fed_id.isValid());
EXPECT_TRUE(dstFiltHnd.handleType == helics::handle_type::filter);
EXPECT_EQ(dstFiltHnd.key, "key");
EXPECT_EQ(dstFiltHnd.type_in, "type_in");
EXPECT_EQ(dstFiltHnd.type_out, "type_out");
}
TEST(InfoClass_tests, endpointinfo_test)
{
// Mostly testing ordering of message sorting and maxTime function arguments
helics::Time maxT = helics::Time::maxVal();
helics::Time minT = helics::Time::minVal();
helics::Time zeroT = helics::Time::zeroVal();
// helics::Time eps = helics::Time::epsilon ();
auto msg_time_max = std::make_unique<helics::Message>();
msg_time_max->data = "maxT";
msg_time_max->original_source = "aFed";
msg_time_max->time = maxT;
auto msg_time_min = std::make_unique<helics::Message>();
msg_time_min->data = "minT";
msg_time_min->original_source = "aFed";
msg_time_min->time = minT;
auto msg_time_zero = std::make_unique<helics::Message>();
msg_time_zero->data = "zeroT";
msg_time_zero->original_source = "aFed";
msg_time_zero->time = zeroT;
auto msg_time_one_a = std::make_unique<helics::Message>();
msg_time_one_a->data = "oneAT";
msg_time_one_a->original_source = "aFed";
msg_time_one_a->time = helics::Time(1);
auto msg_time_one_b = std::make_unique<helics::Message>();
msg_time_one_b->data = "oneBT";
msg_time_one_b->original_source = "bFed";
msg_time_one_b->time = helics::Time(1);
helics::EndpointInfo endPI(
{helics::global_federate_id(5), helics::interface_handle(13)}, "name", "type");
EXPECT_EQ(endPI.id.handle.baseValue(), 13);
EXPECT_EQ(endPI.id.fed_id.baseValue(), 5);
EXPECT_EQ(endPI.key, "name");
EXPECT_EQ(endPI.type, "type");
// Check proper return values for empty queue
// size 0 for any time given
// first message time is the max possible
// nullptr for getting a message
EXPECT_EQ(endPI.queueSize(minT), 0);
EXPECT_EQ(endPI.queueSize(maxT), 0);
EXPECT_EQ(endPI.firstMessageTime(), maxT);
EXPECT_TRUE(endPI.getMessage(minT) == nullptr);
EXPECT_TRUE(endPI.getMessage(maxT) == nullptr);
// Add a message at the max time possible
endPI.addMessage(std::move(msg_time_max));
EXPECT_EQ(endPI.queueSize(minT), 0);
EXPECT_EQ(endPI.queueSize(maxT), 1);
EXPECT_EQ(endPI.firstMessageTime(), maxT);
// Add a message at time zero (check if maxTime parameter is working queueSize())
endPI.addMessage(std::move(msg_time_zero));
EXPECT_EQ(endPI.queueSize(minT), 0);
EXPECT_EQ(endPI.queueSize(zeroT), 1);
EXPECT_EQ(endPI.queueSize(maxT), 2);
EXPECT_EQ(endPI.firstMessageTime(), zeroT);
// Add a message at the min time possible
endPI.addMessage(std::move(msg_time_min));
EXPECT_EQ(endPI.queueSize(minT), 1);
EXPECT_EQ(endPI.queueSize(zeroT), 2);
EXPECT_EQ(endPI.queueSize(1), 2);
EXPECT_EQ(endPI.queueSize(maxT), 3);
EXPECT_EQ(endPI.firstMessageTime(), minT);
// Add a message at a time somewhere in between the others
endPI.addMessage(std::move(msg_time_one_b));
EXPECT_EQ(endPI.queueSize(minT), 1);
EXPECT_EQ(endPI.queueSize(zeroT), 2);
EXPECT_EQ(endPI.queueSize(1), 3);
EXPECT_EQ(endPI.queueSize(maxT), 4);
EXPECT_EQ(endPI.firstMessageTime(), minT);
// Test maxTime parameter for getMessage(), and proper dequeuing
auto msg = endPI.getMessage(minT);
EXPECT_EQ(msg->data.to_string(), "minT");
EXPECT_EQ(endPI.queueSize(minT), 0);
EXPECT_EQ(endPI.queueSize(maxT), 3);
EXPECT_TRUE(endPI.getMessage(minT) == nullptr);
// Message at time 0 should now be the first
EXPECT_EQ(endPI.firstMessageTime(), zeroT);
msg = endPI.getMessage(zeroT);
EXPECT_EQ(msg->data.to_string(), "zeroT");
EXPECT_EQ(endPI.queueSize(maxT), 2);
EXPECT_TRUE(endPI.getMessage(zeroT) == nullptr);
// Now message at time 1 (bFed) should be the first
EXPECT_EQ(endPI.firstMessageTime(), helics::Time(1));
EXPECT_EQ(endPI.queueSize(1), 1);
// Insert another message at time 1 (aFed) to test ordering by original source name
endPI.addMessage(std::move(msg_time_one_a));
EXPECT_EQ(endPI.firstMessageTime(), helics::Time(1));
EXPECT_EQ(endPI.queueSize(1), 2);
msg = endPI.getMessage(1);
EXPECT_EQ(msg->data.to_string(), "oneAT");
EXPECT_EQ(endPI.queueSize(1), 1);
msg = endPI.getMessage(1);
EXPECT_EQ(msg->data.to_string(), "oneBT");
EXPECT_EQ(endPI.queueSize(1), 0);
EXPECT_TRUE(endPI.getMessage(1) == nullptr);
// Recreate messages A and B at time 1
msg_time_one_a = std::make_unique<helics::Message>();
msg_time_one_a->data = "oneAT";
msg_time_one_a->original_source = "aFed";
msg_time_one_a->time = helics::Time(1);
msg_time_one_b = std::make_unique<helics::Message>();
msg_time_one_b->data = "oneBT";
msg_time_one_b->original_source = "bFed";
msg_time_one_b->time = helics::Time(1);
// Perform the same source name federate test, but reverse order of add messages
endPI.addMessage(std::move(msg_time_one_a));
endPI.addMessage(std::move(msg_time_one_b));
EXPECT_EQ(endPI.queueSize(1), 2);
msg = endPI.getMessage(1);
EXPECT_EQ(msg->data.to_string(), "oneAT");
EXPECT_EQ(endPI.queueSize(1), 1);
msg = endPI.getMessage(1);
EXPECT_EQ(msg->data.to_string(), "oneBT");
EXPECT_EQ(endPI.queueSize(1), 0);
// Test removing all elements from queue
msg = endPI.getMessage(maxT);
EXPECT_EQ(msg->data.to_string(), "maxT");
EXPECT_EQ(endPI.queueSize(maxT), 0);
EXPECT_TRUE(endPI.getMessage(maxT) == nullptr);
}
TEST(InfoClass_tests, filterinfo_test)
{
// Mostly testing ordering of message sorting and maxTime function arguments
helics::Time maxT = helics::Time::maxVal();
helics::Time minT = helics::Time::minVal();
helics::Time zeroT = helics::Time::zeroVal();
auto msg_time_max = std::make_unique<helics::Message>();
msg_time_max->data = "maxT";
msg_time_max->original_source = "aFed";
msg_time_max->time = maxT;
auto msg_time_min = std::make_unique<helics::Message>();
msg_time_min->data = "minT";
msg_time_min->original_source = "aFed";
msg_time_min->time = minT;
auto msg_time_zero = std::make_unique<helics::Message>();
msg_time_zero->data = "zeroT";
msg_time_zero->original_source = "aFed";
msg_time_zero->time = zeroT;
auto msg_time_one_a = std::make_unique<helics::Message>();
msg_time_one_a->data = "oneAT";
msg_time_one_a->original_source = "aFed";
msg_time_one_a->time = helics::Time(1);
auto msg_time_one_b = std::make_unique<helics::Message>();
msg_time_one_b->data = "oneBT";
msg_time_one_b->original_source = "bFed";
msg_time_one_b->time = helics::Time(1);
helics::FilterInfo filtI(
helics::global_broker_id(5),
helics::interface_handle(13),
"name",
"type_in",
"type_out",
true);
EXPECT_EQ(filtI.handle.baseValue(), 13);
EXPECT_EQ(filtI.core_id.baseValue(), 5);
EXPECT_EQ(filtI.key, "name");
EXPECT_EQ(filtI.inputType, "type_in");
EXPECT_EQ(filtI.outputType, "type_out");
EXPECT_EQ(filtI.dest_filter, true);
}
TEST(InfoClass_tests, inputinfo_test)
{
// SubscriptionInfo is still a WPI, nothing moves data from the queue to current_data
std::shared_ptr<const helics::data_block> ret_data;
helics::NamedInputInfo subI(
helics::global_handle(helics::global_federate_id(5), helics::interface_handle(13)),
"key",
"type",
"units");
EXPECT_EQ(subI.id.handle.baseValue(), 13);
EXPECT_EQ(subI.id.fed_id.baseValue(), 5);
EXPECT_EQ(subI.key, "key");
EXPECT_EQ(subI.type, "type");
EXPECT_EQ(subI.units, "units");
EXPECT_EQ(subI.required, false);
helics::global_handle testHandle(helics::global_federate_id(5), helics::interface_handle(45));
subI.addSource(testHandle, "", "double", std::string());
// No data available, shouldn't get a data_block back
ret_data = subI.getData(0);
EXPECT_TRUE(!ret_data);
auto hello_data = std::make_shared<helics::data_block>("hello world");
subI.addData(testHandle, helics::timeZero, 0, hello_data);
subI.updateTimeInclusive(helics::timeZero);
ret_data = subI.getData(0);
EXPECT_EQ(ret_data->size(), 11U);
EXPECT_EQ(ret_data->to_string(), hello_data->to_string());
auto time_one_data = std::make_shared<helics::data_block>("time one");
auto time_one_repeat_data = std::make_shared<helics::data_block>("time one repeat");
subI.addData(testHandle, 1, 0, time_one_data);
subI.addData(testHandle, 1, 0, time_one_repeat_data);
subI.updateTimeInclusive(1.0);
ret_data = subI.getData(0);
EXPECT_EQ(ret_data->to_string(), "time one repeat");
subI.addData(testHandle, 2, 0, time_one_data);
subI.addData(testHandle, 2, 1, time_one_repeat_data);
subI.updateTimeNextIteration(2.0);
ret_data = subI.getData(0);
EXPECT_EQ(ret_data->to_string(), "time one");
}
| 37.319277 | 114 | 0.684665 | corinnegroth |
0589f2cecd0ff256314827b698400555b73639f0 | 24,672 | cpp | C++ | Tests/DiligentCoreAPITest/src/QueryTest.cpp | Zone-organization/DiligentCore | a9091a1848492ae1aecece3a955badf9367b189f | [
"Apache-2.0"
] | 398 | 2016-04-21T03:38:50.000Z | 2022-03-23T15:27:31.000Z | Tests/DiligentCoreAPITest/src/QueryTest.cpp | Zone-organization/DiligentCore | a9091a1848492ae1aecece3a955badf9367b189f | [
"Apache-2.0"
] | 275 | 2017-12-27T04:11:55.000Z | 2022-03-30T07:35:11.000Z | Tests/DiligentCoreAPITest/src/QueryTest.cpp | Zone-organization/DiligentCore | a9091a1848492ae1aecece3a955badf9367b189f | [
"Apache-2.0"
] | 139 | 2017-09-13T06:19:49.000Z | 2022-03-28T15:01:20.000Z | /*
* Copyright 2019-2021 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include <sstream>
#include <vector>
#include <thread>
#include "TestingEnvironment.hpp"
#include "ThreadSignal.hpp"
#include "gtest/gtest.h"
using namespace Diligent;
using namespace Diligent::Testing;
extern "C"
{
int TestQueryCInterface(void* pQuery);
}
namespace
{
// clang-format off
const std::string QueryTest_ProceduralQuadVS{
R"(
struct PSInput
{
float4 Pos : SV_POSITION;
};
void main(in uint VertId : SV_VertexID,
out PSInput PSIn)
{
float HalfTexel = 0.5 / 512.0;
float size = 0.25;
float4 Pos[4];
Pos[0] = float4(-size-HalfTexel, -size-HalfTexel, 0.0, 1.0);
Pos[1] = float4(-size-HalfTexel, +size-HalfTexel, 0.0, 1.0);
Pos[2] = float4(+size-HalfTexel, -size-HalfTexel, 0.0, 1.0);
Pos[3] = float4(+size-HalfTexel, +size-HalfTexel, 0.0, 1.0);
PSIn.Pos = Pos[VertId];
}
)"
};
const std::string QueryTest_PS{
R"(
struct PSInput
{
float4 Pos : SV_POSITION;
};
float4 main(in PSInput PSIn) : SV_Target
{
return float4(1.0, 0.0, 0.0, 1.0);
}
)"
};
// clang-format on
class QueryTest : public ::testing::Test
{
protected:
static void SetUpTestSuite()
{
auto* pEnv = TestingEnvironment::GetInstance();
auto* pDevice = pEnv->GetDevice();
TextureDesc TexDesc;
TexDesc.Name = "Mips generation test texture";
TexDesc.Type = RESOURCE_DIM_TEX_2D;
TexDesc.Format = TEX_FORMAT_RGBA8_UNORM;
TexDesc.Width = sm_TextureSize;
TexDesc.Height = sm_TextureSize;
TexDesc.BindFlags = BIND_RENDER_TARGET;
TexDesc.MipLevels = 1;
TexDesc.Usage = USAGE_DEFAULT;
RefCntAutoPtr<ITexture> pRenderTarget;
pDevice->CreateTexture(TexDesc, nullptr, &pRenderTarget);
ASSERT_NE(pRenderTarget, nullptr) << "TexDesc:\n"
<< TexDesc;
sm_pRTV = pRenderTarget->GetDefaultView(TEXTURE_VIEW_RENDER_TARGET);
ASSERT_NE(sm_pRTV, nullptr);
GraphicsPipelineStateCreateInfo PSOCreateInfo;
PipelineStateDesc& PSODesc = PSOCreateInfo.PSODesc;
GraphicsPipelineDesc& GraphicsPipeline = PSOCreateInfo.GraphicsPipeline;
PSODesc.Name = "Query command test - procedural quad";
PSODesc.ImmediateContextMask = ~0ull;
PSODesc.PipelineType = PIPELINE_TYPE_GRAPHICS;
GraphicsPipeline.NumRenderTargets = 1;
GraphicsPipeline.RTVFormats[0] = TexDesc.Format;
GraphicsPipeline.PrimitiveTopology = PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_NONE;
GraphicsPipeline.DepthStencilDesc.DepthEnable = False;
ShaderCreateInfo ShaderCI;
ShaderCI.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL;
ShaderCI.ShaderCompiler = pEnv->GetDefaultCompiler(ShaderCI.SourceLanguage);
ShaderCI.UseCombinedTextureSamplers = true;
RefCntAutoPtr<IShader> pVS;
{
ShaderCI.Desc.ShaderType = SHADER_TYPE_VERTEX;
ShaderCI.EntryPoint = "main";
ShaderCI.Desc.Name = "Query test vertex shader";
ShaderCI.Source = QueryTest_ProceduralQuadVS.c_str();
pDevice->CreateShader(ShaderCI, &pVS);
ASSERT_NE(pVS, nullptr);
}
RefCntAutoPtr<IShader> pPS;
{
ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL;
ShaderCI.EntryPoint = "main";
ShaderCI.Desc.Name = "Query test pixel shader";
ShaderCI.Source = QueryTest_PS.c_str();
pDevice->CreateShader(ShaderCI, &pPS);
ASSERT_NE(pVS, nullptr);
}
PSOCreateInfo.pVS = pVS;
PSOCreateInfo.pPS = pPS;
pDevice->CreateGraphicsPipelineState(PSOCreateInfo, &sm_pPSO);
ASSERT_NE(sm_pPSO, nullptr);
}
static void TearDownTestSuite()
{
sm_pPSO.Release();
sm_pRTV.Release();
auto* pEnv = TestingEnvironment::GetInstance();
pEnv->Reset();
}
static void DrawQuad(IDeviceContext* pContext)
{
ITextureView* pRTVs[] = {sm_pRTV};
pContext->SetRenderTargets(1, pRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
const float ClearColor[] = {0.f, 0.f, 0.f, 0.0f};
pContext->ClearRenderTarget(pRTVs[0], ClearColor, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
pContext->SetPipelineState(sm_pPSO);
DrawAttribs drawAttrs{4, DRAW_FLAG_VERIFY_ALL, 32};
pContext->Draw(drawAttrs);
}
static constexpr Uint32 sm_NumTestQueries = 3;
static constexpr Uint32 sm_NumFrames = 5;
void InitTestQueries(IDeviceContext* pContext, std::vector<RefCntAutoPtr<IQuery>>& Queries, const QueryDesc& queryDesc)
{
auto* pEnv = TestingEnvironment::GetInstance();
auto* pDevice = pEnv->GetDevice();
auto deviceInfo = pDevice->GetDeviceInfo();
if (Queries.empty())
{
Queries.resize(sm_NumTestQueries);
for (auto& pQuery : Queries)
{
pDevice->CreateQuery(queryDesc, &pQuery);
ASSERT_NE(pQuery, nullptr) << "Failed to create pipeline stats query";
}
}
// Nested queries are not supported by OpenGL and Vulkan
for (Uint32 i = 0; i < sm_NumTestQueries; ++i)
{
pContext->BeginQuery(Queries[i]);
for (Uint32 j = 0; j < i + 1; ++j)
DrawQuad(pContext);
pContext->EndQuery(Queries[i]);
Queries[i]->GetData(nullptr, 0);
if (deviceInfo.IsMetalDevice())
{
// Metal may not support queries for draw calls.
// Flush() is one of the ways to begin new render pass.
pContext->Flush();
}
}
if (queryDesc.Type == QUERY_TYPE_DURATION)
{
// FinishFrame() must be called to finish the disjoint query
pContext->Flush();
pContext->FinishFrame();
}
pContext->WaitForIdle();
if (deviceInfo.IsGLDevice())
{
// glFinish() is not a guarantee that queries will become available.
// Even using glFenceSync + glClientWaitSync does not help.
for (Uint32 i = 0; i < sm_NumTestQueries; ++i)
{
WaitForQuery(Queries[i]);
}
}
}
static void WaitForQuery(IQuery* pQuery)
{
while (!pQuery->GetData(nullptr, 0))
std::this_thread::sleep_for(std::chrono::microseconds{1});
}
static constexpr Uint32 sm_TextureSize = 512;
static RefCntAutoPtr<ITextureView> sm_pRTV;
static RefCntAutoPtr<IPipelineState> sm_pPSO;
};
RefCntAutoPtr<ITextureView> QueryTest::sm_pRTV;
RefCntAutoPtr<IPipelineState> QueryTest::sm_pPSO;
TEST_F(QueryTest, PipelineStats)
{
const auto& DeviceInfo = TestingEnvironment::GetInstance()->GetDevice()->GetDeviceInfo();
if (!DeviceInfo.Features.PipelineStatisticsQueries)
{
GTEST_SKIP() << "Pipeline statistics queries are not supported by this device";
}
const auto IsGL = DeviceInfo.IsGLDevice();
TestingEnvironment::ScopedReset EnvironmentAutoReset;
auto* pEnv = TestingEnvironment::GetInstance();
for (Uint32 q = 0; q < pEnv->GetNumImmediateContexts(); ++q)
{
auto* pContext = pEnv->GetDeviceContext(q);
if ((pContext->GetDesc().QueueType & COMMAND_QUEUE_TYPE_GRAPHICS) != COMMAND_QUEUE_TYPE_GRAPHICS)
continue;
QueryDesc queryDesc;
queryDesc.Name = "Pipeline stats query";
queryDesc.Type = QUERY_TYPE_PIPELINE_STATISTICS;
std::vector<RefCntAutoPtr<IQuery>> Queries;
for (Uint32 frame = 0; frame < sm_NumFrames; ++frame)
{
InitTestQueries(pContext, Queries, queryDesc);
for (Uint32 i = 0; i < sm_NumTestQueries; ++i)
{
Uint32 DrawCounter = 1 + i;
QueryDataPipelineStatistics QueryData;
auto QueryReady = Queries[i]->GetData(nullptr, 0);
ASSERT_TRUE(QueryReady) << "Query data must be available after idling the context";
QueryReady = Queries[i]->GetData(&QueryData, sizeof(QueryData));
ASSERT_TRUE(QueryReady) << "Query data must be available after idling the context";
if (!IsGL)
{
EXPECT_GE(QueryData.InputVertices, 4 * DrawCounter);
EXPECT_GE(QueryData.InputPrimitives, 2 * DrawCounter);
EXPECT_GE(QueryData.ClippingPrimitives, 2 * DrawCounter);
EXPECT_GE(QueryData.VSInvocations, 4 * DrawCounter);
auto NumPixels = sm_TextureSize * sm_TextureSize / 16;
EXPECT_GE(QueryData.PSInvocations, NumPixels * DrawCounter);
}
EXPECT_GE(QueryData.ClippingInvocations, 2 * DrawCounter);
}
}
}
}
TEST_F(QueryTest, Occlusion)
{
const auto& DeviceInfo = TestingEnvironment::GetInstance()->GetDevice()->GetDeviceInfo();
if (!DeviceInfo.Features.OcclusionQueries)
{
GTEST_SKIP() << "Occlusion queries are not supported by this device";
}
TestingEnvironment::ScopedReset EnvironmentAutoReset;
auto* pEnv = TestingEnvironment::GetInstance();
for (Uint32 q = 0; q < pEnv->GetNumImmediateContexts(); ++q)
{
auto* pContext = pEnv->GetDeviceContext(q);
if ((pContext->GetDesc().QueueType & COMMAND_QUEUE_TYPE_GRAPHICS) != COMMAND_QUEUE_TYPE_GRAPHICS)
continue;
QueryDesc queryDesc;
queryDesc.Name = "Occlusion query";
queryDesc.Type = QUERY_TYPE_OCCLUSION;
std::vector<RefCntAutoPtr<IQuery>> Queries;
for (Uint32 frame = 0; frame < sm_NumFrames; ++frame)
{
InitTestQueries(pContext, Queries, queryDesc);
for (Uint32 i = 0; i < sm_NumTestQueries; ++i)
{
Uint32 DrawCounter = 1 + i;
QueryDataOcclusion QueryData;
auto QueryReady = Queries[i]->GetData(nullptr, 0);
ASSERT_TRUE(QueryReady) << "Query data must be available after idling the context";
QueryReady = Queries[i]->GetData(&QueryData, sizeof(QueryData));
ASSERT_TRUE(QueryReady) << "Query data must be available after idling the context";
auto NumPixels = sm_TextureSize * sm_TextureSize / 16;
EXPECT_GE(QueryData.NumSamples, NumPixels * DrawCounter);
}
}
}
}
TEST_F(QueryTest, BinaryOcclusion)
{
const auto& DeviceInfo = TestingEnvironment::GetInstance()->GetDevice()->GetDeviceInfo();
if (!DeviceInfo.Features.BinaryOcclusionQueries)
{
GTEST_SKIP() << "Binary occlusion queries are not supported by this device";
}
TestingEnvironment::ScopedReset EnvironmentAutoReset;
auto* pEnv = TestingEnvironment::GetInstance();
for (Uint32 q = 0; q < pEnv->GetNumImmediateContexts(); ++q)
{
auto* pContext = pEnv->GetDeviceContext(q);
if ((pContext->GetDesc().QueueType & COMMAND_QUEUE_TYPE_GRAPHICS) != COMMAND_QUEUE_TYPE_GRAPHICS)
continue;
QueryDesc queryDesc;
queryDesc.Name = "Binary occlusion query";
queryDesc.Type = QUERY_TYPE_BINARY_OCCLUSION;
std::vector<RefCntAutoPtr<IQuery>> Queries;
for (Uint32 frame = 0; frame < sm_NumFrames; ++frame)
{
InitTestQueries(pContext, Queries, queryDesc);
for (Uint32 i = 0; i < sm_NumTestQueries; ++i)
{
QueryDataBinaryOcclusion QueryData;
auto QueryReady = Queries[i]->GetData(nullptr, 0);
ASSERT_TRUE(QueryReady) << "Query data must be available after idling the context";
Queries[i]->GetData(&QueryData, sizeof(QueryData));
ASSERT_TRUE(QueryReady) << "Query data must be available after idling the context";
EXPECT_TRUE(QueryData.AnySamplePassed);
}
}
}
}
TEST_F(QueryTest, Timestamp)
{
auto* pEnv = TestingEnvironment::GetInstance();
auto* pDevice = pEnv->GetDevice();
const auto& DeviceInfo = pDevice->GetDeviceInfo();
if (!DeviceInfo.Features.TimestampQueries)
{
GTEST_SKIP() << "Timestamp queries are not supported by this device";
}
TestingEnvironment::ScopedReset EnvironmentAutoReset;
for (Uint32 q = 0; q < pEnv->GetNumImmediateContexts(); ++q)
{
auto* pContext = pEnv->GetDeviceContext(q);
if ((pContext->GetDesc().QueueType & COMMAND_QUEUE_TYPE_GRAPHICS) != COMMAND_QUEUE_TYPE_GRAPHICS)
continue;
QueryDesc queryDesc;
queryDesc.Name = "Timestamp query";
queryDesc.Type = QUERY_TYPE_TIMESTAMP;
RefCntAutoPtr<IQuery> pQueryStart;
pDevice->CreateQuery(queryDesc, &pQueryStart);
ASSERT_NE(pQueryStart, nullptr) << "Failed to create timestamp query";
RefCntAutoPtr<IQuery> pQueryEnd;
pDevice->CreateQuery(queryDesc, &pQueryEnd);
ASSERT_NE(pQueryEnd, nullptr) << "Failed to create timestamp query";
for (Uint32 frame = 0; frame < sm_NumFrames; ++frame)
{
pContext->EndQuery(pQueryStart);
pQueryStart->GetData(nullptr, 0);
DrawQuad(pContext);
pContext->EndQuery(pQueryEnd);
pQueryEnd->GetData(nullptr, 0);
pContext->Flush();
pContext->FinishFrame();
pContext->WaitForIdle();
if (pDevice->GetDeviceInfo().IsGLDevice())
{
// glFinish() is not a guarantee that queries will become available
// Even using glFenceSync + glClientWaitSync does not help.
WaitForQuery(pQueryStart);
WaitForQuery(pQueryEnd);
}
QueryDataTimestamp QueryStartData, QueryEndData;
auto QueryReady = pQueryStart->GetData(nullptr, 0);
ASSERT_TRUE(QueryReady) << "Query data must be available after idling the context";
QueryReady = pQueryStart->GetData(&QueryStartData, sizeof(QueryStartData));
ASSERT_TRUE(QueryReady) << "Query data must be available after idling the context";
QueryReady = pQueryEnd->GetData(nullptr, 0);
ASSERT_TRUE(QueryReady) << "Query data must be available after idling the context";
QueryReady = pQueryEnd->GetData(&QueryEndData, sizeof(QueryEndData), false);
ASSERT_TRUE(QueryReady) << "Query data must be available after idling the context";
EXPECT_EQ(TestQueryCInterface(pQueryEnd.RawPtr()), 0);
EXPECT_TRUE(QueryStartData.Frequency == 0 || QueryEndData.Frequency == 0 || QueryEndData.Counter > QueryStartData.Counter);
}
}
}
TEST_F(QueryTest, Duration)
{
const auto& DeviceInfo = TestingEnvironment::GetInstance()->GetDevice()->GetDeviceInfo();
if (!DeviceInfo.Features.DurationQueries)
{
GTEST_SKIP() << "Duration queries are not supported by this device";
}
TestingEnvironment::ScopedReset EnvironmentAutoReset;
auto* pEnv = TestingEnvironment::GetInstance();
for (Uint32 q = 0; q < pEnv->GetNumImmediateContexts(); ++q)
{
auto* pContext = pEnv->GetDeviceContext(q);
if ((pContext->GetDesc().QueueType & COMMAND_QUEUE_TYPE_GRAPHICS) != COMMAND_QUEUE_TYPE_GRAPHICS)
continue;
QueryDesc queryDesc;
queryDesc.Name = "Duration query";
queryDesc.Type = QUERY_TYPE_DURATION;
std::vector<RefCntAutoPtr<IQuery>> Queries;
for (Uint32 frame = 0; frame < sm_NumFrames; ++frame)
{
InitTestQueries(pContext, Queries, queryDesc);
for (Uint32 i = 0; i < sm_NumTestQueries; ++i)
{
QueryDataDuration QueryData;
auto QueryReady = Queries[i]->GetData(nullptr, 0);
ASSERT_TRUE(QueryReady) << "Query data must be available after idling the context";
Queries[i]->GetData(&QueryData, sizeof(QueryData));
ASSERT_TRUE(QueryReady) << "Query data must be available after idling the context";
EXPECT_TRUE(QueryData.Frequency == 0 || QueryData.Duration > 0);
}
}
}
}
TEST_F(QueryTest, DeferredContexts)
{
auto* const pEnv = TestingEnvironment::GetInstance();
auto* const pDevice = pEnv->GetDevice();
const auto& DeviceInfo = pDevice->GetDeviceInfo();
if (!DeviceInfo.Features.DurationQueries && !DeviceInfo.Features.TimestampQueries)
{
GTEST_SKIP() << "Time queries are not supported by this device";
}
Uint32 NumDeferredCtx = static_cast<Uint32>(pEnv->GetNumDeferredContexts());
if (NumDeferredCtx == 0)
{
GTEST_SKIP() << "Deferred contexts are not supported by this device";
}
TestingEnvironment::ScopedReset EnvironmentAutoReset;
std::vector<RefCntAutoPtr<IQuery>> pDurations;
if (DeviceInfo.Features.DurationQueries)
{
QueryDesc queryDesc;
queryDesc.Name = "Duration query";
queryDesc.Type = QUERY_TYPE_DURATION;
pDurations.resize(NumDeferredCtx);
for (Uint32 i = 0; i < NumDeferredCtx; ++i)
{
pDevice->CreateQuery(queryDesc, &pDurations[i]);
ASSERT_NE(pDurations[i], nullptr);
}
}
std::vector<RefCntAutoPtr<IQuery>> pStartTimestamps, pEndTimestamps;
if (DeviceInfo.Features.TimestampQueries)
{
QueryDesc queryDesc;
queryDesc.Type = QUERY_TYPE_TIMESTAMP;
pStartTimestamps.resize(NumDeferredCtx);
pEndTimestamps.resize(NumDeferredCtx);
for (Uint32 i = 0; i < NumDeferredCtx; ++i)
{
queryDesc.Name = "Start timestamp query";
pDevice->CreateQuery(queryDesc, &pStartTimestamps[i]);
ASSERT_NE(pStartTimestamps[i], nullptr);
queryDesc.Name = "End timestamp query";
pDevice->CreateQuery(queryDesc, &pEndTimestamps[i]);
ASSERT_NE(pEndTimestamps[i], nullptr);
}
}
auto* pSwapChain = pEnv->GetSwapChain();
for (Uint32 q = 0; q < pEnv->GetNumImmediateContexts(); ++q)
{
auto* pImmediateCtx = pEnv->GetDeviceContext(q);
if ((pImmediateCtx->GetDesc().QueueType & COMMAND_QUEUE_TYPE_GRAPHICS) != COMMAND_QUEUE_TYPE_GRAPHICS)
continue;
const float ClearColor[] = {0.25f, 0.5f, 0.75f, 1.0f};
ITextureView* pRTVs[] = {pSwapChain->GetCurrentBackBufferRTV()};
pImmediateCtx->SetRenderTargets(1, pRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
pImmediateCtx->ClearRenderTarget(pRTVs[0], ClearColor, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
std::vector<std::thread> WorkerThreads(NumDeferredCtx);
std::vector<RefCntAutoPtr<ICommandList>> CmdLists(NumDeferredCtx);
std::vector<ICommandList*> CmdListPtrs(NumDeferredCtx);
std::atomic<Uint32> NumCmdListsReady{0};
ThreadingTools::Signal FinishFrameSignal;
ThreadingTools::Signal ExecuteCommandListsSignal;
for (Uint32 i = 0; i < NumDeferredCtx; ++i)
{
WorkerThreads[i] = std::thread(
[&](Uint32 thread_id) //
{
auto* pCtx = pEnv->GetDeferredContext(thread_id);
pCtx->Begin(pImmediateCtx->GetDesc().ContextId);
pCtx->SetRenderTargets(1, pRTVs, nullptr, RESOURCE_STATE_TRANSITION_MODE_VERIFY);
pCtx->SetPipelineState(sm_pPSO);
if (DeviceInfo.Features.DurationQueries)
pCtx->BeginQuery(pDurations[thread_id]);
if (DeviceInfo.Features.TimestampQueries)
pCtx->EndQuery(pStartTimestamps[thread_id]);
DrawAttribs drawAttrs{4, DRAW_FLAG_VERIFY_ALL, 32};
pCtx->Draw(drawAttrs);
if (DeviceInfo.Features.DurationQueries)
pCtx->EndQuery(pDurations[thread_id]);
if (DeviceInfo.Features.TimestampQueries)
pCtx->EndQuery(pEndTimestamps[thread_id]);
pCtx->FinishCommandList(&CmdLists[thread_id]);
CmdListPtrs[thread_id] = CmdLists[thread_id];
// Atomically increment the number of completed threads
const auto NumReadyLists = NumCmdListsReady.fetch_add(1) + 1;
if (NumReadyLists == NumDeferredCtx)
ExecuteCommandListsSignal.Trigger();
FinishFrameSignal.Wait(true, NumDeferredCtx);
// IMPORTANT: In Metal backend FinishFrame must be called from the same
// thread that issued rendering commands.
pCtx->FinishFrame();
},
i);
}
// Wait for the worker threads
ExecuteCommandListsSignal.Wait(true, 1);
pImmediateCtx->ExecuteCommandLists(NumDeferredCtx, CmdListPtrs.data());
FinishFrameSignal.Trigger(true);
for (auto& t : WorkerThreads)
t.join();
pImmediateCtx->WaitForIdle();
for (IQuery* pQuery : pDurations)
{
QueryDataDuration QueryData;
auto QueryReady = pQuery->GetData(nullptr, 0);
EXPECT_TRUE(QueryReady) << "Query data must be available after idling the context";
pQuery->GetData(&QueryData, sizeof(QueryData));
EXPECT_TRUE(QueryReady) << "Query data must be available after idling the context";
EXPECT_TRUE(QueryData.Frequency == 0 || QueryData.Duration > 0);
}
if (DeviceInfo.Features.TimestampQueries)
{
for (Uint32 i = 0; i < NumDeferredCtx; ++i)
{
IQuery* pQueryStart = pStartTimestamps[i];
IQuery* pQueryEnd = pEndTimestamps[i];
QueryDataTimestamp QueryStartData, QueryEndData;
auto QueryReady = pQueryStart->GetData(nullptr, 0);
EXPECT_TRUE(QueryReady) << "Query data must be available after idling the context";
QueryReady = pQueryStart->GetData(&QueryStartData, sizeof(QueryStartData));
EXPECT_TRUE(QueryReady) << "Query data must be available after idling the context";
QueryReady = pQueryEnd->GetData(nullptr, 0);
EXPECT_TRUE(QueryReady) << "Query data must be available after idling the context";
QueryReady = pQueryEnd->GetData(&QueryEndData, sizeof(QueryEndData), false);
EXPECT_TRUE(QueryReady) << "Query data must be available after idling the context";
EXPECT_TRUE(QueryStartData.Frequency == 0 || QueryEndData.Frequency == 0 || QueryEndData.Counter > QueryStartData.Counter);
}
}
}
}
} // namespace
| 37.268882 | 139 | 0.620866 | Zone-organization |
0589fa5eabede9edee552b0c6a8c4770826901e3 | 567 | cpp | C++ | src/parser/transform/statement/transform_export.cpp | GuinsooLab/guinsoodb | f200538868738ae460f62fb89211deec946cefff | [
"MIT"
] | 1 | 2021-04-22T05:41:54.000Z | 2021-04-22T05:41:54.000Z | src/parser/transform/statement/transform_export.cpp | GuinsooLab/guinsoodb | f200538868738ae460f62fb89211deec946cefff | [
"MIT"
] | null | null | null | src/parser/transform/statement/transform_export.cpp | GuinsooLab/guinsoodb | f200538868738ae460f62fb89211deec946cefff | [
"MIT"
] | 1 | 2021-12-12T10:24:57.000Z | 2021-12-12T10:24:57.000Z | #include "guinsoodb/parser/statement/export_statement.hpp"
#include "guinsoodb/parser/transformer.hpp"
namespace guinsoodb {
unique_ptr<ExportStatement> Transformer::TransformExport(guinsoodb_libpgquery::PGNode *node) {
auto stmt = reinterpret_cast<guinsoodb_libpgquery::PGExportStmt *>(node);
auto info = make_unique<CopyInfo>();
info->file_path = stmt->filename;
info->format = "csv";
info->is_from = false;
// handle export options
TransformCopyOptions(*info, stmt->options);
return make_unique<ExportStatement>(move(info));
}
} // namespace guinsoodb
| 29.842105 | 94 | 0.772487 | GuinsooLab |
058e4c0e1f0e9588844a2d39f7e1d1b0a15e7c26 | 2,253 | cpp | C++ | examples/any.cpp | cyber5tar86/cppbackport | b9db696e0f2f2d8225bbd65fc6a45f88307a1f14 | [
"BSD-3-Clause"
] | 47 | 2016-07-20T21:12:04.000Z | 2021-09-05T22:39:04.000Z | examples/any.cpp | cyber5tar86/cppbackport | b9db696e0f2f2d8225bbd65fc6a45f88307a1f14 | [
"BSD-3-Clause"
] | 9 | 2016-07-21T21:03:36.000Z | 2018-04-26T01:36:10.000Z | examples/any.cpp | cyber5tar86/cppbackport | b9db696e0f2f2d8225bbd65fc6a45f88307a1f14 | [
"BSD-3-Clause"
] | 4 | 2017-05-04T22:38:32.000Z | 2021-09-09T08:12:30.000Z | /* Copyright (c) 2016, Pollard Banknote Limited
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include "any.h"
int main()
{
cpp::any x;
x = 3;
std::cout << "Get value out of an any: " << cpp::any_cast< int >(x) << std::endl;
std::cout << std::endl;
std::cout << "Get a pointer to the stored value: " << cpp::any_cast< int >(&x) << std::endl;
std::cout << std::endl;
std::cout << "Cause a bad cast" << std::endl;
try
{
std::cout << cpp::any_cast< float >(x) << std::endl;
}
catch ( cpp::bad_any_cast& e )
{
std::cerr << "Error converting 'any' to type: " << e.what() << std::endl;
}
std::cout << std::endl;
x.reset();
std::cout << "Get a pointer to a cleared value: " << cpp::any_cast< int >(&x) << std::endl;
std::cout << std::endl;
}
| 38.186441 | 93 | 0.714603 | cyber5tar86 |
0591619afe935e87f2523cc1e28e46f8c6d90370 | 5,528 | cpp | C++ | src/wiztk/gui/display.cpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 37 | 2017-11-22T14:15:33.000Z | 2021-11-25T20:39:39.000Z | src/wiztk/gui/display.cpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 3 | 2018-03-01T12:44:22.000Z | 2021-01-04T23:14:41.000Z | src/wiztk/gui/display.cpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 10 | 2017-11-25T19:09:11.000Z | 2020-12-02T02:05:47.000Z | /*
* Copyright 2017 - 2018 The WizTK 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 "display/private.hpp"
#include "wiztk/base/property.hpp"
#include "wiztk/gui/surface.hpp"
#include <iostream>
namespace wiztk {
namespace gui {
Display::Display() {
p_ = std::make_unique<Private>();
p_->cursors.resize(kCursorBlank, nullptr);
}
Display::~Display() = default;
void Display::Connect(const char *name) {
if (p_->wl_display) return;
p_->wl_display = wl_display_connect(name);
wl_display_add_listener(p_->wl_display, &Private::kDisplayListener, this);
if (nullptr == p_->wl_display) {
throw std::runtime_error("FATAL! Cannot connect to Wayland compositor!");
}
p_->fd = wl_display_get_fd(p_->wl_display);
p_->xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
if (p_->xkb_context == nullptr) {
throw std::runtime_error("FATAL! Cannot create xkb_context!");
}
p_->InitializeEGLDisplay();
p_->CreateVKInstance();
p_->wl_registry = wl_display_get_registry(p_->wl_display);
wl_registry_add_listener(p_->wl_registry, &Private::kRegistryListener, this);
if (wl_display_roundtrip(p_->wl_display) < 0) {
Disconnect();
throw std::runtime_error("Failed to process Wayland connection!");
}
// TODO: more operations
}
void Display::Disconnect() noexcept {
if (nullptr == p_->wl_display) return;
xkb_context_unref(p_->xkb_context);
// TODO: other operations
p_->output_manager.Clear();
p_->input_manager.Clear();
Surface::Clear();
if (p_->wl_data_device_manager) {
wl_data_device_manager_destroy(p_->wl_data_device_manager);
p_->wl_data_device_manager = nullptr;
}
if (p_->wl_cursor_theme) {
ReleaseCursors();
wl_cursor_theme_destroy(p_->wl_cursor_theme);
p_->wl_cursor_theme = nullptr;
}
if (p_->wl_shell) {
wl_shell_destroy(p_->wl_shell);
p_->wl_shell = nullptr;
}
if (p_->xdg_shell) {
zxdg_shell_v6_destroy(p_->xdg_shell);
p_->xdg_shell = nullptr;
}
if (p_->wl_shm) {
wl_shm_destroy(p_->wl_shm);
p_->wl_shm = nullptr;
}
if (p_->wl_subcompositor) {
wl_subcompositor_destroy(p_->wl_subcompositor);
p_->wl_subcompositor = nullptr;
}
if (p_->wl_compositor) {
wl_compositor_destroy(p_->wl_compositor);
p_->wl_compositor = nullptr;
}
if (p_->wl_registry) {
wl_registry_destroy(p_->wl_registry);
p_->wl_registry = nullptr;
}
p_->ReleaseVKInstance();
p_->ReleaseEGLDisplay();
wl_display_disconnect(p_->wl_display);
}
OutputManager *Display::GetOutputManager() const {
return &__PROPERTY__(output_manager);
}
InputManager *Display::GetInputManager() const {
return &__PROPERTY__(input_manager);
}
const std::set<uint32_t> &Display::GetPixelFormats() const {
return __PROPERTY__(pixel_formats);
}
const Cursor *Display::GetCursor(CursorType cursor_type) const {
return __PROPERTY__(cursors)[cursor_type];
}
void Display::InitializeCursors() {
p_->cursors[kCursorBottomLeft] =
Cursor::Create(wl_cursor_theme_get_cursor(p_->wl_cursor_theme, "bottom_left_corner"));
p_->cursors[kCursorBottomRight] =
Cursor::Create(wl_cursor_theme_get_cursor(p_->wl_cursor_theme, "bottom_right_corner"));
p_->cursors[kCursorBottom] =
Cursor::Create(wl_cursor_theme_get_cursor(p_->wl_cursor_theme, "bottom_side"));
p_->cursors[kCursorDragging] =
Cursor::Create(wl_cursor_theme_get_cursor(p_->wl_cursor_theme, "grabbing"));
p_->cursors[kCursorLeftPtr] =
Cursor::Create(wl_cursor_theme_get_cursor(p_->wl_cursor_theme, "left_ptr"));
p_->cursors[kCursorLeft] =
Cursor::Create(wl_cursor_theme_get_cursor(p_->wl_cursor_theme, "left_side"));
p_->cursors[kCursorRight] =
Cursor::Create(wl_cursor_theme_get_cursor(p_->wl_cursor_theme, "right_side"));
p_->cursors[kCursorTopLeft] =
Cursor::Create(wl_cursor_theme_get_cursor(p_->wl_cursor_theme, "top_left_corner"));
p_->cursors[kCursorTopRight] =
Cursor::Create(wl_cursor_theme_get_cursor(p_->wl_cursor_theme, "top_right_corner"));
p_->cursors[kCursorTop] =
Cursor::Create(wl_cursor_theme_get_cursor(p_->wl_cursor_theme, "top_side"));
p_->cursors[kCursorIbeam] =
Cursor::Create(wl_cursor_theme_get_cursor(p_->wl_cursor_theme, "xterm"));
p_->cursors[kCursorHand1] =
Cursor::Create(wl_cursor_theme_get_cursor(p_->wl_cursor_theme, "hand1"));
p_->cursors[kCursorWatch] =
Cursor::Create(wl_cursor_theme_get_cursor(p_->wl_cursor_theme, "watch"));
p_->cursors[kCursorDndMove] =
Cursor::Create(wl_cursor_theme_get_cursor(p_->wl_cursor_theme, "left_ptr"));
p_->cursors[kCursorDndCopy] =
Cursor::Create(wl_cursor_theme_get_cursor(p_->wl_cursor_theme, "left_ptr"));
p_->cursors[kCursorDndForbidden] =
Cursor::Create(wl_cursor_theme_get_cursor(p_->wl_cursor_theme, "left_ptr"));
}
void Display::ReleaseCursors() {
for (size_t i = 0; i < p_->cursors.size(); i++) {
delete p_->cursors[i];
p_->cursors[i] = nullptr;
}
}
} // namespace gui
} // namespace wiztk
| 30.20765 | 93 | 0.721599 | wiztk |
05925481dfc10b1704c79c304b067cc044b538e6 | 50,740 | hpp | C++ | source/pixie/pixie_build.hpp | rdacomp/pixie | cc2abb5572952ce567f96d19244996f249a423ca | [
"Unlicense"
] | 148 | 2018-01-22T05:32:04.000Z | 2022-01-09T22:36:10.000Z | source/pixie/pixie_build.hpp | rdacomp/pixie | cc2abb5572952ce567f96d19244996f249a423ca | [
"Unlicense"
] | null | null | null | source/pixie/pixie_build.hpp | rdacomp/pixie | cc2abb5572952ce567f96d19244996f249a423ca | [
"Unlicense"
] | 3 | 2018-02-08T12:51:16.000Z | 2020-02-01T21:04:38.000Z | /*
------------------------------------------------------------------------------
Licensing information can be found at the end of the file.
------------------------------------------------------------------------------
pixie_build.hpp - v0.1 -
*/
#ifndef pixie_build_hpp
#define pixie_build_hpp
#include <stddef.h>
#include "cpp_compat.hpp"
namespace pixie_build {
typedef int8_t i8; typedef int16_t i16; typedef int32_t i32; typedef int64_t i64;
typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef uint64_t u64;
}
#include "array.hpp"
#include "binary_rw.h"
#include "dictionary.hpp"
#include "math_util.hpp"
#include "refcount.hpp"
#include "sort.hpp"
#include "strpool.hpp"
#include "strpool_util.hpp"
#include "vecmath.hpp"
namespace pixie_build {
namespace internal {
struct PIXIE_BUILD_STRING_POOL;
struct PIXIE_BUILD_STRING_ID_POOL;
} /* namespace internal */
typedef strpool::string_type<internal::PIXIE_BUILD_STRING_POOL> string;
typedef strpool::string_type<internal::PIXIE_BUILD_STRING_ID_POOL> string_id;
#pragma warning( push )
#pragma warning( disable: 4619 ) // pragma warning : there is no warning number 'number'
#pragma warning( disable: 4217 ) // nonstandard extension used : function declaration from a previous block
template< typename T, int CAPACITY = 16 > struct array : array_ns::array_type< T, CAPACITY, array_ns::NOT_POD >
{
explicit array( int initial_capacity = CAPACITY );
template< typename U > array( U const& other );
template< typename U > explicit array( U const* items, int count );
};
template< typename T, int CAPACITY = 16 > struct pod_array : array_ns::array_type< T, CAPACITY, array_ns::IS_POD >
{
explicit pod_array( int initial_capacity = CAPACITY );
template< typename U > pod_array( U const& other );
template< typename U > explicit pod_array( U const* items, int count );
};
#pragma warning( pop )
struct compilation_result
{
int succeeded;
int failed;
int uptodate;
};
struct compiler_param
{
string_id name;
string_id value;
};
struct compile_context
{
string input_root;
string build_root;
string output_root;
string path;
string input;
array<compiler_param> parameters;
};
struct compiler_list
{
char const* id;
compilation_result (*compiler)( compile_context const* context );
};
compilation_result compiler_pixie_copy( compile_context const* context );
compilation_result compiler_pixie_palette( compile_context const* context );
compilation_result compiler_pixie_bitmap( compile_context const* context );
compilation_result compiler_pixie_font( compile_context const* context );
static compiler_list default_compilers[] =
{
{ "pixie_copy", compiler_pixie_copy, },
{ "pixie_palette", compiler_pixie_palette, },
{ "pixie_bitmap", compiler_pixie_bitmap, },
// { "pixie_font", compiler_pixie_font, },
};
enum build_action
{
BUILD_ACTION_UNDEFINED,
BUILD_ACTION_BUILD,
BUILD_ACTION_REBUILD,
BUILD_ACTION_CLEAN,
};
int build( build_action action, char const* input_path, char const* build_path, char const* output_path, compiler_list* compilers = 0, int compilers_count = 0 );
using strpool::str; using strpool::trim; using strpool::ltrim;
using strpool::rtrim; using strpool::left; using strpool::right; using strpool::mid ; using strpool::instr;
using strpool::any; using strpool::upper; using strpool::lower;
using strpool::val; using strpool::integer; using strpool::space; using strpool::flip; using strpool::repeat;
using strpool::chr; using strpool::asc; using strpool::len;
using refcount::ref;
using vecmath::float2; using vecmath::float3; using vecmath::float4; using vecmath::float2x2;
using vecmath::float2x3; using vecmath::float3x2; using vecmath::float3x3; using vecmath::float2x4;
using vecmath::float3x4; using vecmath::float4x2; using vecmath::float4x3; using vecmath::float4x4; using vecmath::abs;
using vecmath::acos; using vecmath::all; using vecmath::any; using vecmath::asin; using vecmath::atan;
using vecmath::atan2; using vecmath::ceil; using vecmath::clamp; using vecmath::cos; using vecmath::cosh;
using vecmath::degrees; using vecmath::distancesq; using vecmath::distance; using vecmath::dot; using vecmath::exp;
using vecmath::exp2; using vecmath::floor; using vecmath::fmod; using vecmath::frac; using vecmath::lengthsq;
using vecmath::length; using vecmath::lerp; using vecmath::log; using vecmath::log10; using vecmath::mad;
using vecmath::max; using vecmath::min; using vecmath::normalize; using vecmath::pow; using vecmath::radians;
using vecmath::rcp; using vecmath::reflect; using vecmath::refract; using vecmath::round; using vecmath::rsqrt;
using vecmath::saturate; using vecmath::sign; using vecmath::sin; using vecmath::sinh; using vecmath::smoothstep;
using vecmath::smootherstep; using vecmath::sqrt; using vecmath::step; using vecmath::tan; using vecmath::tanh;
using math_util::PI; using math_util::TWO_PI;
using dictionary_ns::dictionary;
inline string str( int x ) { return strpool::str<pixie_build::internal::PIXIE_BUILD_STRING_POOL>( x ); }
inline string str( float x ) { return strpool::str<pixie_build::internal::PIXIE_BUILD_STRING_POOL>( x ); }
#define str_switch( x ) pixie_build::string_id const& multiple_str_switch_not_allowed_within_the_same_scope( x );
#define str_case( x ) if( multiple_str_switch_not_allowed_within_the_same_scope == pixie_build::string_id( x ) )
template< typename T > void swap( T* a, T* b );
void random_seed( u32 seed );
float random();
int random( int min, int max );
float random_bell_curve( int iterations = 3 );
int random_bell_curve( int min, int max, int iterations = 3 );
template< typename T > void shuffle( T* elements, int count );
template< typename T > void shuffle( array<T>* arr );
template< typename T > void shuffle( pod_array<T>* arr );
float3 random_unit_vector();
template< typename T > void sort( T* elements, int count );
template< typename T > void sort( array<T>* arr );
template< typename T > void sort( pod_array<T>* arr );
template< typename T, int (*COMPARE_FUNC)( T const&, T const& ) > void custom_sort( T* array, int count );
template< typename T, int (*COMPARE_FUNC)( T const&, T const& ) > void custom_sort( array<T>* arr );
template< typename T, int (*COMPARE_FUNC)( T const&, T const& ) > void custom_sort( pod_array<T>* arr );
template< typename T > int find( T const* haystack_elements, int haystack_count, T const& needle );
template< typename T > int find( array<T> const& haystack, T const& needle );
template< typename T > int find( pod_array<T> const& haystack, T const& needle );
int abs( int x );
int min( int x, int y );
int max( int x, int y );
int clamp( int x, int min_val, int max_val );
struct binary { size_t size; void* data; };
ref<binary> bload( string const& filename );
ref<binary> bnew( size_t size );
ref<binary> bresize( ref<binary> const& bin, size_t new_size );
string basename( string a );
string extname( string a );
string dirname( string a );
string path_join( string const& a, string const& b );
string path_join( string const& a, string const& b, string const& c );
string path_join( string const& a, string const& b, string const& c, string const& d );
string path_join( string const& a, string const& b, string const& c, string const& d, string const& e );
void logf( string str, ... );
bool file_exists( string const& filename );
} /* namespace pixie_build */
#endif // pixie_build_hpp
/*
----------------------
IMPLEMENTATION
----------------------
*/
#ifndef pixie_build_impl
#define pixie_build_impl
namespace pixie_build { namespace internal {
strpool::internal::string_pool& string_pool();
strpool::internal::string_pool& string_id_pool();
} /* namespace internal */ } /* namespace pixie */
template<> inline strpool::internal::string_pool& strpool::internal::pool_instance<pixie_build::internal::PIXIE_BUILD_STRING_POOL>( bool )
{
return pixie_build::internal::string_pool();
}
template<> inline strpool::internal::string_pool& strpool::internal::pool_instance<pixie_build::internal::PIXIE_BUILD_STRING_ID_POOL>( bool )
{
return pixie_build::internal::string_id_pool();
}
template< typename T > void pixie_build::swap( T* a, T* b )
{
// expressed using only copy constructor, no assignment operator, for consistency with container classes
T t( *a ); // t = a
a->~T(); new ( a ) T( *b ); // a = b
b->~T(); new ( b ) T( t ); // b = t
}
template< typename T, int CAPACITY > pixie_build::array<T, CAPACITY>::array( int initial_capacity = CAPACITY ) :
array_ns::array_type<T, CAPACITY, array_ns::NOT_POD>( initial_capacity, 0 )
{ }
template< typename T, int CAPACITY > template< typename U > pixie_build::array<T, CAPACITY>::array( U const& other ) :
array_ns::array_type<T, CAPACITY, array_ns::NOT_POD>( other )
{ }
template< typename T, int CAPACITY > template< typename U > pixie_build::array<T, CAPACITY>::array( U const* items, int count ) :
array_ns::array_type<T, CAPACITY, array_ns::NOT_POD>( items, count, 0 )
{ }
template< typename T, int CAPACITY > pixie_build::pod_array<T, CAPACITY>::pod_array( int initial_capacity = CAPACITY ) :
array_ns::array_type<T, CAPACITY, array_ns::IS_POD>( initial_capacity, 0 )
{ }
template< typename T, int CAPACITY > template< typename U > pixie_build::pod_array<T, CAPACITY>::pod_array( U const& other ) :
array_ns::array_type<T, CAPACITY, array_ns::IS_POD>( other )
{ }
template< typename T, int CAPACITY > template< typename U > pixie_build::pod_array<T, CAPACITY>::pod_array( U const* items, int count ) :
array_ns::array_type<T, CAPACITY, array_ns::IS_POD>( items, count, 0 )
{ }
template< typename T > void pixie_build::shuffle( T* elements, int count )
{
for( int i = 0; i < count; ++i )
{
int const r = random( i, count - 1 );
swap( &elements[ i ], &elements[ r ] );
}
}
template< typename T > void pixie_build::shuffle( array<T>* arr )
{
shuffle( arr->data(), arr->count() );
}
template< typename T > void pixie_build::shuffle( pod_array<T>* arr )
{
shuffle( arr->data(), arr->count() );
}
template< typename T > void pixie_build::sort( T* elements, int count )
{
::sort_ns::sort( elements, count );
}
template< typename T > void pixie_build::sort( array<T>* arr )
{
::sort_ns::sort( arr->data(), arr->count() );
}
template< typename T > void pixie_build::sort( pod_array<T>* arr )
{
::sort_ns::sort( arr->data(), arr->count() );
}
template< typename T, int (*COMPARE_FUNC)( T const&, T const& ) > void pixie_build::custom_sort( T* elements, int count )
{
::sort_ns::sort<T, COMPARE_FUNC>( array, count );
}
template< typename T, int (*COMPARE_FUNC)( T const&, T const& ) > void pixie_build::custom_sort( array<T>* arr )
{
::sort_ns::sort<T, COMPARE_FUNC>( arr->data(), arr->count() );
}
template< typename T, int (*COMPARE_FUNC)( T const&, T const& ) > void pixie_build::custom_sort( pod_array<T>* arr )
{
::sort_ns::sort<T, COMPARE_FUNC>( arr->data(), arr->count() );
}
template< typename T > int pixie_build::find( T const* haystack_elements, int haystack_count, T const& needle )
{
for( int i = 0; i < haystack_count; ++i )
if( haystack_elements[ i ] == needle ) return i;
return -1;
}
template< typename T > int pixie_build::find( array<T> const& haystack, T const& needle )
{
return find( haystack.data(), haystack.count(), needle );
}
template< typename T > int pixie_build::find( pod_array<T> const& haystack, T const& needle )
{
return find( haystack.data(), haystack.count(), needle );
}
#endif /* pixie_build_impl */
#ifdef PIXIE_BUILD_IMPLEMENTATION
#undef PIXIE_BUILD_IMPLEMENTATION
#include "dir.h"
#include "file.h"
#include "file_util.h"
#include "ini.h"
#include "log.h"
#include "paldither.h"
#include "palettize.h"
#include "rnd.h"
#include "thread.h"
#include "stb_image.h"
#include "stb_perlin.h"
#define _CRT_NONSTDC_NO_DEPRECATE
#define _CRT_SECURE_NO_WARNINGS
#include <math.h>
#include <stdarg.h>
namespace pixie_build { namespace internal {
static thread_tls_t internals_tls;
struct internals_t;
internals_t* internals();
} /* namespace internal */ } /* namespace pixie_build */
pixie_build::internal::internals_t* pixie_build::internal::internals()
{
assert( internals_tls && "Attempt to call a Pixie build function from outside a pixie_build::build block." );
void* ptr = thread_tls_get( internals_tls );
assert( ptr && "Attempt to call a Pixie build function from a thread which it is not running on." );
return (internals_t*) ptr;
}
struct pixie_build::internal::internals_t final
{
internals_t();
log_t* log;
char* log_buffer;
size_t log_capacity;
strpool::internal::string_pool string_pool;
strpool::internal::string_pool string_id_pool;
rnd_pcg_t rng_instance;
};
pixie_build::internal::internals_t::internals_t() :
string_pool( true ),
string_id_pool( false )
{
rnd_pcg_seed( &rng_instance, 0 );
}
strpool::internal::string_pool& pixie_build::internal::string_pool()
{
return internals()->string_pool;
}
strpool::internal::string_pool& pixie_build::internal::string_id_pool()
{
return internals()->string_id_pool;
}
float pixie_build::random()
{
internal::internals_t* internals = internal::internals();
return rnd_pcg_nextf( &internals->rng_instance);
}
int pixie_build::random( int min, int max )
{
internal::internals_t* internals = internal::internals();
return rnd_pcg_range( &internals->rng_instance, min, max );
}
void pixie_build::random_seed( u32 seed )
{
internal::internals_t* internals = internal::internals();
rnd_pcg_seed( &internals->rng_instance, seed );
}
float pixie_build::random_bell_curve( int iterations )
{
float sum = 0.0f;
for( int i = 0; i < iterations; ++i )
sum += random();
return sum / (float) iterations;
}
int pixie_build::random_bell_curve( int min, int max, int iterations )
{
int const range = ( max - min ) + 1;
if( range <= 0 ) return min;
int const value = (int) ( random_bell_curve( iterations ) * range );
return min + value;
}
pixie_build::float3 pixie_build::random_unit_vector()
{
float const TWO_PI_ = 6.283185307179586476925286766559f;
float phi = random() * TWO_PI_;
float costheta = random() * 2.0f - 1.0f;
float theta = acosf( costheta );
float x = sinf( theta ) * cosf( phi );
float y = sinf( theta ) * sinf( phi );
float z = cosf( theta );
return float3( x, y, z );
}
namespace pixie_build { namespace internal {
void binary_delete( void* instance )
{
free( instance );
}
} /* namespace internal */ } /*namespace pixie */
pixie_build::ref<pixie_build::binary> pixie_build::bload( string const& filename )
{
file_t* file = file_load( filename.c_str(), FILE_MODE_BINARY, 0 );
if( !file ) return ref<binary>::ref();
size_t file_size = file->size;
void* storage = malloc( sizeof( binary ) + sizeof( int ) + file_size );
void* file_data = (void*)( (uintptr_t)storage + sizeof( binary ) + sizeof( int ) );
memcpy( file_data, file->data, file_size );
file_destroy( file );
binary* bin = (binary*)storage;
bin->data = (u8*)file_data;
bin->size = file_size;
return refcount::make_ref( bin, internal::binary_delete, (int*)( (uintptr_t)storage + sizeof( binary ) ), 0 );
}
pixie_build::ref<pixie_build::binary> pixie_build::bnew( size_t size )
{
void* storage = malloc( sizeof( binary ) + sizeof( int ) + size );
binary* bin = (binary*)storage;
bin->data = (u8*)( (uintptr_t)storage + sizeof( binary ) + sizeof( int ) );
bin->size = (size_t)size;
return refcount::make_ref( bin, internal::binary_delete, (int*)( (uintptr_t)storage + sizeof( binary ) ), 0 );
}
pixie_build::ref<pixie_build::binary> pixie_build::bresize( ref<binary> const& bin, size_t new_size )
{
ref<binary> new_binary = bnew( new_size );
memcpy( new_binary->data, bin->data, new_size < bin->size ? new_size : bin->size );
return new_binary;
}
namespace pixie_build {
string path_join( string const& a, string const& b )
{
string r = a;
if( len( a ) > 0 && len( b ) > 0 ) r += "/";
r += b;
return r;
}
string path_join( string const& a, string const& b, string const& c )
{
return path_join( path_join( a, b ), c );
}
string path_join( string const& a, string const& b, string const& c, string const& d )
{
return path_join( path_join( path_join( a, b ), c ), d );
}
string path_join( string const& a, string const& b, string const& c, string const& d, string const& e )
{
return path_join( path_join( path_join( path_join( a, b ), c ), d ), e );
}
void logf( string str, ... )
{
#pragma warning( push )
#pragma warning( disable: 4619 ) // there is no warning number '4840'
#pragma warning( disable: 4840 ) // non-portable use of class 'strpool::string_type<pixie_build::internal::PIXIE_BUILD_STRING_POOL>' as an argument to a variadic function
pixie_build::internal::internals_t* internals = pixie_build::internal::internals();
va_list args;
va_start( args, str );
size_t count = (size_t) _vsnprintf( internals->log_buffer, internals->log_capacity, str.c_str(), args );
va_end( args );
if( count >= internals->log_capacity )
{
if( internals->log_capacity == 0 )
internals->log_capacity = 1024;
else
internals->log_capacity = ( internals->log_capacity * 2 <= count ) ? count + 1 : internals->log_capacity * 2;
internals->log_buffer = (char*) malloc( internals->log_capacity );
va_start (args, str);
count = (size_t) _vsnprintf( internals->log_buffer, internals->log_capacity, str.c_str(), args );
va_end (args);
}
log_print( internals->log, internals->log_buffer );
#pragma warning( pop )
}
bool file_exists( string const& filename )
{
return ::file_exists( filename.c_str() ) != 0;
}
struct compile_counts
{
int succeeded;
int failed;
int uptodate;
compile_counts() : succeeded( 0 ), failed( 0 ), uptodate( 0 ) {}
void operator+=( compile_counts other )
{
succeeded += other.succeeded;
failed += other.failed;
uptodate += other.uptodate;
}
};
struct file_location
{
string_id filename;
int line;
};
struct missing_buildstep
{
string_id buildstep;
file_location location;
};
struct build_t
{
string root_input;
string root_build;
string root_output;
compiler_list* compilers;
int compilers_count;
array<missing_buildstep> missing_buildsteps_reported;
};
struct config_buildstep
{
string_id id;
string_id compiler;
array<compiler_param> parameters;
file_location location;
};
struct build_mapping
{
string_id name;
string_id buildstep;
file_location location;
};
struct config
{
config() : valid( false ) {}
bool valid;
build_mapping folder_mapping;
file_location folder_mapping_location;
array<build_mapping> file_mappings;
array<config_buildstep> buildsteps;
};
config read_config( build_t* build, string const& path )
{
(void) build;
config cfg;
cfg.valid = false;
string relative_path = dirname( path.c_str() );
if( right( relative_path, 1 ) == "/" || right( relative_path, 1 ) == "\\" ) relative_path = left( relative_path, len( relative_path ) -1 );
// TODO: append relative path to file name
file_t* file = file_load( path.c_str(), FILE_MODE_TEXT, 0 );
if( !file ) return cfg;
ini_t* ini = ini_load( file->data, 0 );
file_destroy( file );
if( !ini ) return cfg;
// TODO: check for duplicate mappings and buildsteps
// file mappings
int pcount = ini_property_count( ini, INI_GLOBAL_SECTION );
for( int i = 0; i < pcount; ++i )
{
string_id name = ini_property_name( ini, INI_GLOBAL_SECTION, i );
string_id value = ini_property_value( ini, INI_GLOBAL_SECTION, i );
name = trim( name );
value = trim( value );
if( name == "folder" )
{
if( cfg.folder_mapping.name != "" ) (void)i; // TODO: error handling
cfg.folder_mapping.name = "folder";
cfg.folder_mapping.buildstep = value;
cfg.folder_mapping_location.filename = path;
cfg.folder_mapping_location.line = 0;
}
else
{
build_mapping mapping;
if( left( name, 1 ) != "." ) name = path_join( relative_path, name );
mapping.name = name;
mapping.buildstep = value;
cfg.file_mappings.add( mapping );
}
}
// buildsteps
int scount = ini_section_count( ini );
for( int i = 0; i < scount; ++i )
{
string_id section = ini_section_name( ini, i );
if( section == "" ) continue;
config_buildstep step;
step.id = section;
int prop_count = ini_property_count( ini, i );
for( int j = 0; j < prop_count; ++j )
{
string_id name = ini_property_name( ini, i, j );
string_id value = ini_property_value( ini, i, j );
name = trim( name );
value = trim( value );
if( name == "compiler" )
{
if( step.compiler != "" ) (void)i; // TODO: error handling
step.compiler = value;
}
else
{
compiler_param param;
param.name = name;
param.value = value;
step.parameters.add( param );
}
}
cfg.buildsteps.add( step );
}
ini_destroy( ini );
cfg.valid = true;
return cfg;
}
config merge_cfg( config const& a, config const& b )
{
config cfg;
cfg.valid = false;
if( !a.valid && !b.valid ) return cfg;
if( !a.valid ) return b;
cfg = a;
if( b.valid )
{
if( b.folder_mapping.name != "" ) cfg.folder_mapping = b.folder_mapping;
for( int i = 0; i < b.file_mappings.count(); ++i )
{
build_mapping m = b.file_mappings[ i ];
for( int j = 0; cfg.file_mappings.count(); ++j )
{
if( cfg.file_mappings[ j ].name == m.name )
{
cfg.file_mappings.remove( j );
break;
}
}
if( m.buildstep != "" ) cfg.file_mappings.add( m );
}
for( int i = 0; i < b.buildsteps.count(); ++i )
{
config_buildstep s = b.buildsteps[ i ];
for( int j = 0; j < cfg.buildsteps.count(); ++j )
{
if( cfg.buildsteps[ j ].id == s.id )
{
cfg.buildsteps.remove( j );
break;
}
}
if( s.compiler != "" ) cfg.buildsteps.add( s );
}
}
return cfg;
}
compile_counts build_file( build_t* build, config cfg, string buildstep, string filename, string const& build_path, string const& out_path )
{
(void) build, cfg, filename, build_path, out_path;
// printf( "%s: %s\n", buildstep.c_str(), filename.c_str() + len( build->root_input ) + 1 );
filename = filename.c_str() + len( build->root_input ) + 1;
for( int i = 0; i < cfg.buildsteps.count(); ++i )
{
config_buildstep s = cfg.buildsteps[ i ];
if( s.id == buildstep )
{
bool found = false;
for( int j = 0; j < build->compilers_count; ++j )
{
if( s.compiler == build->compilers[ j ].id )
{
compile_context context;
context.input_root = build->root_input;
context.build_root = build->root_build;
context.output_root = build->root_output;
context.path = dirname( filename.c_str() );
context.path = left( context.path, len( context.path ) - 1 );
context.input = filename.c_str() + len( context.path ) + ( len( context.path ) == 0 ? 0 : 1 );
context.parameters = s.parameters;
build->compilers[ j ].compiler( &context );
found = true;
}
}
if( !found )
{
//logf( "%s(%d) : error: build step '%s' not found when compiling '%s'\n", __FILE__, __LINE__, buildstep.c_str(), filename.c_str() );
}
break;
}
}
return compile_counts();
}
compile_counts build_folder( build_t* build, config cfg, string buildstep, string foldername, string const& build_path, string const& out_path )
{
(void) build, cfg, foldername, build_path, out_path;
// printf( "%s: %s\n", buildstep.c_str(), filename.c_str() + len( build->root_input ) + 1 );
foldername = foldername.c_str() + len( build->root_input ) + 1;
for( int i = 0; i < cfg.buildsteps.count(); ++i )
{
config_buildstep s = cfg.buildsteps[ i ];
if( s.id == buildstep )
{
bool found = false;
for( int j = 0; j < build->compilers_count; ++j )
{
if( s.compiler == build->compilers[ j ].id )
{
compile_context context;
context.input_root = build->root_input;
context.build_root = build->root_build;
context.output_root = build->root_output;
context.path = dirname( foldername.c_str() );
context.path = left( context.path, len( context.path ) - 1 );
context.input = foldername.c_str() + len( context.path ) + ( len( context.path ) == 0 ? 0 : 1 );
context.parameters = s.parameters;
build->compilers[ j ].compiler( &context );
found = true;
}
}
if( !found )
{
//logf( "%s(%d) : error: build step '%s' not found when compiling '%s'\n", __FILE__, __LINE__, buildstep.c_str(), filename.c_str() );
}
break;
}
}
return compile_counts();
}
compile_counts build_dir( build_t* build, config cfg, string const& input, string const& build_path, string const& output )
{
compile_counts counts;
cfg = merge_cfg( cfg, read_config( build, input + "/build.ini" ) );
// subdirs
dir_t* dir = dir_open( input.c_str() );
if( !dir ) { /* TODO: error handling */ return counts; }
dir_entry_t* ent = dir_read( dir );
while( ent )
{
if( dir_is_folder( ent ) && strcmp( dir_name( ent ), "." ) != 0 && strcmp( dir_name( ent ), ".." ) != 0 )
{
if( cfg.folder_mapping.name != "folder" )
{
string new_input = path_join( input, dir_name( ent ) );
string new_build_path = path_join( build_path, dir_name( ent ) );
string new_output = path_join( output, dir_name( ent ) );
build_dir( build, cfg, new_input, new_build_path, new_output );
}
}
ent = dir_read( dir );
}
dir_close( dir );
// files
dir = dir_open( input.c_str() );
if( !dir ) { /* TODO: error handling */ return counts; }
ent = dir_read( dir );
while( ent )
{
if( dir_is_folder( ent ) && strcmp( dir_name( ent ), "." ) != 0 && strcmp( dir_name( ent ), ".." ) != 0 )
{
if( cfg.folder_mapping.name == "folder" )
{
string foldername = dir_name( ent );
build_folder( build, cfg, cfg.folder_mapping.buildstep, path_join( input, foldername ), build_path, output );
}
}
else if( dir_is_file( ent ) )
{
string filename = path_join( input, dir_name( ent ) );
bool found = false;
for( int i = 0; i < cfg.file_mappings.count(); ++i )
{
build_mapping m = cfg.file_mappings[ i ];
if( filename == m.name )
{
build_file( build, cfg, m.buildstep, filename, build_path, output );
found = true;
break;
}
}
if( !found )
{
string extension = extname( dir_name( ent ) );
for( int i = 0; i < cfg.file_mappings.count(); ++i )
{
build_mapping m = cfg.file_mappings[ i ];
if( extension == m.name )
{
build_file( build, cfg, m.buildstep, filename, build_path, output );
found = true;
break;
}
}
}
}
ent = dir_read( dir );
}
dir_close( dir );
return counts;
}
/*
const char* asset_type = dir_name( ent );
compiler_t* compiler = find_compiler( conditioner, asset_type );
if( compiler )
{
char source_path[ MAX_PATH ];
char build_path[ MAX_PATH ];
char output_path[ MAX_PATH ];
strcat( strcat( strcpy( source_path, conditioner->source_path ), "/" ), asset_type );
strcat( strcat( strcpy( build_path, conditioner->build_path ), "/" ), asset_type );
strcat( strcat( strcpy( output_path, conditioner->output_path ), "/" ), asset_type );
compile_context_t context;
context.asset_type = asset_type;
context.source_path = source_path;
context.build_path = build_path;
context.output_path = output_path;
context.log = conditioner->log;
log_queue( conditioner->log, "\nCompiling asset type '%s'...\n", asset_type );
if( compiler->compile )
{
counts += compiler->compile( &context );
}
else
{
log_print( conditioner->log, "%s(%d) : error: no compiler registered for asset type '%s'\n", __FILE__, __LINE__, asset_type );
++counts.failed;
}
log_cancel_queued( conditioner->log );
}
else
{
log_print( conditioner->log, "%s(%d) : error: no compiler registered for asset type '%s'\n", __FILE__, __LINE__, asset_type );
++counts.failed;
}
*/
compilation_result compiler_pixie_copy( compile_context const* context )
{
compilation_result result = { 0 };
string input_file = path_join( context->input_root, context->path, context->input );
string output_file = path_join( context->output_root, context->path, context->input );
if( !file_exists( output_file.c_str() ) || file_more_recent( input_file.c_str(), output_file.c_str() ) )
{
logf( path_join( context->path, context->input ) + "\n" );
create_path( path_join( context->output_root,context->path ).c_str() );
copy_file( input_file.c_str(), output_file.c_str() );
}
return result;
}
string basename( string a )
{
return ::basename( a.c_str(), ::extname( a.c_str() ) );
}
string extname( string a )
{
return ::extname( a.c_str() );
}
string dirname( string a )
{
return ::dirname( a.c_str() );
}
void build_palette_lookup( string const& input_file, string const& output_file )
{
int w, h, c;
stbi_uc* img = stbi_load( input_file.c_str(), &w, &h, &c, 4 );
u32 palette[ 256 ];
memset( palette, 0, 256 * sizeof( u32 ) );
int count = 0;
for( int y = 0; y < h; ++y )
{
for( int x = 0; x < w; ++x )
{
u32 pixel = ((u32*)img)[ x + y * w ];
if( ( pixel & 0xff000000 ) == 0 ) goto skip;
pixel = ( pixel & 0x00ffffff ) | 0xff000000;
if( count < 256 )
{
for( int i = 0; i < count; ++i )
{
if( palette[ i ] == pixel )
goto skip;
}
palette[ count ] = pixel;
}
++count;
skip:
;
}
}
if( count > 256 )
{
memset( palette, 0, 256 * sizeof( u32 ) );
count = palettize_generate_palette_xbgr32( (PALETTIZE_U32*) img, w, h, palette, 256, 0 );
}
stbi_image_free( img );
size_t size = 0;
paldither_palette_t* pal = paldither_palette_create( palette, count, &size, 0 );
create_path( dirname( output_file ).c_str() );
file_save_data( pal, size, output_file.c_str(), FILE_MODE_BINARY );
paldither_palette_destroy( pal );
}
compilation_result compiler_pixie_palette( compile_context const* context )
{
compilation_result result = { 0 };
string input_file = path_join( context->input_root, context->path, context->input );
bool file_printed = false;
string output_file = path_join( context->output_root, context->path, basename( context->input ) ) + ".pal";
if( !file_exists( output_file.c_str() ) || file_more_recent( input_file.c_str(), output_file.c_str() ) )
{
string build_file = path_join( context->build_root, context->path, basename( context->input ) ) + ".plut";
if( !file_exists( build_file.c_str() ) || file_more_recent( input_file.c_str(), build_file.c_str() ) )
{
logf( path_join( context->path, context->input ) + "\n" );
file_printed = true;
build_palette_lookup( input_file, build_file );
}
if( !file_printed ) logf( path_join( context->path, context->input ) + "\n" );
int w, h, c;
stbi_uc* img = stbi_load( input_file.c_str(), &w, &h, &c, 4 );
char const header[] = "PIXIE_PAL";
int version = 1;
u8 storage[ sizeof( header ) + sizeof( version ) + 256 * sizeof( u32 ) ];
memcpy( storage, header, sizeof( header ) );
memcpy( storage + sizeof( header ), &version, sizeof( version) );
u32* palette = (u32*)( storage + sizeof( header ) + sizeof( version ) );
memset( palette, 0, 256 * sizeof( u32 ) );
int count = 0;
for( int y = 0; y < h; ++y )
{
for( int x = 0; x < w; ++x )
{
u32 pixel = ((u32*)img)[ x + y * w ];
if( ( pixel & 0xff000000 ) == 0 ) goto skip;
pixel = ( pixel & 0x00ffffff ) | 0xff000000;
if( count < 256 )
{
for( int i = 0; i < count; ++i )
{
if( palette[ i ] == pixel )
goto skip;
}
palette[ count ] = pixel;
}
++count;
skip:
;
}
}
if( count > 256 )
{
memset( palette, 0, 256 * sizeof( u32 ) );
count = palettize_generate_palette_xbgr32( (PALETTIZE_U32*) img, w, h, palette, 256, 0 );
}
stbi_image_free( img );
create_path( dirname( output_file ).c_str() );
file_save_data( storage, sizeof( storage ), output_file.c_str(), FILE_MODE_BINARY );
}
return result;
}
compilation_result compiler_pixie_bitmap_single( compile_context const* context )
{
compilation_result result = { 0 };
string format;
string palette;
string dither;
for( int i = 0; i < context->parameters.count(); ++i )
{
string_id name( context->parameters[ i ].name );
string value( context->parameters[ i ].value );
str_switch( name )
{
str_case( "format" )
{
format = value;
}
str_case( "palette" )
{
palette = value;
}
str_case( "dither" )
{
dither = value;
}
}
}
string input_file = path_join( context->input_root, context->path, context->input );
string output_file = path_join( context->output_root, context->path, basename( context->input ) ) + ".pix";
if( !file_exists( output_file.c_str() ) || file_more_recent( input_file.c_str(), output_file.c_str() ) )
{
string palette_file = path_join( context->build_root, dirname( palette ), basename( palette ) ) + ".plut";
string palette_input = path_join( context->input_root, palette );
if( !file_exists( palette_file.c_str() ) || file_more_recent( palette_input.c_str(), palette_file.c_str() ) )
{
logf( palette + "\n" );
build_palette_lookup( palette_input, palette_file );
}
logf( path_join( context->path, context->input ) + "\n" );
file_t* file = file_load( palette_file.c_str(), FILE_MODE_BINARY, 0 );
if( !file ) { return result; /* TODO: error handling */}
paldither_palette_t* pal = paldither_palette_create_from_data( file->data, file->size, 0 );
file_destroy( file );
int w, h, n;
stbi_uc* img = stbi_load( input_file.c_str(), &w, &h, &n, 4 );
char const header[] = "PIXIE_PIX";
int version = 1;
size_t size = 5 * sizeof ( int ) + 2 * w * h + sizeof( header ) + sizeof( version ) + 4 * sizeof( int );
u8* output = (u8*) malloc( size );
memcpy( output, header, sizeof( header ) );
memcpy( output + sizeof( header ), &version, sizeof( version ) );
for( int i = 0; i < w * h; ++i )
{
u32 c = ( (u32*)img )[ i ];
u32 r = c & 0xff;
u32 g = ( c >> 8 ) & 0xff;
u32 b = ( c >> 16 ) & 0xff;
u32 a = ( c >> 24 ) & 0xff;
r = ( r * a ) >> 8;
g = ( g * a ) >> 8;
b = ( b * a ) >> 8;
c = ( a << 24 ) | ( b << 16 ) | ( g << 8 ) | r;
( (u32*)img )[ i ] = c;
}
int* offset_and_pitch = (int*)( output + sizeof( header ) + sizeof( version ) + 5 * sizeof ( int ) );
paldither_type_t dither_type = PALDITHER_TYPE_DEFAULT;
if( dither == "none" )
dither_type = PALDITHER_TYPE_NONE;
else if( dither == "bayer" )
dither_type = PALDITHER_TYPE_BAYER;
u8* pixels = output + sizeof( header ) + sizeof( version ) + 5 * sizeof ( int ) + 4 * sizeof( int ) ;
if( dither == "remap" )
palettize_remap_xbgr32( (PALDITHER_U32*)img, w, h, pal->colortable, pal->color_count, pixels );
else
paldither_palettize( (PALDITHER_U32*)img, w, h, pal, dither_type, pixels );
u8* mask = pixels + w * h;
bool is_masked = false;
int x_min = w;
int x_max = -1;
int y_min = h;
int y_max = -1;
for( int y = 0; y < h; ++y )
{
for( int x = 0; x < w; ++x )
{
u8 m = (u8)( ( ((u32*) img)[ x + w * y ] ) >> 24 );
mask[ x + w * y ] = m;
is_masked |= m < 0xff;
if( m )
{
x_min = x < x_min ? x : x_min;
y_min = y < y_min ? y : y_min;
x_max = x > x_max ? x : x_max;
y_max = y > y_max ? y : y_max;
}
}
}
stbi_image_free( img );
int offset_x = x_min;
int offset_y = y_min;
int pitch_x = x_max - x_min + 1;
int pitch_y = y_max - y_min + 1;
if( x_max < x_min || y_max < y_min )
{
offset_x = 0;
offset_y = 0;
pitch_x = 0;
pitch_y = 0;
}
if( pitch_x < w || pitch_y < h )
{
size -= 2 * w * h;
size += pitch_x * pitch_y;
for( int y = 0; y < pitch_y; ++y )
for( int x = 0; x < pitch_x; ++x )
pixels[ x + pitch_x * y ] = pixels[ ( x + offset_x ) + ( y + offset_y ) * w ];
if( is_masked )
{
size += pitch_x * pitch_y;
u8* mask_target = pixels + pitch_x * pitch_y;
for( int y = 0; y < pitch_y; ++y )
for( int x = 0; x < pitch_x; ++x )
mask_target[ x + pitch_x * y ] = mask[ ( x + offset_x ) + ( y + offset_y ) * w ];
}
}
else if( !is_masked ) size -= w * h;
offset_and_pitch[ 0 ] = offset_x;
offset_and_pitch[ 1 ] = offset_y;
offset_and_pitch[ 2 ] = pitch_x;
offset_and_pitch[ 3 ] = pitch_y;
int* info = (int*)( output + sizeof( header ) + sizeof( version ) );
info[ 0 ] = 0; // raw
info[ 1 ] = w;
info[ 2 ] = h;
info[ 3 ] = 1; // cel_count
info[ 4 ] = is_masked ? 1 : 0;
create_path( path_join( context->output_root, context->path ).c_str() );
file_save_data( output, size, output_file.c_str(), FILE_MODE_BINARY );
free( output );
paldither_palette_destroy( pal );
}
return result;
}
compilation_result compiler_pixie_bitmap_strip( compile_context const* context )
{
array<string> inputs;
compilation_result result = { 0 };
string ext = extname( context->input );
char const* underscore = strrchr( basename( context->input ).c_str(), '_' );
string stripped_name( basename( context->input ).c_str(), underscore + 1 );
dir_t* dir = dir_open( path_join( context->input_root, context->path ).c_str() );
assert( dir );
dir_entry_t* ent = dir_read( dir );
while( ent )
{
if( dir_is_file( ent ) )
{
if( (int)strlen( dir_name( ent ) ) == len( context->input ) && left( string( dir_name( ent ) ), len( stripped_name ) ) == stripped_name )
{
inputs.add( dir_name( ent ) );
}
}
ent = dir_read( dir );
}
dir_close( dir );
pixie_build::sort( &inputs );
for( int i = 0; i < inputs.count(); ++i )
{
compile_context single_context = *context;
single_context.output_root = single_context.build_root;
single_context.input = inputs[ i ];
compiler_pixie_bitmap_single( &single_context );
}
string output_file = path_join( context->output_root, context->path, left( stripped_name, len( stripped_name ) -1 ) ) + ".pix";
bool need_to_build = !file_exists( output_file.c_str() );
if( !need_to_build )
{
for( int i = 0; i < inputs.count(); ++i )
{
string build_file = path_join( context->build_root, context->path, basename( context->input ) ) + ".pix";
if( file_more_recent( build_file.c_str(), output_file.c_str() ) )
{
need_to_build = true;
break;
}
}
}
if( need_to_build )
{
array<pixie_build::ref<pixie_build::binary> > files;
for( int i = 0; i < inputs.count(); ++i )
{
string build_file = path_join( context->build_root, context->path, basename( inputs[ i ] ) ) + ".pix";
pixie_build::ref<pixie_build::binary> file = pixie_build::bload( build_file );
// TODO: error handling, file == 0, size == 0
files.add( file );
}
char const header[] = "PIXIE_PIX";
int version = 1;
int w = -1;
int h = -1;
int is_masked = -1;
for( int i = 0; i < files.count(); ++i )
{
u8* data = (u8*)files[ i ]->data;
int* info = (int*)( data + sizeof( header ) + sizeof( version ) );
if( w >= 0 && w != info[ 1 ] ) (void)w; // TODO: error handling
if( h >= 0 && h != info[ 2 ] ) (void)h; // TODO: error handling
if( is_masked >= 0 && is_masked != info[ 4 ] ) (void)is_masked; // TODO: error handling
w = info[ 1 ];
h = info[ 2 ];
is_masked = info[ 4 ];
}
assert( w > 0 && h > 0 && is_masked >= 0 );
size_t alloc_size = 5 * sizeof ( int ) + sizeof( header ) + sizeof( version ) + ( w * h * ( is_masked ? 2 : 1 ) + sizeof( int ) * 4 ) * files.count();
u8* output = (u8*) malloc( alloc_size );
memcpy( output, header, sizeof( header ) );
memcpy( output + sizeof( header ), &version, sizeof( version ) );
int* info = (int*)( output + sizeof( header ) + sizeof( version ) );
info[ 0 ] = 0; // raw
info[ 1 ] = w;
info[ 2 ] = h;
info[ 3 ] = files.count(); // cel_count
info[ 4 ] = is_masked;
size_t size = 5 * sizeof ( int ) + sizeof( header ) + sizeof( version ) + sizeof( int ) * 4 * files.count();
u8* data = (u8*)( info + 5 );
for( int i = 0; i < files.count(); ++i )
{
u8* src = (u8*)files[ i ]->data;
src += 5 * sizeof ( int ) + sizeof( header ) + sizeof( version );
memcpy( data, src, sizeof( int ) * 4 ); data += sizeof( int ) * 4; size += sizeof( int ) * 4;
src += sizeof( int );
src += sizeof( int );
int pitch_x = *(int*) src; src += sizeof( int );
int pitch_y = *(int*) src; src += sizeof( int );
memcpy( data, src, (size_t) pitch_x * pitch_y * ( is_masked ? 2 : 1 ) );
data += pitch_x * pitch_y * ( is_masked ? 2 : 1 );
size += pitch_x * pitch_y * ( is_masked ? 2 : 1 );
}
create_path( path_join( context->output_root, context->path ).c_str() );
file_save_data( output, size, output_file.c_str(), FILE_MODE_BINARY );
free( output );
}
return result;
}
compilation_result compiler_pixie_bitmap( compile_context const* context )
{
string name = basename( context->input );
int digit_count = 0;
char const* underscore = strrchr( name.c_str(), '_' );
string stripped_name( name.c_str(), underscore );
if( underscore )
{
++underscore;
while( *underscore )
{
if( *underscore >= '0' && *underscore <= '9' )
{
++digit_count;
}
else
{
digit_count = -1;
break;
}
++underscore;
}
}
if( digit_count > 1 )
{
int frame_num = integer( mid( name, len( stripped_name ) + 1 ) );
bool is_first = true;
dir_t* dir = dir_open( path_join( context->input_root, context->path ).c_str() );
assert( dir );
dir_entry_t* ent = dir_read( dir );
while( ent )
{
if( dir_is_file( ent ) )
{
if( left( string( dir_name( ent ) ), len( stripped_name ) + 1 ) == stripped_name + "_" )
{
int number = integer( mid( string( dir_name( ent ) ), len ( stripped_name ) + 1 ) );
if( number < frame_num )
{
is_first = false;
break;
}
}
}
ent = dir_read( dir );
}
dir_close( dir );
// if not the first image of the strip, just silently skip it (as this file will be built when the first image of the strip is built)
if( !is_first )
{
compilation_result result = { 0 };
return result;
}
// there needs to be at least two images in sequence for it to count as a strip
string next_frame = str( frame_num + 1 );
while( len( next_frame ) < digit_count ) next_frame = "0" + next_frame;
next_frame = stripped_name + "_" + next_frame;
next_frame = path_join( context->input_root, context->path, next_frame ) + extname( context->input );
if( file_exists( next_frame.c_str() ) )
return compiler_pixie_bitmap_strip( context );
}
return compiler_pixie_bitmap_single( context );
}
int build( build_action action, char const* input_path, char const* build_path, char const* output_path, compiler_list* compilers, int compilers_count )
{
(void) action, input_path, build_path, output_path, compilers, compilers_count;
static thread_atomic_int_t init_count;
if( thread_atomic_int_inc( &init_count ) == 0 ) pixie_build::internal::internals_tls = thread_tls_create();
u8* internals_storage = (u8*) malloc( sizeof( pixie_build::internal::internals_t ) );
memset( internals_storage, 0, sizeof( pixie_build::internal::internals_t ) );
thread_tls_set( pixie_build::internal::internals_tls, internals_storage );
pixie_build::internal::internals_t* internals = new (internals_storage) pixie_build::internal::internals_t();
int retval = 0;
{
if( compilers == 0 || compilers_count <= 0 )
{
compilers = default_compilers;
compilers_count = sizeof( default_compilers ) / sizeof( *default_compilers );
}
string input( input_path );
string builddir( build_path );
string output( output_path );
if( right( input, 1 ) == "/" || right( input, 1 ) == "\\" ) input = left( input, len( input ) -1 );
if( right( builddir, 1 ) == "/" || right( builddir, 1 ) == "\\" ) input = left( builddir, len( input ) -1 );
if( right( output, 1 ) == "/" || right( output, 1 ) == "\\" ) output = left( output, len( output ) -1 );
internals->log = log_create( path_join( builddir, "build.log" ).c_str(), 0 );
build_t build;
build.root_input = input;
build.root_build = builddir;
build.root_output = output;
build.compilers = compilers;
build.compilers_count = compilers_count;
if( action == BUILD_ACTION_CLEAN || action == BUILD_ACTION_REBUILD )
{
assert( !"Not implemented yet." ); // TODO: implement clean
}
if( action == BUILD_ACTION_BUILD || action == BUILD_ACTION_REBUILD )
{
config cfg;
compile_counts counts = build_dir( &build, cfg, input, builddir, output );
retval = ( counts.failed > 0 ? -1 : 0 );
}
log_destroy( internals->log );
free( internals->log_buffer );
}
internals->~internals_t();
thread_tls_set( pixie_build::internal::internals_tls, 0 );
free( internals_storage );
if( thread_atomic_int_dec( &init_count ) == 1 )thread_tls_destroy( pixie_build::internal::internals_tls );
return retval;
}
} /* namespace pixie_build */
int pixie_build::abs( int x )
{
return x < 0 ? -x : x;
}
int pixie_build::min( int x, int y )
{
return x < y ? x : y;
}
int pixie_build::max( int x, int y )
{
return x > y ? x : y;
}
#undef clamp
int pixie_build::clamp( int x, int min_val, int max_val )
{
return x > max_val ? max_val : x < min_val ? min_val : x;
}
#undef final
#undef override
#undef STATIC_ASSERT
#define ARRAY_IMPLEMENTATION
#include "array.hpp"
#define DIR_IMPLEMENTATION
#define DIR_WINDOWS
#include "dir.h"
#define FILE_IMPLEMENTATION
#include "file.h"
#define FILE_UTIL_IMPLEMENTATION
#include "file_util.h"
#define INI_IMPLEMENTATION
#include "ini.h"
#define HASHTABLE_IMPLEMENTATION
#include "hashtable.h"
#define LOG_IMPLEMENTATION
#include "log.h"
#define MATH_UTIL_IMPLEMENTATION
#include "math_util.hpp"
#define PALDITHER_IMPLEMENTATION
#include "paldither.h"
#define PALETTIZE_IMPLEMENTATION
#include "palettize.h"
#define RND_IMPLEMENTATION
#include "rnd.h"
#define STRPOOL_IMPLEMENTATION
#include "strpool.h"
#define STRPOOL_HPP_IMPLEMENTATION
#include "strpool.hpp"
#define STRPOOL_UTIL_IMPLEMENTATION
#include "strpool_util.hpp"
#define THREAD_IMPLEMENTATION
#include "thread.h"
#define VECMATH_IMPLEMENTATION
#include "vecmath.hpp"
#pragma warning( push )
#pragma warning( disable: 4619 ) // there is no warning number 'nnnn'
#pragma warning( disable: 4100 ) // unreferenced formal parameter
#pragma warning( disable: 4127 ) // conditional expression is constant
#pragma warning( disable: 4242 ) // conversion, possible loss of data
#pragma warning( disable: 4244 ) // conversion, possible loss of data
#pragma warning( disable: 4245 ) // conversion, signed/unsigned mismatch
#pragma warning( disable: 4302 ) // 'type cast' : truncation from 'type' to 'type'
#pragma warning( disable: 4311 ) // 'variable' : pointer truncation from 'type' to 'type'
#pragma warning( disable: 4365 ) // conversion, signed/unsigned mismatch
#pragma warning( disable: 4456 ) // declaration hides previous local declaration
#pragma warning( disable: 4457 ) // declaration hides function parameter
#pragma warning( disable: 4459 ) // declaration hides global declaration
#pragma warning( disable: 4555 ) // expression has no effect; expected expression with side-effect
#pragma warning( disable: 4701 ) // potentially uninitialized local variable used
#define STB_IMAGE_IMPLEMENTATION
#pragma push_macro("L")
#undef L
#include "stb_image.h"
#pragma pop_macro("L")
#undef STB_IMAGE_IMPLEMENTATION
#define STB_PERLIN_IMPLEMENTATION
#include "stb_perlin.h"
#undef STB_PERLIN_IMPLEMENTATION
#pragma warning( pop )
#endif // PIXIE_BUILD_IMPLEMENTATION
/*
------------------------------------------------------------------------------
This software is available under 2 licenses - you may choose the one you like.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2017 Mattias Gustavsson
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.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
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 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.
------------------------------------------------------------------------------
*/
| 29.98818 | 171 | 0.653252 | rdacomp |
0592ef0da60334bf4ac0e0780502fa56c526fa53 | 6,546 | cc | C++ | src/web_server/old/sim.cc | varqox/sim | b115a4e858dda1288917243e511751b835c28482 | [
"MIT"
] | 12 | 2017-11-05T21:02:58.000Z | 2022-03-28T23:11:51.000Z | src/web_server/old/sim.cc | varqox/sim | b115a4e858dda1288917243e511751b835c28482 | [
"MIT"
] | 11 | 2017-01-05T18:11:41.000Z | 2019-11-01T12:40:55.000Z | src/web_server/old/sim.cc | krzyk240/sim | b115a4e858dda1288917243e511751b835c28482 | [
"MIT"
] | 6 | 2016-12-25T11:22:34.000Z | 2020-10-20T16:03:51.000Z | #include "src/web_server/old/sim.hh"
#include "simlib/mysql/mysql.hh"
#include "simlib/path.hh"
#include "simlib/random.hh"
#include "simlib/time.hh"
#include "src/web_server/http/request.hh"
#include "src/web_server/http/response.hh"
#include <memory>
#include <sys/stat.h>
using sim::users::User;
using std::string;
namespace web_server::old {
Sim::Sim() { web_worker = std::make_unique<web_worker::WebWorker>(mysql); }
http::Response Sim::handle(http::Request req) {
request = std::move(req);
resp = http::Response(http::Response::TEXT);
stdlog(request.target);
// TODO: this is pretty bad-looking
auto hard_error500 = [&] {
resp.status_code = "500 Internal Server Error";
resp.headers["Content-Type"] = "text/html; charset=utf-8";
resp.content = "<!DOCTYPE html>"
"<html lang=\"en\">"
"<head><title>500 Internal Server Error</title></head>"
"<body>"
"<center>"
"<h1>500 Internal Server Error</h1>"
"<p>Try to reload the page in a few seconds.</p>"
"<button onclick=\"history.go(0)\">Reload</button>"
"</center>"
"</body>"
"</html>";
};
try {
STACK_UNWINDING_MARK;
// Try to handle the request using the new request handling
auto res = web_worker->handle(std::move(request));
if (auto* response = std::get_if<http::Response>(&res)) {
return *response;
}
request = std::move(std::get<http::Request>(res));
try {
STACK_UNWINDING_MARK;
url_args = RequestUriParser{request.target};
StringView next_arg = url_args.extract_next_arg();
// Reset state
page_template_began = false;
notifications.clear();
session = std::nullopt;
form_validation_error = false;
// Check CSRF token
if (request.method == http::Request::POST) {
// If no session is open, load value from cookie to pass
// verification
if (session_open() and
request.form_fields.get("csrf_token").value_or("") != session->csrf_token)
{
error403();
goto cleanup;
}
}
if (next_arg == "kit") {
// Subsystems that do not need the session to be opened
static_file();
} else {
// Other subsystems need the session to be opened in order to
// work properly
session_open();
if (next_arg == "c") {
contests_handle();
} else if (next_arg == "s") {
submissions_handle();
} else if (next_arg == "u") {
users_handle();
} else if (next_arg == "") {
main_page();
} else if (next_arg == "api") {
api_handle();
} else if (next_arg == "p") {
problems_handle();
} else if (next_arg == "contest_file") {
contest_file_handle();
} else if (next_arg == "jobs") {
jobs_handle();
} else if (next_arg == "file") {
file_handle();
} else if (next_arg == "logs") {
view_logs();
} else {
error404();
}
}
cleanup:
page_template_end();
// Make sure that the session is closed
session_close();
#ifdef DEBUG
if (notifications.size != 0) {
THROW("There are notifications left: ", notifications);
}
#endif
} catch (const std::exception& e) {
ERRLOG_CATCH(e);
error500();
session_close(); // Prevent session from being left open
} catch (...) {
ERRLOG_CATCH();
error500();
session_close(); // Prevent session from being left open
}
} catch (const std::exception& e) {
ERRLOG_CATCH(e);
// We cannot use error500() because it will probably throw
hard_error500();
session = std::nullopt; // Prevent session from being left open
} catch (...) {
ERRLOG_CATCH();
// We cannot use error500() because it will probably throw
hard_error500();
session = std::nullopt; // Prevent session from being left open
}
return std::move(resp);
}
void Sim::main_page() {
STACK_UNWINDING_MARK;
page_template("Main page");
append("main_page();");
}
void Sim::static_file() {
STACK_UNWINDING_MARK;
string file_path = concat_tostr(
"static",
path_absolute(intentional_unsafe_string_view(
decode_uri(substring(request.target, 1, request.target.find('?'))))));
// Extract path (ignore query)
D(stdlog(file_path);)
// Get file stat
struct stat attr {};
if (stat(file_path.c_str(), &attr) != -1) {
// Extract time of last modification
resp.headers["last-modified"] = date("%a, %d %b %Y %H:%M:%S GMT", attr.st_mtime);
resp.set_cache(true, 100 * 24 * 60 * 60, false); // 100 days
// If "If-Modified-Since" header is set and its value is not lower than
// attr.st_mtime
struct tm client_mtime {};
auto if_modified_since = request.headers.get("if-modified-since");
if (if_modified_since and
strptime(if_modified_since->data(), "%a, %d %b %Y %H:%M:%S GMT", &client_mtime) !=
nullptr and
timegm(&client_mtime) >= attr.st_mtime)
{
resp.status_code = "304 Not Modified";
return;
}
}
resp.content_type = http::Response::FILE;
resp.content = std::move(file_path);
}
void Sim::view_logs() {
STACK_UNWINDING_MARK;
// TODO: convert it to some kind of permissions
if (!session.has_value()) {
return error403();
}
switch (session->user_type) {
case User::Type::ADMIN: break;
case User::Type::TEACHER:
case User::Type::NORMAL: return error403();
}
page_template("Logs");
append("tab_logs_view($('body'));");
}
} // namespace web_server::old
| 29.754545 | 94 | 0.517721 | varqox |
0594c5f21f74a434e815da459f6e374fc53c160e | 511 | cpp | C++ | 448/findDisappearedNumbers.cpp | Lixu518/leetcode | f8e868ef6963da92237e6dc6888d7dda0b9bdd19 | [
"MIT"
] | 1 | 2018-06-24T13:58:07.000Z | 2018-06-24T13:58:07.000Z | 448/findDisappearedNumbers.cpp | Lixu518/leetcode | f8e868ef6963da92237e6dc6888d7dda0b9bdd19 | [
"MIT"
] | null | null | null | 448/findDisappearedNumbers.cpp | Lixu518/leetcode | f8e868ef6963da92237e6dc6888d7dda0b9bdd19 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
using namespace std;
vector<int> findDisappearedNumbers(vector<int>& nums) {
vector<int>res;
int i = 0;
while(i < nums.size()){
if(nums[i] != nums[nums[i] - 1]) swap(nums[i], nums[nums[i] - 1]);
else i++;
}
for(int i = 0;i < nums.size();i++){
if(nums[i] != i + 1)res.push_back(i+1);
}
return res;
}
int main(){
vector<int>nums = {4,3,2,7,8,2,3,1};
vector<int>res = findDisappearedNumbers(nums);
for(auto num :res)
cout<<num<<" ";
cout<<endl;
return 0;
}
| 20.44 | 68 | 0.610568 | Lixu518 |
0598abe3105f0dea9bdafe60826c66b646257788 | 1,932 | cpp | C++ | lab14/0-1 - set.cpp | uiowa-cs-3210-0001/cs3210-labs | d6263d719a45257ba056a1ead7cc3dd428d377f3 | [
"MIT"
] | 1 | 2019-01-24T14:04:45.000Z | 2019-01-24T14:04:45.000Z | lab14/0-1 - set.cpp | uiowa-cs-3210-0001/cs3210-labs | d6263d719a45257ba056a1ead7cc3dd428d377f3 | [
"MIT"
] | 1 | 2019-01-24T18:32:45.000Z | 2019-01-28T04:10:28.000Z | lab14/0-1 - set.cpp | uiowa-cs-3210-0001/cs3210-labs | d6263d719a45257ba056a1ead7cc3dd428d377f3 | [
"MIT"
] | 1 | 2019-02-07T00:28:20.000Z | 2019-02-07T00:28:20.000Z | #include <iostream>
#include <set>
#include <stdexcept>
using namespace std;
struct Student
{
string name;
string email;
string id;
};
namespace std {
template<>
struct less<Student>
{
using is_transparent = void;
bool operator()( Student const& lhs, Student const& rhs ) const
{
return lhs.email < rhs.email;
}
bool operator()( Student const& lhs, string const& email ) const
{
return lhs.email < email;
}
bool operator()( string const& email, Student const& rhs ) const
{
return email < rhs.email;
}
};
}
struct less_by_id
{
bool operator()( Student const& lhs, Student const& rhs ) const
{
return lhs.id < rhs.id;
}
};
using Students = set<Student>;
using StudentsById = set<Student,less_by_id>;
Student find_by_email(
Students const& students,
string const& email
)
{
auto iter = students.find( email );
if ( iter != students.end() )
return *iter;
// for ( auto const& s : students )
// if ( s.email == email )
// return s;
throw runtime_error( "No student with email " + email );
}
int main()
{
Students students;
students.insert( { "Alice", "alice@uiowa.edu" } );
students.insert( { "Bob", "Bob@uiowa.edu" } );
students.erase( { "Bob", "Bob@uiowa.edu" } );
auto iter = students.count( "Bob@uiowa.edu" );
// { "Alice", "alice@uiowa.edu" },
// { "Bob", "Bob@uiowa.edu" },
// { "Karl", "karl@uiowa.edu" },
// { "Zoe", "zoe@uiowa.edu" },
// { "Zoe Salinger", "zoe@uiowa.edu" },
// { "Zoe Salinger", "zoe@uiowa.edu" }
// };
for ( auto const& s : students )
cout << s.name << endl;
try {
auto r = find_by_email( students, "zoe@uiowa.edu" );
// cout << r.name << endl;
}
catch ( exception const& x )
{
cout << x.what();
}
}
| 19.32 | 68 | 0.547101 | uiowa-cs-3210-0001 |
05a097e584b97f39957ed6c38bd4a705b6786114 | 4,078 | cc | C++ | src/StandAlone/tools/mpi_test/async_mpi_test.cc | damu1000/Uintah | 0c768664c1fe0a80eff2bbbd9b837e27f281f0a5 | [
"MIT"
] | 2 | 2021-12-17T05:50:44.000Z | 2021-12-22T21:37:32.000Z | src/StandAlone/tools/mpi_test/async_mpi_test.cc | damu1000/Uintah | 0c768664c1fe0a80eff2bbbd9b837e27f281f0a5 | [
"MIT"
] | null | null | null | src/StandAlone/tools/mpi_test/async_mpi_test.cc | damu1000/Uintah | 0c768664c1fe0a80eff2bbbd9b837e27f281f0a5 | [
"MIT"
] | 1 | 2020-11-30T04:46:05.000Z | 2020-11-30T04:46:05.000Z | /*
* The MIT License
*
* Copyright (c) 1997-2020 The University of Utah
*
* 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 <Core/Parallel/UintahMPI.h>
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <vector>
#include <queue>
#include <unistd.h>
#include <sys/time.h>
#define debug_main
#define debug_main_thread
#define debug_mpi_thread
using namespace std;
int message_size = 5*1024*1024;
void do_some_work(int myid);
int
main(int argc, char** argv)
{
int thread_supported = 0;
char *send_buf;
char *send_buf2;
char *recv_buf;
char *recv_buf2;
int myid = 99;
int dest = 0;
int numprocs = 99;
int tag = 1;
Uintah::MPI::Init_thread(&argc, &argv, MPI_THREAD_FUNNELED, &thread_supported);
#ifdef debug_main
cout<<"Thread supported is "<<thread_supported<<endl;
#endif
Uintah::MPI::Comm_size(MPI_COMM_WORLD, &numprocs);
Uintah::MPI::Comm_rank(MPI_COMM_WORLD, &myid);
srand(myid*10);
do_some_work(myid);
if (myid == 0){
dest = 1;
}
else {
dest = 0;
}
send_buf = new char[message_size];
send_buf2 = new char[message_size];
recv_buf = new char[message_size];
recv_buf2 = new char[message_size];
MPI_Request rq1;
MPI_Request rq2;
MPI_Request rq3;
MPI_Status st1;
MPI_Status st2;
MPI_Status st3;
if (myid == 1){
sprintf((char*)send_buf, "this a message sent from myid1, signed Bruce R. Kanobi");
Uintah::MPI::Isend(send_buf, message_size, MPI_CHAR, dest, tag, MPI_COMM_WORLD, &rq1);
sprintf((char*)send_buf2, "this a 2nd message sent from myid1, signed Bruce R. Kanobi");
Uintah::MPI::Isend(send_buf2, message_size, MPI_CHAR, dest, tag+5, MPI_COMM_WORLD, &rq2);
}
else{
Uintah::MPI::Recv(recv_buf, message_size, MPI_CHAR, dest, tag, MPI_COMM_WORLD, &st1);
cout<<"0 Got message "<<recv_buf<<endl;
}
do_some_work(myid);
if (myid == 1){
Uintah::MPI::Recv(recv_buf, message_size, MPI_CHAR, dest, tag, MPI_COMM_WORLD,&st2);
cout<<"1 Got message "<<recv_buf<<endl;
}
else{
sprintf(send_buf, "this a message sent from myid0, signed Thomas S. Duku");
Uintah::MPI::Isend(send_buf, message_size, MPI_CHAR, dest, tag, MPI_COMM_WORLD, &rq3);
Uintah::MPI::Recv(recv_buf2, message_size, MPI_CHAR, dest, tag+5, MPI_COMM_WORLD,&st3);
cout<<"0 Got message "<<recv_buf2<<endl;
}
do_some_work(myid);
//MPI_Status status2[1];
//int* probe_flag = new int(0);
//Uintah::MPI::Iprobe(MPI_ANY_SOURCE,MPI_ANY_TAG,MPI_COMM_WORLD,probe_flag,status2);
//if (*probe_flag){
// cout<<"myid"<<myid<<" has outstading communications"<<endl;
//}
#ifdef debug_main
//cout<<"myid"<<myid<<" mpiCallQueue"<<MPICommObj.mpiCallQueue.size()<<endl;
#endif
Uintah::MPI::Finalize();
return 0;
}
void
do_some_work(int myid)
{
const int sleep_time_constant = 5000000;
//const int sleep_time_constant = 1000000;
int sleep_time_total = 0;
sleep_time_total = sleep_time_constant + (rand()%1000000);
cout<<myid<<" is sleeping for "<<sleep_time_total<<endl;
usleep(sleep_time_total);
}
| 29.338129 | 93 | 0.709662 | damu1000 |
05a401e09ae76a2aec7b9c8079570ff68a28a352 | 5,953 | hpp | C++ | include/sdsl/sorted_stack_support.hpp | wolfee001/sdsl-lite | 3061a0b64f75f070bb8f4a1f91e570fcfc7ebe75 | [
"BSD-3-Clause"
] | 54 | 2017-03-23T23:10:40.000Z | 2022-03-22T14:25:11.000Z | include/sdsl/sorted_stack_support.hpp | wolfee001/sdsl-lite | 3061a0b64f75f070bb8f4a1f91e570fcfc7ebe75 | [
"BSD-3-Clause"
] | 65 | 2017-05-09T05:28:43.000Z | 2021-12-16T13:02:25.000Z | include/sdsl/sorted_stack_support.hpp | wolfee001/sdsl-lite | 3061a0b64f75f070bb8f4a1f91e570fcfc7ebe75 | [
"BSD-3-Clause"
] | 23 | 2017-03-23T23:11:44.000Z | 2022-02-20T22:36:33.000Z | // Copyright (c) 2016, the SDSL Project Authors. All rights reserved.
// Please see the AUTHORS file for details. Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.
/*!\file sorted_stack_support.hpp
* \author Simon Gog
*/
#ifndef INCLUDED_SDSL_SORTED_STACK_SUPPORT
#define INCLUDED_SDSL_SORTED_STACK_SUPPORT
#include <sdsl/int_vector.hpp>
namespace sdsl
{
//! A stack which contains strictly increasing numbers in the range from \f$0\f$ to \f$n\f$.
/*!
* \par Reference
* Johannes Fischer:
* Optimal Succinctness for Range Minimum Queries
* LATIN 2010
*
* \par Space complexity
* \f$n\f$ bits
*/
class sorted_stack_support
{
public:
typedef int_vector<64>::size_type size_type;
private:
size_type m_n; // Size of the supported vector.
size_type m_cnt; // Counter for the indices on the stack.
size_type m_top; // Topmost index of the stack.
int_vector<64> m_stack; // Memory for the stack.
inline size_type block_nr(size_type x) { return x / 63; }; // TODO: maybe we can speed this up with bit hacks
inline size_type block_pos(size_type x) { return x % 63; }; // TODO: maybe we can speed this up with bit hacks
public:
//! Constructor
/*!\param n Maximum that can be pushed onto the stack
*/
sorted_stack_support(size_type n);
sorted_stack_support(const sorted_stack_support &) = default;
sorted_stack_support(sorted_stack_support &&) = default;
sorted_stack_support & operator=(const sorted_stack_support &) = default;
sorted_stack_support & operator=(sorted_stack_support &&) = default;
/*! Returns if the stack is empty.
*/
bool empty() const { return 0 == m_cnt; };
/*! Returns the topmost index on the stack.
* \pre empty()==false
*/
size_type top() const;
/*! Pop the topmost index of the stack.
*/
void pop();
/*! Push the index x of vector vec onto the stack.
* \par x Index of the value in vec which should be pushed onto the stack.
* \pre top() < x and x <= n
*/
void push(size_type x);
/*! Returns the number of element is the stack.
*/
size_type size() const { return m_cnt; };
size_type serialize(std::ostream & out, structure_tree_node * v = nullptr, std::string name = "") const;
void load(std::istream & in);
template <typename archive_t>
void CEREAL_SAVE_FUNCTION_NAME(archive_t & ar) const;
template <typename archive_t>
void CEREAL_LOAD_FUNCTION_NAME(archive_t & ar);
bool operator==(sorted_stack_support const & other) const noexcept;
bool operator!=(sorted_stack_support const & other) const noexcept;
};
inline sorted_stack_support::sorted_stack_support(size_type n)
: m_n(n)
, m_cnt(0)
, m_top(0)
, m_stack()
{
m_stack = int_vector<64>(block_nr(m_n + 1) + 1, 0);
m_stack[0] = 1;
}
inline sorted_stack_support::size_type sorted_stack_support::top() const
{
assert(empty() == false);
return m_top - 1;
}
inline void sorted_stack_support::push(size_type x)
{
assert((empty() or top() < x) and x <= m_n);
x += 1;
++m_cnt; //< increment counter
size_type bn = block_nr(x);
m_stack[bn] ^= (1ULL << block_pos(x));
if (bn > 0 and m_stack[bn - 1] == 0) { m_stack[bn - 1] = 0x8000000000000000ULL | m_top; }
m_top = x;
}
inline void sorted_stack_support::pop()
{
if (!empty())
{
--m_cnt; //< decrement counter
size_type bn = block_nr(m_top);
uint64_t w = m_stack[bn];
assert((w >> 63) == 0); // highest bit is not set, as the block contains no pointer
w ^= (1ULL << block_pos(m_top));
m_stack[bn] = w;
if (w > 0) { m_top = bn * 63 + bits::hi(w); }
else
{ // w==0 and cnt>0
assert(bn > 0);
w = m_stack[bn - 1];
if ((w >> 63) == 0)
{ // highest bit is not set => the block contains no pointer
assert(w > 0);
m_top = (bn - 1) * 63 + bits::hi(w);
}
else
{ // block contains pointers
m_stack[bn - 1] = 0;
m_top = w & 0x7FFFFFFFFFFFFFFFULL;
}
}
}
}
inline sorted_stack_support::size_type sorted_stack_support::serialize(std::ostream & out,
structure_tree_node * v,
std::string name) const
{
structure_tree_node * child = structure_tree::add_child(v, name, util::class_name(*this));
size_type written_bytes = 0;
written_bytes += write_member(m_n, out);
written_bytes += write_member(m_top, out);
written_bytes += write_member(m_cnt, out);
written_bytes += m_stack.serialize(out);
structure_tree::add_size(child, written_bytes);
return written_bytes;
}
inline void sorted_stack_support::load(std::istream & in)
{
read_member(m_n, in);
read_member(m_top, in);
read_member(m_cnt, in);
m_stack.load(in);
}
template <typename archive_t>
void sorted_stack_support::CEREAL_SAVE_FUNCTION_NAME(archive_t & ar) const
{
ar(CEREAL_NVP(m_n));
ar(CEREAL_NVP(m_cnt));
ar(CEREAL_NVP(m_top));
ar(CEREAL_NVP(m_stack));
}
template <typename archive_t>
void sorted_stack_support::CEREAL_LOAD_FUNCTION_NAME(archive_t & ar)
{
ar(CEREAL_NVP(m_n));
ar(CEREAL_NVP(m_cnt));
ar(CEREAL_NVP(m_top));
ar(CEREAL_NVP(m_stack));
}
//! Equality operator.
inline bool sorted_stack_support::operator==(sorted_stack_support const & other) const noexcept
{
return (m_n == other.m_n) && (m_cnt == other.m_cnt) && (m_top == other.m_top) && (m_stack == other.m_stack);
}
//! Inequality operator.
inline bool sorted_stack_support::operator!=(sorted_stack_support const & other) const noexcept
{
return !(*this == other);
}
} // end namespace sdsl
#endif // end file
| 31.005208 | 114 | 0.629934 | wolfee001 |
05a4a12012a2e275dd1b79ae4774c50276b41d9f | 167 | hpp | C++ | include/nocopy/fwd/box.hpp | mikezackles/nocopy | 7ddae640e88b2bc2ab3b1130d16616da2f673c2a | [
"Apache-2.0"
] | null | null | null | include/nocopy/fwd/box.hpp | mikezackles/nocopy | 7ddae640e88b2bc2ab3b1130d16616da2f673c2a | [
"Apache-2.0"
] | null | null | null | include/nocopy/fwd/box.hpp | mikezackles/nocopy | 7ddae640e88b2bc2ab3b1130d16616da2f673c2a | [
"Apache-2.0"
] | null | null | null | #ifndef UUID_E46E9091_283C_46FE_ACE3_6712B60338C7
#define UUID_E46E9091_283C_46FE_ACE3_6712B60338C7
namespace nocopy {
template <typename T>
class box;
}
#endif
| 16.7 | 49 | 0.832335 | mikezackles |
05a5fcdafd4c1055445151eb6ca06fb0e4231789 | 6,044 | cpp | C++ | case/weatherwidget.cpp | dreamtravel/Sensor_PC | 7fa7b4acd217fd97ada5c19a7127d0332b1e6256 | [
"MIT"
] | null | null | null | case/weatherwidget.cpp | dreamtravel/Sensor_PC | 7fa7b4acd217fd97ada5c19a7127d0332b1e6256 | [
"MIT"
] | null | null | null | case/weatherwidget.cpp | dreamtravel/Sensor_PC | 7fa7b4acd217fd97ada5c19a7127d0332b1e6256 | [
"MIT"
] | null | null | null | /*****************************************************************************
**
**Copyright (C) 2014 UP-TECH Corporation and/or its subsidiary(-ies).
**All rights reserved.
**Contact: UP-TECH Corporation (anld@up-tech.com)
**
**This file is the weather interface class of Sensor platform system software.
**
*****************************************************************************/
#include "weatherwidget.h"
#include "ui_weatherwidget.h"
#include "tool/mydelay.h"
#include <QDateTime>
#include <QString>
#include <QSqlQuery>
#include <QTimer>
#include<QTextCodec>
WeatherWidget::WeatherWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::WeatherWidget)
{
ui->setupUi(this);
ui->stackedWidget->setCurrentIndex(0);
QDateTime time = QDateTime::currentDateTime();
QString str = time.toString(QObject::tr("yyyy.MM.dd dddd (hh:mmAP)实况"));
ui->label_time->setText(str);
//QTextCodec* codec = QTextCodec::codecForName("UTF-8");
//QTextCodec::setCodecForLocale(codec);
//QTextCodec::setCodecForCStrings(codec);
//QTextCodec::setCodecForTr(codec);
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(getCurTime()));
timer->start(1000);
ui->pushButton_Save->setStyleSheet("QPushButton{border-image: url(:/new/prefix1/res/weather-sensor/save1.png);}"
"QPushButton:hover{border-image: url(:/new/prefix1/res/weather-sensor/save1.png);}"
"QPushButton:pressed{border-image: url(:/new/prefix1/res/weather-sensor/save2.png);}");
ui->pushButton_Query->setStyleSheet("QPushButton{border-image: url(:/new/prefix1/res/weather-sensor/query1.png);}"
"QPushButton:hover{border-image: url(:/new/prefix1/res/weather-sensor/query1.png);}"
"QPushButton:pressed{border-image: url(:/new/prefix1/res/weather-sensor/query2.png);}");
ui->pushButton_Close->setStyleSheet("QPushButton{border-image: url(:/new/prefix1/res/main/button1.png);}"
"QPushButton:hover{border-image: url(:/new/prefix1/res/main/button1.png);}"
"QPushButton:pressed{border-image: url(:/new/prefix1/res/main/button2.png);}");
ui->pushButton_Return->setStyleSheet("QPushButton{border-image: url(:/new/prefix1/res/main/button1.png);}"
"QPushButton:hover{border-image: url(:/new/prefix1/res/main/button1.png);}"
"QPushButton:pressed{border-image: url(:/new/prefix1/res/main/button2.png);}");
ui->label_notice->setWordWrap(true);
ui->label_notice->setAlignment(Qt::AlignTop);
ui->label_notice->setText(QObject::tr("应该避免外出,敏感的人应该呆在室内,关闭门窗。"));
}
WeatherWidget::~WeatherWidget()
{
delete ui;
}
void WeatherWidget::on_pushButton_Save_clicked()
{
QSqlQuery query;
query.exec(QObject::tr("insert into weather (时间, 状态, 光照, 气压, 温度, 湿度, 粉尘, 紫外线) "
"values(?, ?, ?, ?, ?, ?, ?, ?)"));
query.addBindValue(ui->label_time->text());
query.addBindValue(ui->label_rs->text());
query.addBindValue(ui->label_ilin->text());
query.addBindValue(ui->label_aipr->text());
query.addBindValue(ui->label_temp->text());
query.addBindValue(ui->label_hum->text());
query.addBindValue(ui->label_dust->text());
query.addBindValue(ui->label_ulr->text());
query.exec();
MyDelay *delay = new MyDelay(3);
connect(delay, SIGNAL(TimeOut()), this, SLOT(clearText()));
ui->label_savestatus->setText(QObject::tr("保存成功"));
delay->start();
}
void WeatherWidget::on_pushButton_Query_clicked()
{
model = new QSqlTableModel(this);
model->setTable("weather");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->select();
ui->tableView->setModel(model);
ui->tableView->setColumnWidth(0,250);
ui->tableView->setColumnWidth(1,50);
ui->tableView->setColumnWidth(2,50);
ui->tableView->setColumnWidth(3,50);
ui->tableView->setColumnWidth(4,50);
ui->tableView->setColumnWidth(5,50);
ui->tableView->setColumnWidth(6,50);
ui->tableView->setColumnWidth(7,70);
ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->stackedWidget->setCurrentIndex(1);
}
void WeatherWidget::on_pushButton_Close_clicked()
{
emit closeCurrentPage();
}
void WeatherWidget::on_pushButton_Return_clicked()
{
ui->stackedWidget->setCurrentIndex(0);
}
void WeatherWidget::getData(Data *data)
{
if(data->rnsw == 0){
ui->label->setStyleSheet("border-image: url(:/new/prefix1/res/weather-sensor/fine.png);");
ui->label_rs->setText(QObject::tr("晴"));
}
else if(data->rnsw == 1){
ui->label->setStyleSheet("border-image: url(:/new/prefix1/res/weather-sensor/rain.png);");
ui->label_rs->setText(QObject::tr("雨"));
}
ui->label_temp->setNum(data->sht.a);
ui->label_aipr->setText(QString::number(data->aipr,'f',2));
ui->label_hum->setText(QString::number(data->sht.b,'f',2));
ui->label_ilin->setText(QString::number(data->ilin,'f',2));
ui->label_dust->setNum(data->dust);
ui->label_ulr->setNum(data->ulr);
if(data->dust==0)
{
ui->label_9->setText(QObject::tr("空气良好"));
ui->label_notice->setText(QObject::tr("适宜外出,多出去走走,去呼吸新鲜空气吧!"));
}
else if(data->dust==0.1)
{
ui->label_9->setText(QObject::tr("中度污染"));
ui->label_notice->setText(QObject::tr("减少外出,空气中的颗粒物对您有害!"));
}
else
{
ui->label_9->setText(QObject::tr("严重污染"));
ui->label_notice->setText(QObject::tr("应该避免外出,敏感的人应该呆在室内,关闭门窗。"));
}
}
void WeatherWidget::getCurTime()
{
QDateTime time = QDateTime::currentDateTime();
QString str = time.toString(QObject::tr("yyyy.MM.dd dddd(hh:mm:ss)实况"));
ui->label_time->setText(str);
}
void WeatherWidget::clearText()
{
ui->label_savestatus->setText("");
}
| 38.496815 | 130 | 0.622105 | dreamtravel |
05a69a35ba28111bfbf8867ab92f947a1be54fd7 | 623 | cpp | C++ | baekjoonOnlineJudge/3040/main.cpp | sdkcoding/baekjoonOnlineJudge | de36e501021a9a4ed5d2676a46627013bbf2c70f | [
"Apache-2.0"
] | null | null | null | baekjoonOnlineJudge/3040/main.cpp | sdkcoding/baekjoonOnlineJudge | de36e501021a9a4ed5d2676a46627013bbf2c70f | [
"Apache-2.0"
] | null | null | null | baekjoonOnlineJudge/3040/main.cpp | sdkcoding/baekjoonOnlineJudge | de36e501021a9a4ed5d2676a46627013bbf2c70f | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int sum = 0;
int len = 9;
int* numList = new int[len]{ 0 };
for (int i = 0; i < len; i++) {
scanf("%d", &numList[i]);
sum += numList[i];
}
int idx1 = 0, idx2 = 0;
bool flag = false;
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
if (sum - (numList[i] + numList[j]) == 100) {
idx1 = i; idx2 = j; flag = true;
break;
}
}
if (flag) {
break;
}
}
for (int i = 0; i < len; i++) {
if ((idx1 != i) && (idx2 != i)) {
printf("%d\n", numList[i]);
}
}
delete[] numList;
return 0;
} | 16.394737 | 48 | 0.476726 | sdkcoding |
05a90d4dcfd35fa7eb2e47bab826cc6aa911913b | 5,323 | cpp | C++ | tests/argos-Core-Tests/Text/TextSpanTests.cpp | henrikfroehling/interlinck | d9d947b890d9286c6596c687fcfcf016ef820d6b | [
"MIT"
] | null | null | null | tests/argos-Core-Tests/Text/TextSpanTests.cpp | henrikfroehling/interlinck | d9d947b890d9286c6596c687fcfcf016ef820d6b | [
"MIT"
] | 19 | 2021-12-01T20:37:23.000Z | 2022-02-14T21:05:43.000Z | tests/argos-Core-Tests/Text/TextSpanTests.cpp | henrikfroehling/interlinck | d9d947b890d9286c6596c687fcfcf016ef820d6b | [
"MIT"
] | null | null | null | #include <catch2/catch.hpp>
#include <argos-Core/Text/TextSpan.hpp>
using argos::Core::Text::TextSpan;
TEST_CASE("TextSpan default constructor", "[Core][Text]")
{
const TextSpan span{};
REQUIRE(span.start() == 0);
REQUIRE(span.end() == 0);
REQUIRE(span.length() == 0);
REQUIRE(span.isEmpty());
REQUIRE(span.toString() == "[0..0]");
}
TEST_CASE("TextSpan explicit constructor (1, 5)", "[Core][Text]")
{
const TextSpan span{1, 5};
REQUIRE(span.start() == 1);
REQUIRE(span.end() == 6);
REQUIRE(span.length() == 5);
REQUIRE_FALSE(span.isEmpty());
REQUIRE(span.toString() == "[1..6]");
}
TEST_CASE("TextSpan::fromBounds()", "[Core][Text]")
{
const auto span = TextSpan::fromBounds(1, 5);
REQUIRE(span.start() == 1);
REQUIRE(span.end() == 5);
REQUIRE(span.length() == 4);
REQUIRE_FALSE(span.isEmpty());
REQUIRE(span.toString() == "[1..5]");
}
TEST_CASE("TextSpan::contains(position)", "[Core][Text]")
{
const auto span = TextSpan::fromBounds(1, 3);
REQUIRE_FALSE(span.contains(0));
REQUIRE(span.contains(1));
REQUIRE(span.contains(2));
REQUIRE(span.contains(3));
REQUIRE_FALSE(span.contains(4));
}
TEST_CASE("TextSpan::contains(TextSpan)", "[Core][Text]")
{
const auto span = TextSpan::fromBounds(1, 5);
REQUIRE(span.contains(TextSpan::fromBounds(2, 4)));
REQUIRE(span.contains(TextSpan::fromBounds(1, 2)));
REQUIRE(span.contains(TextSpan::fromBounds(4, 5)));
REQUIRE_FALSE(span.contains(TextSpan::fromBounds(0, 1)));
REQUIRE_FALSE(span.contains(TextSpan::fromBounds(5, 6)));
}
TEST_CASE("TextSpan::overlapsWith()", "[Core][Text]")
{
const auto span = TextSpan::fromBounds(1, 5);
REQUIRE(span.overlapsWith(TextSpan::fromBounds(2, 4)));
REQUIRE(span.overlapsWith(TextSpan::fromBounds(1, 2)));
REQUIRE(span.overlapsWith(TextSpan::fromBounds(4, 5)));
REQUIRE(span.overlapsWith(TextSpan::fromBounds(0, 1)));
REQUIRE(span.overlapsWith(TextSpan::fromBounds(5, 6)));
}
TEST_CASE("TextSpan::overlapOf()", "[Core][Text]")
{
const auto span = TextSpan::fromBounds(1, 5);
auto overlapSpan = span.overlapOf(TextSpan::fromBounds(2, 4));
REQUIRE_FALSE(overlapSpan.isEmpty());
REQUIRE(overlapSpan.start() == 2);
REQUIRE(overlapSpan.end() == 4);
REQUIRE(overlapSpan.length() == 2);
overlapSpan = span.overlapOf(TextSpan::fromBounds(1, 2));
REQUIRE_FALSE(overlapSpan.isEmpty());
REQUIRE(overlapSpan.start() == 1);
REQUIRE(overlapSpan.end() == 2);
REQUIRE(overlapSpan.length() == 1);
overlapSpan = span.overlapOf(TextSpan::fromBounds(4, 5));
REQUIRE_FALSE(overlapSpan.isEmpty());
REQUIRE(overlapSpan.start() == 4);
REQUIRE(overlapSpan.end() == 5);
REQUIRE(overlapSpan.length() == 1);
overlapSpan = span.overlapOf(TextSpan::fromBounds(0, 1));
REQUIRE(overlapSpan.isEmpty());
REQUIRE(overlapSpan.start() == 1);
REQUIRE(overlapSpan.end() == 1);
REQUIRE(overlapSpan.length() == 0);
overlapSpan = span.overlapOf(TextSpan::fromBounds(5, 6));
REQUIRE(overlapSpan.isEmpty());
REQUIRE(overlapSpan.start() == 5);
REQUIRE(overlapSpan.end() == 5);
REQUIRE(overlapSpan.length() == 0);
}
TEST_CASE("TextSpan::intersectsWith(position)", "[Core][Text]")
{
const auto span = TextSpan::fromBounds(1, 3);
REQUIRE_FALSE(span.intersectsWith(0));
REQUIRE(span.intersectsWith(1));
REQUIRE(span.intersectsWith(2));
REQUIRE(span.intersectsWith(3));
REQUIRE_FALSE(span.intersectsWith(4));
}
TEST_CASE("TextSpan::intersectsWith(TextSpan)", "[Core][Text]")
{
const auto span = TextSpan::fromBounds(1, 5);
REQUIRE(span.intersectsWith(TextSpan::fromBounds(2, 4)));
REQUIRE(span.intersectsWith(TextSpan::fromBounds(1, 2)));
REQUIRE(span.intersectsWith(TextSpan::fromBounds(4, 5)));
REQUIRE(span.intersectsWith(TextSpan::fromBounds(0, 1)));
REQUIRE(span.intersectsWith(TextSpan::fromBounds(5, 6)));
}
TEST_CASE("TextSpan::intersectionOf()", "[Core][Text]")
{
const auto span = TextSpan::fromBounds(1, 5);
auto intersectionSpan = span.intersectionOf(TextSpan::fromBounds(2, 4));
REQUIRE_FALSE(intersectionSpan.isEmpty());
REQUIRE(intersectionSpan.start() == 2);
REQUIRE(intersectionSpan.end() == 4);
REQUIRE(intersectionSpan.length() == 2);
intersectionSpan = span.intersectionOf(TextSpan::fromBounds(1, 2));
REQUIRE_FALSE(intersectionSpan.isEmpty());
REQUIRE(intersectionSpan.start() == 1);
REQUIRE(intersectionSpan.end() == 2);
REQUIRE(intersectionSpan.length() == 1);
intersectionSpan = span.intersectionOf(TextSpan::fromBounds(4, 5));
REQUIRE_FALSE(intersectionSpan.isEmpty());
REQUIRE(intersectionSpan.start() == 4);
REQUIRE(intersectionSpan.end() == 5);
REQUIRE(intersectionSpan.length() == 1);
intersectionSpan = span.intersectionOf(TextSpan::fromBounds(0, 1));
REQUIRE(intersectionSpan.isEmpty());
REQUIRE(intersectionSpan.start() == 1);
REQUIRE(intersectionSpan.end() == 1);
REQUIRE(intersectionSpan.length() == 0);
intersectionSpan = span.intersectionOf(TextSpan::fromBounds(5, 6));
REQUIRE(intersectionSpan.isEmpty());
REQUIRE(intersectionSpan.start() == 5);
REQUIRE(intersectionSpan.end() == 5);
REQUIRE(intersectionSpan.length() == 0);
}
| 32.656442 | 76 | 0.669172 | henrikfroehling |
05b255cd58da6b84bf85c9557ceb47335f294d6c | 1,331 | cpp | C++ | rpcclient.cpp | akshatpandya/AirSim-Plugin-App | 40a14cc38480ee9ecb8b7bed67addcc6d2723718 | [
"MIT"
] | null | null | null | rpcclient.cpp | akshatpandya/AirSim-Plugin-App | 40a14cc38480ee9ecb8b7bed67addcc6d2723718 | [
"MIT"
] | null | null | null | rpcclient.cpp | akshatpandya/AirSim-Plugin-App | 40a14cc38480ee9ecb8b7bed67addcc6d2723718 | [
"MIT"
] | null | null | null | #include "rpcclient.h"
RPCclient::RPCclient()
{
while(!((uint8_t)client.getConnectionState() == 1))
{
qDebug() << "Connecting to AirSim....." << (uint8_t)client.getConnectionState();;
client.confirmConnection();
}
while(!(client.isApiControlEnabled() == true))
{
qDebug() << "Enabling API control.....";
client.enableApiControl(true);
}
// joystick_manager = new joystick(&client);
}
void RPCclient::arm_disarm(bool arm)
{
if(arm == true)
client.armDisarm(true);
else
client.armDisarm(false);
}
void RPCclient::takeOff(float time_out)
{
client.takeoffAsync(time_out);
}
void RPCclient::moveByRC(RCData& rc_data)
{
// client.moveByVelocityAsync(rc_data.pitch*5, rc_data.roll*5, rc_data.throttle*5, 0.5, DrivetrainType::MaxDegreeOfFreedom, yaw_mode);
// client.rotateByYawRateAsync(rc_data.yaw*50, 0.5);
joystick_manager.move(rc_data, &client);
}
void RPCclient::moveByRCYaw(RCData &rc_data)
{
client.rotateByYawRateAsync(rc_data.yaw*50, 0.5);
}
void RPCclient::land(float time_out)
{
client.landAsync(time_out);
}
void RPCclient::disconnect()
{
client.reset();
}
MultirotorState RPCclient::getMultirotorState()
{
MultirotorState uav_state;
uav_state = client.getMultirotorState();
return uav_state;
}
| 21.819672 | 137 | 0.676935 | akshatpandya |
05b688d29b71b5c51eade760ad329ee71ef6a156 | 7,271 | cpp | C++ | src/Algorithms/RawArraySort.cpp | Straydragonl/DataStructure-Algorithm-Cpp | 276b6ca9df54f2425732f7c9c9e9dd60c59033d1 | [
"MIT"
] | 1 | 2018-12-20T09:41:49.000Z | 2018-12-20T09:41:49.000Z | src/Algorithms/RawArraySort.cpp | StrayDragon/DataStructure-Algorithm-Cpp | 276b6ca9df54f2425732f7c9c9e9dd60c59033d1 | [
"MIT"
] | 3 | 2018-10-15T06:49:39.000Z | 2018-10-25T13:09:36.000Z | src/Algorithms/RawArraySort.cpp | StrayDragon/DataStructure-Algorithm-Cpp | 276b6ca9df54f2425732f7c9c9e9dd60c59033d1 | [
"MIT"
] | null | null | null | //
// Created by straydragon on 18-10-16.
//
#include "RawArraySort.h"
#include <algorithm>
#include <typeinfo>
int RawArray::SortBy::HelperFunc::findIndexOfLargest(
const RawArray::ElementType* targetArray,
int size) {
int guessBiggestIndex = 0;
for (int cur = 1; cur < size; cur++) {
if (targetArray[cur] > targetArray[guessBiggestIndex])
guessBiggestIndex = cur;
}
return guessBiggestIndex;
}
void RawArray::SortBy::selectionSort(RawArray::ElementType* targetArray,
int size) {
int biggestIndex;
for (int last = size - 1; last >= 1; last--) {
biggestIndex = HelperFunc::findIndexOfLargest(targetArray, last + 1);
std::swap(targetArray[biggestIndex], targetArray[last]);
}
}
void RawArray::SortBy::bubbleSort(RawArray::ElementType* targetArray,
int size) {
bool sorted = false;
int pass = 1;
while (!sorted && (pass < size)) {
sorted = true;
for (int nextI, i = 0; i < size - pass; i++) {
nextI = i + 1;
if (targetArray[i] > targetArray[nextI]) {
std::swap(targetArray[i], targetArray[nextI]);
sorted = false;
}
}
#ifdef DEBUG
for (int i = 0; i < size - pass; i++) {
assert(targetArray[i] < targetArray[size - pass]);
}
#endif
pass++;
}
}
void RawArray::SortBy::insertionSort(RawArray::ElementType* targetArray,
int size) {
for (int unsorted = 0; unsorted < size; unsorted++) {
ElementType nextElement = targetArray[unsorted];
int cur = unsorted;
while ((cur > 0) && targetArray[cur - 1] > nextElement) {
targetArray[cur] = targetArray[cur - 1];
cur--;
}
targetArray[cur] = nextElement;
}
}
void RawArray::SortBy::insertionSort(ElementType targetArray[],
int first,
int last) {
for (int unsorted = first; unsorted <= last; unsorted++) {
ElementType nextElement = targetArray[unsorted];
int cur = unsorted;
while ((cur > 0) && targetArray[cur - 1] > nextElement) {
targetArray[cur] = targetArray[cur - 1];
cur--;
}
targetArray[cur] = nextElement;
}
}
void RawArray::SortBy::HelperFunc::merge(RawArray::ElementType* targetArray,
int first,
int mid,
int last) {
ElementType tmpArray[RawArray::MAX_SIZE];
int first1 = first;
int last1 = mid;
int first2 = mid + 1;
int last2 = last;
int i = first1;
while ((first1 <= last1) && (first2 <= last2)) {
if (targetArray[first1] <= targetArray[first2]) {
tmpArray[i] = targetArray[first1];
first1++;
} else {
tmpArray[i] = targetArray[first2];
first2++;
}
i++;
}
while (first1 <= last1) {
tmpArray[i] = targetArray[first1];
first1++;
i++;
}
while (first2 <= last2) {
tmpArray[i] = targetArray[first2];
first2++;
i++;
}
for (i = first; i <= last; i++)
targetArray[i] = tmpArray[i];
}
void RawArray::SortBy::mergeSort(RawArray::ElementType* targetArray,
int first,
int last) {
if (first < last) {
int mid = first + (last - first) / 2;
mergeSort(targetArray, first, mid);
mergeSort(targetArray, mid + 1, last);
HelperFunc::merge(targetArray, first, mid, last);
}
}
int RawArray::SortBy::HelperFunc::partition(RawArray::ElementType* targetArray,
int first,
int last) {
// 把原数组的第一个元素 targetArray[first]
// 中间元素 targetArray[(last - first) / 2]
// 最后一个元素 targetArray[last]
// 按元素大小排序,最后返回三元素排序后的中间位置元素下标
int mid = (last - first) / 2;
if (targetArray[first] > targetArray[mid]) {
std::swap(targetArray[first], targetArray[mid]);
}
#ifdef DEBUG
std::cout << first << " " << mid << " " << last << std::endl;
// std::cout << targetArray[first] << " " << targetArray[mid] << " "
// << targetArray[last] << std::endl;
#endif
if (targetArray[mid] > targetArray[last]) {
std::swap(targetArray[mid], targetArray[last]);
}
#ifdef DEBUG
std::cout << first << " " << mid << " " << last << std::endl;
// std::cout << targetArray[first] << " " << targetArray[mid] << " "
// << targetArray[last] << std::endl;
#endif
return mid;
}
void RawArray::SortBy::quickSort(RawArray::ElementType* targetArray,
int first,
int last) {
if (last - first + 1 < RawArray::MIN_SIZE) {
RawArray::SortBy::insertionSort(targetArray, first, last);
} else {
int pivotIndex = HelperFunc::partition(targetArray, first, last);
quickSort(targetArray, first + 1, pivotIndex + 1);
quickSort(targetArray, pivotIndex - 1, last - 1);
}
}
void RawArray::SortBy::radixSort(RawArray::ElementType* targetArray,
int size,
int digits) {
if (typeid(targetArray[0]) == typeid(int)) {
//创建10个桶(队列)分别给每个数位(0到9)
LinkedQueue<ElementType> queue[10];
int nDigitValue;
//遍历每个数位
for (int n = 1; n <= digits; ++n) {
for (int i = 0; i < size; ++i) {
//遍历数列中的每个元素,指示下标(i)
nDigitValue = HelperFunc::countSpecificDigitOfNumber(targetArray[i], n);
//并将元素移至相应的桶中
queue[nDigitValue].enqueue(targetArray[i]);
}
//在每个桶中,从最小的数位(j)开始
for (int j = 0, k = 0; j < 10; ++j) {
//当桶不是空的
while (!((queue[j]).isEmpty())) {
//将元素恢复至数列中,元素下标(k)
targetArray[k] = queue[j].front();
queue[j].dequeue();
//将元素下标(k)递增1,到下一元素
++k;
}
}
}
} else {
return;
}
}
#include "../ADTs/BinarySearchTree.h"
void RawArray::SortBy::treeSort(RawArray::ElementType* targetArray, int size) {
using namespace HelperFunc;
BinarySearchTree<ElementType> bst;
for (int i = 0; i < size; ++i) {
bst.add(targetArray[i]);
}
int i = 0;
bst.inorderTraverse([&](ElementType e) { targetArray[i++] = e; });
}
void RawArray::SortBy::heapSort(RawArray::ElementType* targetArray, int size) {
for (int i = size / 2; i >= 0; i--) {
HelperFunc::heapRebuild(i, targetArray, size);
}
#ifdef DEBUG
for (int j = 0; j < size; ++j)
std::cout << targetArray[j] << " ";
std::cout << std::endl;
#endif
std::swap(targetArray[0], targetArray[size - 1]);
int heapSize = size - 1;
while (heapSize > 1) {
HelperFunc::heapRebuild(0, targetArray, heapSize);
std::swap(targetArray[0], targetArray[heapSize - 1]);
heapSize--;
}
}
void RawArray::SortBy::HelperFunc::heapRebuild(
int index,
RawArray::ElementType* targetArray,
int size) {
int leftIndex = index * 2 + 1;
if (leftIndex < size) {
int rightIndex = index * 2 + 2;
if (rightIndex < size) {
if (targetArray[leftIndex] < targetArray[rightIndex])
leftIndex = rightIndex;
}
if (targetArray[index] < targetArray[leftIndex]) {
std::swap(targetArray[index], targetArray[leftIndex]);
heapRebuild(leftIndex, targetArray, size);
}
}
}
| 28.968127 | 80 | 0.563334 | Straydragonl |
05b6cc340b3ab29085981041e50e64567d254b0c | 276 | hpp | C++ | vulkan_layer/include/buffers.hpp | JnCrMx/cheeky-imp | 7f2064fa421444bbd2e426879af3becd6c5e7ea8 | [
"MIT"
] | 2 | 2021-09-12T06:57:23.000Z | 2021-09-12T14:09:00.000Z | vulkan_layer/include/buffers.hpp | JnCrMx/cheeky-imp | 7f2064fa421444bbd2e426879af3becd6c5e7ea8 | [
"MIT"
] | null | null | null | vulkan_layer/include/buffers.hpp | JnCrMx/cheeky-imp | 7f2064fa421444bbd2e426879af3becd6c5e7ea8 | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include "layer.hpp"
extern std::map<VkBuffer, VkBufferCreateInfo> buffers;
extern std::map<VkBuffer, VkDevice> bufferDevices;
extern std::map<VkBuffer, VkDeviceMemory> bufferMemories;
extern std::map<VkBuffer, VkDeviceSize> bufferMemoryOffsets;
| 27.6 | 60 | 0.797101 | JnCrMx |
05bb00739bcda2387224ddbe545fef5675c8e95e | 998 | hpp | C++ | include/Sound.hpp | mariohackandglitch/YAMKC_3DS | aed7d9b1d714b13391ebb40377c4ac36892ab82f | [
"RSA-MD"
] | 12 | 2021-05-13T12:47:25.000Z | 2021-05-30T19:22:43.000Z | include/Sound.hpp | mariohackandglitch/YAMKC_3DS | aed7d9b1d714b13391ebb40377c4ac36892ab82f | [
"RSA-MD"
] | null | null | null | include/Sound.hpp | mariohackandglitch/YAMKC_3DS | aed7d9b1d714b13391ebb40377c4ac36892ab82f | [
"RSA-MD"
] | null | null | null | #pragma once
#include <string>
#include <3ds.h>
#include <cwav.h>
class Sound {
public:
Sound(const std::string& fileName, int simulPlays);
~Sound();
bool IsLoaded();
bool IsPlaying();
void Play();
void EnsurePlaying();
void StereoPlay();
void Stop();
void SetMasterVolume(float volume);
void SetVolume(float volume);
void SetPitch(float amount, bool affect = false);
void SetTargetVolume(float amount, int frames);
void SetCreatePitch(float amount, int frames);
void SetDecayPitch(float amount, int frames);
void SetTargetStop(int frames);
void Tick();
private:
CWAV* sound;
bool isLoaded;
float masterVolume = 1.f;
int lChann = -1, rChann = -1;
int targetVolFrame, targetPitchFrame, targetDPitchFrame;
int currVolFrame = 0, currPitchFrame = 0, currDPitchFrame = 0, currStopFrame = 0;
float fromVolAmount, fromPitchAmount, fromDPitchAmount;
float toVolAmount, toPitchAmount, toDPitchAmount;
}; | 28.514286 | 85 | 0.687375 | mariohackandglitch |
05c18465809c5273d713afbff97e14fda55a849f | 231 | cpp | C++ | src/examples/04_module/05_value_and_reference_params/main.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-djchenevert | 0f7b3f47eb518fc4e85ec853cab9ceb4c629025a | [
"MIT"
] | null | null | null | src/examples/04_module/05_value_and_reference_params/main.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-djchenevert | 0f7b3f47eb518fc4e85ec853cab9ceb4c629025a | [
"MIT"
] | null | null | null | src/examples/04_module/05_value_and_reference_params/main.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-djchenevert | 0f7b3f47eb518fc4e85ec853cab9ceb4c629025a | [
"MIT"
] | null | null | null | #include<iostream>
#include "value_ref.h"
using std::cout;
int main()
{
static_example();
static_example();
static_example();
pass_by_val_and_ref(5);
int num1 = 5, num2 = 10;
pass_by_val_and_ref(num1, num2);
return 0;
} | 13.588235 | 33 | 0.69697 | acc-cosc-1337-fall-2020 |
05c6ceb7d4ed3228012689187c7137646205ba74 | 3,279 | cpp | C++ | modules/webbrowser/src/browserclient.cpp | nbartzokas/OpenSpace | 9df1e9b4821fade185b6e0a31b7cce1e67752a44 | [
"MIT"
] | null | null | null | modules/webbrowser/src/browserclient.cpp | nbartzokas/OpenSpace | 9df1e9b4821fade185b6e0a31b7cce1e67752a44 | [
"MIT"
] | null | null | null | modules/webbrowser/src/browserclient.cpp | nbartzokas/OpenSpace | 9df1e9b4821fade185b6e0a31b7cce1e67752a44 | [
"MIT"
] | null | null | null | /*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2018 *
* *
* 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 <modules/webbrowser/include/browserclient.h>
#include <modules/webbrowser/include/defaultbrowserlauncher.h>
#include <modules/webbrowser/include/webrenderhandler.h>
#include <modules/webbrowser/include/webkeyboardhandler.h>
#include <ghoul/misc/assert.h>
namespace openspace {
BrowserClient::BrowserClient(WebRenderHandler* handler,
WebKeyboardHandler* keyboardHandler)
: _renderHandler(handler)
, _keyboardHandler(keyboardHandler)
{
ghoul_assert(handler, "No WebRenderHandler provided");
ghoul_assert(keyboardHandler, "No WebKeyboardHandler provided");
DefaultBrowserLauncher* browserLauncher = new DefaultBrowserLauncher;
_lifeSpanHandler = browserLauncher;
_requestHandler = browserLauncher;
};
CefRefPtr<CefRenderHandler> BrowserClient::GetRenderHandler() {
return _renderHandler;
}
CefRefPtr<CefLifeSpanHandler> BrowserClient::GetLifeSpanHandler() {
return _lifeSpanHandler;
}
CefRefPtr<CefRequestHandler> BrowserClient::GetRequestHandler() {
return _requestHandler;
}
CefRefPtr<CefKeyboardHandler> BrowserClient::GetKeyboardHandler() {
return _keyboardHandler;
}
} // namespace openspace
| 51.234375 | 90 | 0.541934 | nbartzokas |
05c8b3d6e5a8688626195e1650863552336478c9 | 1,056 | cpp | C++ | geo/pathpt.cpp | lukas-ke/faint-graphics-editor | 33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf | [
"Apache-2.0"
] | 10 | 2016-12-28T22:06:31.000Z | 2021-05-24T13:42:30.000Z | geo/pathpt.cpp | lukas-ke/faint-graphics-editor | 33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf | [
"Apache-2.0"
] | 4 | 2015-10-09T23:55:10.000Z | 2020-04-04T08:09:22.000Z | geo/pathpt.cpp | lukas-ke/faint-graphics-editor | 33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf | [
"Apache-2.0"
] | null | null | null | // -*- coding: us-ascii-unix -*-
// Copyright 2013 Lukas Kemmer
//
// 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 "geo/angle.hh"
#include "geo/geo-func.hh"
#include "geo/pathpt.hh"
namespace faint{
PathPt PathPt::Rotated(const Angle& angle, const Point& origin) const{
PathPt p2(type, rotate_point(p, angle, origin),
rotate_point(c, angle, origin),
rotate_point(d, angle, origin));
p2.r = r;
p2.largeArcFlag = largeArcFlag;
p2.sweepFlag = sweepFlag;
p2.axisRotation = axisRotation + angle;
return p2;
}
} // namespace
| 30.171429 | 70 | 0.721591 | lukas-ke |
fe45c3d5af4ff03e10f18d01e03d629b627b5b9d | 1,349 | hh | C++ | CLARKSCV1.2.6.1/src/analyser.hh | Intensive-School-Virology-Unipv/metaviromics_data | df56c517b7d08000db0096b823a633450b15c0a1 | [
"MIT"
] | null | null | null | CLARKSCV1.2.6.1/src/analyser.hh | Intensive-School-Virology-Unipv/metaviromics_data | df56c517b7d08000db0096b823a633450b15c0a1 | [
"MIT"
] | null | null | null | CLARKSCV1.2.6.1/src/analyser.hh | Intensive-School-Virology-Unipv/metaviromics_data | df56c517b7d08000db0096b823a633450b15c0a1 | [
"MIT"
] | null | null | null | /*
* CLARK, CLAssifier based on Reduced K-mers.
*/
/*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Copyright 2013-2019, Rachid Ounit <clark.ucr.help at gmail.com>
*/
/*
* @author: Rachid Ounit, Ph.D Candidate.
* @project: CLARK, Metagenomic and Genomic Sequences Classification project.
* @note: C++ IMPLEMENTATION supported on latest Linux and Mac OS.
*
*/
#ifndef ANALYSER_HH
#define ANALYSER_HH
/*
* Rachid Ounit
* Date: 07/12/2013
*
*/
#include <vector>
class analyser
{
private:
size_t m_size;
std::vector< std::vector<int> > m_kmers;
std::vector<int> m_frequency;
public:
analyser(const char* _file);
~analyser();
bool getBumpInterval(int& _indexS, int& _indexE, const size_t& _div = 2);
};
#endif
| 24.089286 | 77 | 0.711638 | Intensive-School-Virology-Unipv |
fe464b4b88409e8699da06d268833caced9dbea2 | 2,009 | cpp | C++ | src/gui/chat_view.cpp | lucckb/telesecure | 9da299c29551d8abdba244458a0f894a9cc89b19 | [
"BSD-3-Clause"
] | 1 | 2020-03-22T17:06:43.000Z | 2020-03-22T17:06:43.000Z | src/gui/chat_view.cpp | lucckb/telesecure | 9da299c29551d8abdba244458a0f894a9cc89b19 | [
"BSD-3-Clause"
] | null | null | null | src/gui/chat_view.cpp | lucckb/telesecure | 9da299c29551d8abdba244458a0f894a9cc89b19 | [
"BSD-3-Clause"
] | null | null | null | #include <gui/chat_view.hpp>
#include <gui/chat_doc.hpp>
#include <gui/window_driver_context.hpp>
#include <gui/utility.hpp>
#include <ctime>
namespace gui {
//! Construtor
chat_view::chat_view(color_t bg, color_t fg)
: window(0,bg,fg)
{
}
//! Destructor
chat_view::~chat_view()
{
}
//When screen should be redrawed
bool chat_view::do_draw_screen( detail::window_driver_context& ctx )
{
if(m_view) {
int y,x;
getmaxyx(ctx.win(),y,x);
m_view->maxx(x);
}
if(m_view) {
changed( changed()| m_view->changed() );
m_view->displayed();
}
bool ret = changed();
if( m_view && (changed()||m_view->changed()) ) {
auto win = ctx.win();
int maxx,maxy;
getmaxyx(win,maxy,maxx);
//Calculate lines from the end
const auto begin = std::make_reverse_iterator(m_view->end());
const auto end = std::make_reverse_iterator(m_view->begin());
wclear(win);
int curr_y = maxy;
for (auto i=begin;i!=end; ++i) {
if(!i->second) { //Is Sender
setcolor(win,fgcolor(),bgcolor());
} else { //Im not sender
setcolor(win,color_t::blue,bgcolor());
}
const auto real_lines = split_string(i->first,maxx);
const auto rls = real_lines.size();
const auto start_ln = curr_y - rls;
for(int y=start_ln,n=0; n<rls ;++n,++y) {
mvwaddstr(win,y,0,real_lines[n].c_str());
}
curr_y -= rls;
if(curr_y<=0) break;
}
}
return ret;
}
//Assign view to the container
void chat_view::set_view(std::shared_ptr<chat_doc> view)
{
wclear(ctx().win());
m_view = view;
changed(true);
}
//Scroll up
void chat_view::scrolling(scroll_mode mode)
{
auto win = ctx().win();
int maxx,maxy;
getmaxyx(win,maxy,maxx);
maxy = maxy-1;
m_view->rewind(mode==scroll_mode::up?-maxy:maxy);
changed(true);
}
} | 23.916667 | 69 | 0.56446 | lucckb |
fe48ccd4cfffc7014476514587037f11d6660019 | 7,381 | cpp | C++ | tool_kits/ui_component/ui_kit/module/session/session_manager_dragdrop.cpp | stephenzhj/NIM_PC_Demo | 0d2933955e079afa5c9e4df196ee017fad6c79af | [
"BSD-2-Clause",
"OpenSSL"
] | 161 | 2016-01-24T13:55:15.000Z | 2021-06-01T03:48:56.000Z | tool_kits/ui_component/ui_kit/module/session/session_manager_dragdrop.cpp | stephenzhj/NIM_PC_Demo | 0d2933955e079afa5c9e4df196ee017fad6c79af | [
"BSD-2-Clause",
"OpenSSL"
] | 49 | 2016-01-24T14:06:52.000Z | 2021-06-01T07:14:53.000Z | tool_kits/ui_component/ui_kit/module/session/session_manager_dragdrop.cpp | xiejiulong/NIM_PC_Demo | 47f74270b200bb365035209c9734723f1cb7efea | [
"BSD-2-Clause",
"OpenSSL"
] | 140 | 2016-02-22T09:42:07.000Z | 2021-05-26T01:15:12.000Z | #include "stdafx.h"
#include "session_manager.h"
#include "gui/session/session_form.h"
#include "gui/session/session_box.h"
#include "gui/session/dragdrop/drag_form.h"
#include "gui/session/session_dock_def.h"
#include "module/dragdrop/drag_drop.h"
namespace
{
const int kSplitFormXOffset = 20; //自动拆分会话窗口后新窗口的x偏移坐标
const int kSplitFormYOffset = 20; //自动拆分会话窗口后新窗口的y偏移坐标
const int kDragFormXOffset = -100; //拖拽出新会话窗口后的相对鼠标的x偏移坐标
const int kDragFormYOffset = -20; //拖拽出新会话窗口后的相对鼠标的y偏移坐标
}
namespace nim_comp
{
void SessionManager::SetEnableMerge(bool enable)
{
if (enable_merge_ == enable)
return;
enable_merge_ = enable;
if (enable_merge_)
{
// 如果当前只有一个会话窗口或者会话盒子,就不需要进行合并操作
if (session_box_map_.size() <= 1)
return;
// 选择第一个会话盒子所属的窗口作为合并窗口
ISessionDock *merge_form = session_box_map_.begin()->second->GetSessionForm();
// 遍历所有会话盒子,脱离原会话窗口,再附加到合并窗口里
for (auto it_box : session_box_map_)
{
ASSERT(NULL != it_box.second);
ISessionDock *parent_form = it_box.second->GetSessionForm();
if (merge_form != parent_form)
{
if (parent_form->DetachSessionBox(it_box.second))
{
merge_form->AttachSessionBox(it_box.second);
}
}
}
}
else
{
// 如果当前只有一个会话盒子,就不需要进行拆分操作
if (session_box_map_.size() <= 1)
return;
// 给新拆分的窗口设置坐标
bool first_sort = true;
ui::UiRect rect_old_form;
ISessionDock *sort_form = NULL;
// 遍历所有会话盒子,脱离原会话窗口,创建新的会话窗口并附加会话盒子
for (auto it_box : session_box_map_)
{
ASSERT(NULL != it_box.second);
ISessionDock *parent_form = it_box.second->GetSessionForm();
if (1 == parent_form->GetSessionBoxCount())
{
sort_form = parent_form;
}
else if (parent_form->DetachSessionBox(it_box.second))
{
ISessionDock *session_form = ISessionDock::InstantDock();
HWND hwnd = session_form->Create();
if (hwnd == NULL)
{
ASSERT(0);
continue;
}
if (!session_form->AttachSessionBox(it_box.second))
{
ASSERT(0);
continue;
}
sort_form = session_form;
}
if (NULL != sort_form)
{
if (first_sort)
{
first_sort = false;
sort_form->CenterWindow();
rect_old_form = sort_form->GetPos(true);
}
else
{
rect_old_form.left += kSplitFormXOffset;
rect_old_form.top += kSplitFormXOffset;
sort_form->SetPos(rect_old_form, true, SWP_NOSIZE, NULL, true);
}
}
}
}
}
bool SessionManager::IsEnableMerge() const
{
return enable_merge_;
}
void SessionManager::SetUseCustomDragImage(bool use)
{
use_custom_drag_image_ = use;
}
bool SessionManager::IsUseCustomDragImage() const
{
return use_custom_drag_image_;
}
bool SessionManager::IsDragingSessionBox() const
{
return enable_merge_ && NULL != draging_session_box_;
}
void SessionManager::SetDropSessionForm(ISessionDock *session_form)
{
if (NULL == session_form)
return;
drop_session_form_ = session_form;
}
bool SessionManager::DoDragSessionBox(SessionBox *session_box, HBITMAP bitmap, POINT pt_offset)
{
if (!enable_merge_)
return false;
SdkDropSource* drop_src = new SdkDropSource;
if (drop_src == NULL)
return false;
SdkDataObject* data_object = CreateDragDataObject(bitmap, pt_offset);
if (data_object == NULL)
return false;
// 无论什么时候都让拖拽时光标显示为箭头
drop_src->SetFeedbackCursor(::LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW)));
OnBeforeDragSessionBox(session_box, bitmap, pt_offset);
// 此函数会阻塞直到拖拽完成
DWORD dwEffect;
HRESULT hr = ::DoDragDrop(data_object, drop_src, DROPEFFECT_COPY | DROPEFFECT_MOVE, &dwEffect);
OnAfterDragSessionBox();
// 销毁位图
DeleteObject(bitmap);
drop_src->Release();
data_object->Release();
return true;
}
SdkDataObject* SessionManager::CreateDragDataObject(HBITMAP bitmap, POINT pt_offset)
{
SdkDataObject* data_object = new SdkDataObject;
if (data_object == NULL)
return NULL;
if (use_custom_drag_image_)
{
FORMATETC fmtetc = { 0 };
fmtetc.dwAspect = DVASPECT_CONTENT;
fmtetc.lindex = -1;
fmtetc.cfFormat = CF_HDROP;
fmtetc.tymed = TYMED_NULL;
STGMEDIUM medium = { 0 };
medium.tymed = TYMED_NULL;
data_object->SetData(&fmtetc, &medium, FALSE);
}
else
{
FORMATETC fmtetc = { 0 };
fmtetc.dwAspect = DVASPECT_CONTENT;
fmtetc.lindex = -1;
fmtetc.cfFormat = CF_BITMAP;
fmtetc.tymed = TYMED_GDI;
STGMEDIUM medium = { 0 };
medium.tymed = TYMED_GDI;
HBITMAP hBitmap = (HBITMAP)OleDuplicateData(bitmap, fmtetc.cfFormat, NULL);
medium.hBitmap = hBitmap;
data_object->SetData(&fmtetc, &medium, FALSE);
BITMAP bitmap_info;
GetObject(hBitmap, sizeof(BITMAP), &bitmap_info);
SIZE bitmap_size = { bitmap_info.bmWidth, bitmap_info.bmHeight };
SdkDragSourceHelper dragSrcHelper;
dragSrcHelper.InitializeFromBitmap(hBitmap, pt_offset, bitmap_size, data_object, RGB(255, 0, 255));
}
return data_object;
}
void SessionManager::OnBeforeDragSessionBox(SessionBox *session_box, HBITMAP bitmap, POINT pt_offset)
{
// 获取当前被拖拽的会话盒子所属的会话窗口
draging_session_box_ = session_box;
ISessionDock *drag_session_form = draging_session_box_->GetSessionForm();
ASSERT(NULL != drag_session_form);
// 获取被拖拽会话窗口中会话盒子的数量
int box_count = drag_session_form->GetSessionBoxCount();
ASSERT(box_count > 0);
drop_session_form_ = NULL;
drag_session_form->OnBeforeDragSessionBoxCallback(nbase::UTF8ToUTF16(draging_session_box_->GetSessionId()));
if (use_custom_drag_image_)
DragForm::CreateCustomDragImage(bitmap, pt_offset);
}
void SessionManager::OnAfterDragSessionBox()
{
if (use_custom_drag_image_)
DragForm::CloseCustomDragImage();
if (NULL == draging_session_box_)
return;
// 获取当前被拖拽的会话盒子所属的会话窗口
ISessionDock *drag_session_form = draging_session_box_->GetSessionForm();
ASSERT(NULL != drag_session_form);
// 获取被拖拽会话窗口中会话盒子的数量
int box_count = drag_session_form->GetSessionBoxCount();
ASSERT(box_count > 0);
// 如果被拖拽的会话盒子放入到一个会话窗口里
if (NULL != drop_session_form_)
{
if (drag_session_form == drop_session_form_)
{
drag_session_form->OnAfterDragSessionBoxCallback(false);
}
else
{
drag_session_form->OnAfterDragSessionBoxCallback(true);
if (drag_session_form->DetachSessionBox(draging_session_box_))
{
drop_session_form_->AttachSessionBox(draging_session_box_);
}
}
// 如果被拖拽的会话窗口包含多个会话盒子,就投递一个WM_LBUTTONUP消息给窗口
// (因为窗口被拖拽时触发了ButtonDown和ButtonMove消息,但是最终的ButtonUp消息会被忽略,这里补上)
// 如果只有一个会话盒子,则会话盒子脱离会话窗口时,会话窗体就会关闭,不需要投递
if (box_count > 1)
drag_session_form->PostMessage(WM_LBUTTONUP, 0, 0);
}
// 如果没有被拖拽到另一个会话窗口里
else
{
// 如果被拖拽的会话窗口里只有一个会话盒子,则拖拽失败
if (1 == box_count)
{
drag_session_form->OnAfterDragSessionBoxCallback(false);
}
// 如果有多个会话盒子, 就把会话盒子脱离原会话窗口,附加到新的会话窗口,拖拽成功
else
{
drag_session_form->OnAfterDragSessionBoxCallback(true);
if (drag_session_form->DetachSessionBox(draging_session_box_))
{
ISessionDock *session_form = ISessionDock::InstantDock();
HWND hwnd = session_form->Create();
if (hwnd != NULL)
{
if (session_form->AttachSessionBox(draging_session_box_))
{
// 这里设置新会话窗口的位置,设置到偏移鼠标坐标100,20的位置
POINT pt_mouse;
::GetCursorPos(&pt_mouse);
ui::UiRect rect(pt_mouse.x + kDragFormXOffset, pt_mouse.y + kDragFormYOffset, 0, 0);
session_form->SetPos(rect, false, SWP_NOSIZE);
}
}
}
}
// 如果没有被拖拽到另一个会话窗口里,这时不会有会话窗口被关闭,所以直接投递ButtonUp消息
drag_session_form->PostMessage(WM_LBUTTONUP, 0, 0);
}
draging_session_box_ = NULL;
drop_session_form_ = NULL;
}
} | 24.279605 | 109 | 0.730524 | stephenzhj |
fe4dbaf64a7aa3f13ef7fda3cd07c5d1eb8d5706 | 94 | hpp | C++ | hostsdk/include/rtvamp/hostsdk.hpp | lukasberbuer/rt-vamp-plugin-sdk | 745e3e30d2899669ff3a482135c58407b3b3b36b | [
"MIT"
] | null | null | null | hostsdk/include/rtvamp/hostsdk.hpp | lukasberbuer/rt-vamp-plugin-sdk | 745e3e30d2899669ff3a482135c58407b3b3b36b | [
"MIT"
] | null | null | null | hostsdk/include/rtvamp/hostsdk.hpp | lukasberbuer/rt-vamp-plugin-sdk | 745e3e30d2899669ff3a482135c58407b3b3b36b | [
"MIT"
] | null | null | null | #pragma once
#include "rtvamp/hostsdk/Plugin.hpp"
#include "rtvamp/hostsdk/PluginLoader.hpp"
| 18.8 | 42 | 0.787234 | lukasberbuer |
fe4e8dec153da3fd5a6bce8bdea21d57a7f435d8 | 10,219 | cpp | C++ | Source/Data/TLS/Base/NptTlsTrustAnchor_Base_0079.cpp | mcgwh/Neptune | 9f95d33e594088d9e95a3d77818de3cc6e4b7dba | [
"BSD-3-Clause"
] | 1 | 2019-07-20T02:26:52.000Z | 2019-07-20T02:26:52.000Z | Source/Data/TLS/Base/NptTlsTrustAnchor_Base_0079.cpp | mcgwh/Neptune | 9f95d33e594088d9e95a3d77818de3cc6e4b7dba | [
"BSD-3-Clause"
] | null | null | null | Source/Data/TLS/Base/NptTlsTrustAnchor_Base_0079.cpp | mcgwh/Neptune | 9f95d33e594088d9e95a3d77818de3cc6e4b7dba | [
"BSD-3-Clause"
] | null | null | null | /*****************************************************************
|
| Neptune - Trust Anchors
|
| This file is automatically generated by a script, do not edit!
|
| Copyright (c) 2002-2010, Axiomatic Systems, LLC.
| 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 Axiomatic Systems 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 AXIOMATIC SYSTEMS ''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 AXIOMATIC SYSTEMS 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.
|
****************************************************************/
/* E-Tugra Certification Authority */
const unsigned char NptTlsTrustAnchor_Base_0079_Data[1615] = {
0x30,0x82,0x06,0x4b,0x30,0x82,0x04,0x33
,0xa0,0x03,0x02,0x01,0x02,0x02,0x08,0x6a
,0x68,0x3e,0x9c,0x51,0x9b,0xcb,0x53,0x30
,0x0d,0x06,0x09,0x2a,0x86,0x48,0x86,0xf7
,0x0d,0x01,0x01,0x0b,0x05,0x00,0x30,0x81
,0xb2,0x31,0x0b,0x30,0x09,0x06,0x03,0x55
,0x04,0x06,0x13,0x02,0x54,0x52,0x31,0x0f
,0x30,0x0d,0x06,0x03,0x55,0x04,0x07,0x0c
,0x06,0x41,0x6e,0x6b,0x61,0x72,0x61,0x31
,0x40,0x30,0x3e,0x06,0x03,0x55,0x04,0x0a
,0x0c,0x37,0x45,0x2d,0x54,0x75,0xc4,0x9f
,0x72,0x61,0x20,0x45,0x42,0x47,0x20,0x42
,0x69,0x6c,0x69,0xc5,0x9f,0x69,0x6d,0x20
,0x54,0x65,0x6b,0x6e,0x6f,0x6c,0x6f,0x6a
,0x69,0x6c,0x65,0x72,0x69,0x20,0x76,0x65
,0x20,0x48,0x69,0x7a,0x6d,0x65,0x74,0x6c
,0x65,0x72,0x69,0x20,0x41,0x2e,0xc5,0x9e
,0x2e,0x31,0x26,0x30,0x24,0x06,0x03,0x55
,0x04,0x0b,0x0c,0x1d,0x45,0x2d,0x54,0x75
,0x67,0x72,0x61,0x20,0x53,0x65,0x72,0x74
,0x69,0x66,0x69,0x6b,0x61,0x73,0x79,0x6f
,0x6e,0x20,0x4d,0x65,0x72,0x6b,0x65,0x7a
,0x69,0x31,0x28,0x30,0x26,0x06,0x03,0x55
,0x04,0x03,0x0c,0x1f,0x45,0x2d,0x54,0x75
,0x67,0x72,0x61,0x20,0x43,0x65,0x72,0x74
,0x69,0x66,0x69,0x63,0x61,0x74,0x69,0x6f
,0x6e,0x20,0x41,0x75,0x74,0x68,0x6f,0x72
,0x69,0x74,0x79,0x30,0x1e,0x17,0x0d,0x31
,0x33,0x30,0x33,0x30,0x35,0x31,0x32,0x30
,0x39,0x34,0x38,0x5a,0x17,0x0d,0x32,0x33
,0x30,0x33,0x30,0x33,0x31,0x32,0x30,0x39
,0x34,0x38,0x5a,0x30,0x81,0xb2,0x31,0x0b
,0x30,0x09,0x06,0x03,0x55,0x04,0x06,0x13
,0x02,0x54,0x52,0x31,0x0f,0x30,0x0d,0x06
,0x03,0x55,0x04,0x07,0x0c,0x06,0x41,0x6e
,0x6b,0x61,0x72,0x61,0x31,0x40,0x30,0x3e
,0x06,0x03,0x55,0x04,0x0a,0x0c,0x37,0x45
,0x2d,0x54,0x75,0xc4,0x9f,0x72,0x61,0x20
,0x45,0x42,0x47,0x20,0x42,0x69,0x6c,0x69
,0xc5,0x9f,0x69,0x6d,0x20,0x54,0x65,0x6b
,0x6e,0x6f,0x6c,0x6f,0x6a,0x69,0x6c,0x65
,0x72,0x69,0x20,0x76,0x65,0x20,0x48,0x69
,0x7a,0x6d,0x65,0x74,0x6c,0x65,0x72,0x69
,0x20,0x41,0x2e,0xc5,0x9e,0x2e,0x31,0x26
,0x30,0x24,0x06,0x03,0x55,0x04,0x0b,0x0c
,0x1d,0x45,0x2d,0x54,0x75,0x67,0x72,0x61
,0x20,0x53,0x65,0x72,0x74,0x69,0x66,0x69
,0x6b,0x61,0x73,0x79,0x6f,0x6e,0x20,0x4d
,0x65,0x72,0x6b,0x65,0x7a,0x69,0x31,0x28
,0x30,0x26,0x06,0x03,0x55,0x04,0x03,0x0c
,0x1f,0x45,0x2d,0x54,0x75,0x67,0x72,0x61
,0x20,0x43,0x65,0x72,0x74,0x69,0x66,0x69
,0x63,0x61,0x74,0x69,0x6f,0x6e,0x20,0x41
,0x75,0x74,0x68,0x6f,0x72,0x69,0x74,0x79
,0x30,0x82,0x02,0x22,0x30,0x0d,0x06,0x09
,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01
,0x01,0x05,0x00,0x03,0x82,0x02,0x0f,0x00
,0x30,0x82,0x02,0x0a,0x02,0x82,0x02,0x01
,0x00,0xe2,0xf5,0x3f,0x93,0x05,0x51,0x1e
,0x85,0x62,0x54,0x5e,0x7a,0x0b,0xf5,0x18
,0x07,0x83,0xae,0x7e,0xaf,0x7c,0xf7,0xd4
,0x8a,0x6b,0xa5,0x63,0x43,0x39,0xb9,0x4b
,0xf7,0xc3,0xc6,0x64,0x89,0x3d,0x94,0x2e
,0x54,0x80,0x52,0x39,0x39,0x07,0x4b,0x4b
,0xdd,0x85,0x07,0x76,0x87,0xcc,0xbf,0x2f
,0x95,0x4c,0xcc,0x7d,0xa7,0x3d,0xbc,0x47
,0x0f,0x98,0x70,0xf8,0x8c,0x85,0x1e,0x74
,0x8e,0x92,0x6d,0x1b,0x40,0xd1,0x99,0x0d
,0xbb,0x75,0x6e,0xc8,0xa9,0x6b,0x9a,0xc0
,0x84,0x31,0xaf,0xca,0x43,0xcb,0xeb,0x2b
,0x34,0xe8,0x8f,0x97,0x6b,0x01,0x9b,0xd5
,0x0e,0x4a,0x08,0xaa,0x5b,0x92,0x74,0x85
,0x43,0xd3,0x80,0xae,0xa1,0x88,0x5b,0xae
,0xb3,0xea,0x5e,0xcb,0x16,0x9a,0x77,0x44
,0xc8,0xa1,0xf6,0x54,0x68,0xce,0xde,0x8f
,0x97,0x2b,0xba,0x5b,0x40,0x02,0x0c,0x64
,0x17,0xc0,0xb5,0x93,0xcd,0xe1,0xf1,0x13
,0x66,0xce,0x0c,0x79,0xef,0xd1,0x91,0x28
,0xab,0x5f,0xa0,0x12,0x52,0x30,0x73,0x19
,0x8e,0x8f,0xe1,0x8c,0x07,0xa2,0xc3,0xbb
,0x4a,0xf0,0xea,0x1f,0x15,0xa8,0xee,0x25
,0xcc,0xa4,0x46,0xf8,0x1b,0x22,0xef,0xb3
,0x0e,0x43,0xba,0x2c,0x24,0xb8,0xc5,0x2c
,0x5c,0xd4,0x1c,0xf8,0x5d,0x64,0xbd,0xc3
,0x93,0x5e,0x28,0xa7,0x3f,0x27,0xf1,0x8e
,0x1e,0xd3,0x2a,0x50,0x05,0xa3,0x55,0xd9
,0xcb,0xe7,0x39,0x53,0xc0,0x98,0x9e,0x8c
,0x54,0x62,0x8b,0x26,0xb0,0xf7,0x7d,0x8d
,0x7c,0xe4,0xc6,0x9e,0x66,0x42,0x55,0x82
,0x47,0xe7,0xb2,0x58,0x8d,0x66,0xf7,0x07
,0x7c,0x2e,0x36,0xe6,0x50,0x1c,0x3f,0xdb
,0x43,0x24,0xc5,0xbf,0x86,0x47,0x79,0xb3
,0x79,0x1c,0xf7,0x5a,0xf4,0x13,0xec,0x6c
,0xf8,0x3f,0xe2,0x59,0x1f,0x95,0xee,0x42
,0x3e,0xb9,0xad,0xa8,0x32,0x85,0x49,0x97
,0x46,0xfe,0x4b,0x31,0x8f,0x5a,0xcb,0xad
,0x74,0x47,0x1f,0xe9,0x91,0xb7,0xdf,0x28
,0x04,0x22,0xa0,0xd4,0x0f,0x5d,0xe2,0x79
,0x4f,0xea,0x6c,0x85,0x86,0xbd,0xa8,0xa6
,0xce,0xe4,0xfa,0xc3,0xe1,0xb3,0xae,0xde
,0x3c,0x51,0xee,0xcb,0x13,0x7c,0x01,0x7f
,0x84,0x0e,0x5d,0x51,0x94,0x9e,0x13,0x0c
,0xb6,0x2e,0xa5,0x4c,0xf9,0x39,0x70,0x36
,0x6f,0x96,0xca,0x2e,0x0c,0x44,0x55,0xc5
,0xca,0xfa,0x5d,0x02,0xa3,0xdf,0xd6,0x64
,0x8c,0x5a,0xb3,0x01,0x0a,0xa9,0xb5,0x0a
,0x47,0x17,0xff,0xef,0x91,0x40,0x2a,0x8e
,0xa1,0x46,0x3a,0x31,0x98,0xe5,0x11,0xfc
,0xcc,0xbb,0x49,0x56,0x8a,0xfc,0xb9,0xd0
,0x61,0x9a,0x6f,0x65,0x6c,0xe6,0xc3,0xcb
,0x3e,0x75,0x49,0xfe,0x8f,0xa7,0xe2,0x89
,0xc5,0x67,0xd7,0x9d,0x46,0x13,0x4e,0x31
,0x76,0x3b,0x24,0xb3,0x9e,0x11,0x65,0x86
,0xab,0x7f,0xef,0x1d,0xd4,0xf8,0xbc,0xe7
,0xac,0x5a,0x5c,0xb7,0x5a,0x47,0x5c,0x55
,0xce,0x55,0xb4,0x22,0x71,0x5b,0x5b,0x0b
,0xf0,0xcf,0xdc,0xa0,0x61,0x64,0xea,0xa9
,0xd7,0x68,0x0a,0x63,0xa7,0xe0,0x0d,0x3f
,0xa0,0xaf,0xd3,0xaa,0xd2,0x7e,0xef,0x51
,0xa0,0xe6,0x51,0x2b,0x55,0x92,0x15,0x17
,0x53,0xcb,0xb7,0x66,0x0e,0x66,0x4c,0xf8
,0xf9,0x75,0x4c,0x90,0xe7,0x12,0x70,0xc7
,0x45,0x02,0x03,0x01,0x00,0x01,0xa3,0x63
,0x30,0x61,0x30,0x1d,0x06,0x03,0x55,0x1d
,0x0e,0x04,0x16,0x04,0x14,0x2e,0xe3,0xdb
,0xb2,0x49,0xd0,0x9c,0x54,0x79,0x5c,0xfa
,0x27,0x2a,0xfe,0xcc,0x4e,0xd2,0xe8,0x4e
,0x54,0x30,0x0f,0x06,0x03,0x55,0x1d,0x13
,0x01,0x01,0xff,0x04,0x05,0x30,0x03,0x01
,0x01,0xff,0x30,0x1f,0x06,0x03,0x55,0x1d
,0x23,0x04,0x18,0x30,0x16,0x80,0x14,0x2e
,0xe3,0xdb,0xb2,0x49,0xd0,0x9c,0x54,0x79
,0x5c,0xfa,0x27,0x2a,0xfe,0xcc,0x4e,0xd2
,0xe8,0x4e,0x54,0x30,0x0e,0x06,0x03,0x55
,0x1d,0x0f,0x01,0x01,0xff,0x04,0x04,0x03
,0x02,0x01,0x06,0x30,0x0d,0x06,0x09,0x2a
,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x0b
,0x05,0x00,0x03,0x82,0x02,0x01,0x00,0x05
,0x37,0x3a,0xf4,0x4d,0xb7,0x45,0xe2,0x45
,0x75,0x24,0x8f,0xb6,0x77,0x52,0xe8,0x1c
,0xd8,0x10,0x93,0x65,0xf3,0xf2,0x59,0x06
,0xa4,0x3e,0x1e,0x29,0xec,0x5d,0xd1,0xd0
,0xab,0x7c,0xe0,0x0a,0x90,0x48,0x78,0xed
,0x4e,0x98,0x03,0x99,0xfe,0x28,0x60,0x91
,0x1d,0x30,0x1d,0xb8,0x63,0x7c,0xa8,0xe6
,0x35,0xb5,0xfa,0xd3,0x61,0x76,0xe6,0xd6
,0x07,0x4b,0xca,0x69,0x9a,0xb2,0x84,0x7a
,0x77,0x93,0x45,0x17,0x15,0x9f,0x24,0xd0
,0x98,0x13,0x12,0xff,0xbb,0xa0,0x2e,0xfd
,0x4e,0x4c,0x87,0xf8,0xce,0x5c,0xaa,0x98
,0x1b,0x05,0xe0,0x00,0x46,0x4a,0x82,0x80
,0xa5,0x33,0x8b,0x28,0xdc,0xed,0x38,0xd3
,0xdf,0xe5,0x3e,0xe9,0xfe,0xfb,0x59,0xdd
,0x61,0x84,0x4f,0xd2,0x54,0x96,0x13,0x61
,0x13,0x3e,0x8f,0x80,0x69,0xbe,0x93,0x47
,0xb5,0x35,0x43,0xd2,0x5a,0xbb,0x3d,0x5c
,0xef,0xb3,0x42,0x47,0xcd,0x3b,0x55,0x13
,0x06,0xb0,0x09,0xdb,0xfd,0x63,0xf6,0x3a
,0x88,0x0a,0x99,0x6f,0x7e,0xe1,0xce,0x1b
,0x53,0x6a,0x44,0x66,0x23,0x51,0x08,0x7b
,0xbc,0x5b,0x52,0xa2,0xfd,0x06,0x37,0x38
,0x40,0x61,0x8f,0x4a,0x96,0xb8,0x90,0x37
,0xf8,0x66,0xc7,0x78,0x90,0x00,0x15,0x2e
,0x8b,0xad,0x51,0x35,0x53,0x07,0xa8,0x6b
,0x68,0xae,0xf9,0x4e,0x3c,0x07,0x26,0xcd
,0x08,0x05,0x70,0xcc,0x39,0x3f,0x76,0xbd
,0xa5,0xd3,0x67,0x26,0x01,0x86,0xa6,0x53
,0xd2,0x60,0x3b,0x7c,0x43,0x7f,0x55,0x8a
,0xbc,0x95,0x1a,0xc1,0x28,0x39,0x4c,0x1f
,0x43,0xd2,0x91,0xf4,0x72,0x59,0x8a,0xb9
,0x56,0xfc,0x3f,0xb4,0x9d,0xda,0x70,0x9c
,0x76,0x5a,0x8c,0x43,0x50,0xee,0x8e,0x30
,0x72,0x4d,0xdf,0xff,0x49,0xf7,0xc6,0xa9
,0x67,0xd9,0x6d,0xac,0x02,0x11,0xe2,0x3a
,0x16,0x25,0xa7,0x58,0x08,0xcb,0x6f,0x53
,0x41,0x9c,0x48,0x38,0x47,0x68,0x33,0xd1
,0xd7,0xc7,0x8f,0xd4,0x74,0x21,0xd4,0xc3
,0x05,0x90,0x7a,0xff,0xce,0x96,0x88,0xb1
,0x15,0x29,0x5d,0x23,0xab,0xd0,0x60,0xa1
,0x12,0x4f,0xde,0xf4,0x17,0xcd,0x32,0xe5
,0xc9,0xbf,0xc8,0x43,0xad,0xfd,0x2e,0x8e
,0xf1,0xaf,0xe2,0xf4,0x98,0xfa,0x12,0x1f
,0x20,0xd8,0xc0,0xa7,0x0c,0x85,0xc5,0x90
,0xf4,0x3b,0x2d,0x96,0x26,0xb1,0x2c,0xbe
,0x4c,0xab,0xeb,0xb1,0xd2,0x8a,0xc9,0xdb
,0x78,0x13,0x0f,0x1e,0x09,0x9d,0x6d,0x8f
,0x00,0x9f,0x02,0xda,0xc1,0xfa,0x1f,0x7a
,0x7a,0x09,0xc4,0x4a,0xe6,0x88,0x2a,0x97
,0x9f,0x89,0x8b,0xfd,0x37,0x5f,0x5f,0x3a
,0xce,0x38,0x59,0x86,0x4b,0xaf,0x71,0x0b
,0xb4,0xd8,0xf2,0x70,0x4f,0x9f,0x32,0x13
,0xe3,0xb0,0xa7,0x57,0xe5,0xda,0xda,0x43
,0xcb,0x84,0x34,0xf2,0x28,0xc4,0xea,0x6d
,0xf4,0x2a,0xef,0xc1,0x6b,0x76,0xda,0xfb
,0x7e,0xbb,0x85,0x3c,0xd2,0x53,0xc2,0x4d
,0xbe,0x71,0xe1,0x45,0xd1,0xfd,0x23,0x67
,0x0d,0x13,0x75,0xfb,0xcf,0x65,0x67,0x22
,0x9d,0xae,0xb0,0x09,0xd1,0x09,0xff,0x1d
,0x34,0xbf,0xfe,0x23,0x97,0x37,0xd2,0x39
,0xfa,0x3d,0x0d,0x06,0x0b,0xb4,0xdb,0x3b
,0xa3,0xab,0x6f,0x5c,0x1d,0xb6,0x7e,0xe8
,0xb3,0x82,0x34,0xed,0x06,0x5c,0x24};
const unsigned int NptTlsTrustAnchor_Base_0079_Size = 1615;
| 42.757322 | 79 | 0.767883 | mcgwh |
fe50aab4de840cd4cab2118fc0ccae75257302f6 | 10,285 | cpp | C++ | baseoperations/math/binarymath.cpp | ridoo/IlwisCore | 9d9837507d804a4643545a03fd40d9b4d0eaee45 | [
"Apache-2.0"
] | null | null | null | baseoperations/math/binarymath.cpp | ridoo/IlwisCore | 9d9837507d804a4643545a03fd40d9b4d0eaee45 | [
"Apache-2.0"
] | null | null | null | baseoperations/math/binarymath.cpp | ridoo/IlwisCore | 9d9837507d804a4643545a03fd40d9b4d0eaee45 | [
"Apache-2.0"
] | null | null | null | #include <functional>
#include <future>
#include "kernel.h"
#include "raster.h"
#include "symboltable.h"
#include "ilwisoperation.h"
#include "binarymath.h"
using namespace Ilwis;
using namespace BaseOperations;
OperationImplementation *BinaryMath::create(quint64 metaid, const Ilwis::OperationExpression &expr)
{
return new BinaryMath( metaid, expr);
}
BinaryMath::BinaryMath() : _coveragecoverage(false)
{
}
BinaryMath::BinaryMath(quint64 metaid,const Ilwis::OperationExpression &expr) : OperationImplementation(metaid, expr) , _coveragecoverage(false)
{
}
bool BinaryMath::setOutput(ExecutionContext *ctx, SymbolTable& symTable) {
if ( ctx) {
QVariant value;
value.setValue<IRasterCoverage>(_outputGC);
ctx->addOutput(symTable,value,_outputGC->name(), itRASTER,_outputGC->resource() );
}
return _outputGC.isValid();
}
bool BinaryMath::executeRasterNumber(ExecutionContext *ctx, SymbolTable& symTable) {
auto binaryMath = [&](const Box3D<qint32> box ) -> bool {
PixelIterator iterIn(_inputGC1, box);
PixelIterator iterOut(_outputGC, Box3D<qint32>(box.size()));
double v_in = 0;
for_each(iterOut, iterOut.end(), [&](double& v){
if ( (v_in = *iterIn) != rUNDEF) {
switch(_operator) {
case otPLUS:
v = v_in + _number;break;
case otMINUS:
v = v_in - _number;break;
case otDIV:
if ( _number != 0)
v = v_in / _number;
else
v = rUNDEF;
break;
case otMULT:
v = v_in * _number;break;
}
}
++iterIn;
});
return true;
};
if (!OperationHelperRaster::execute(ctx, binaryMath, _outputGC))
return false;
return setOutput(ctx, symTable);
}
bool BinaryMath::executeRasterRaster(ExecutionContext *ctx, SymbolTable& symTable) {
std::function<bool(const Box3D<qint32>)> binaryMath = [&](const Box3D<qint32> box ) -> bool {
//auto binaryMath = [&](const Box3D<qint32> box ) -> bool {
PixelIterator iterIn1(_inputGC1, box);
PixelIterator iterIn2(_inputGC2, box);
PixelIterator iterOut(_outputGC, Box3D<qint32>(box.size()));
double v_in1 = 0;
double v_in2 = 0;
for_each(iterOut, iterOut.end(), [&](double& v){
v_in1 = *iterIn1;
v_in2 = *iterIn2;
if ( v_in1 != rUNDEF && v_in2 != rUNDEF) {
switch(_operator) {
case otPLUS:
v = v_in1 + v_in2;break;
case otMINUS:
v = v_in1 - v_in2;break;
case otDIV:
if ( v_in2 != 0)
v = v_in1 / v_in2;
else
v = rUNDEF;
break;
case otMULT:
v = v_in1 * v_in2;break;
}
}
++iterIn1;
++iterIn2;
});
return true;
};
bool res = OperationHelperRaster::execute(ctx, binaryMath, _outputGC);
if (res)
return setOutput(ctx, symTable);
return false;
}
bool BinaryMath::execute(ExecutionContext *ctx, SymbolTable& symTable)
{
if (_prepState == sNOTPREPARED)
if((_prepState = prepare(ctx, symTable)) != sPREPARED)
return false;
if ( _coveragecoverage) {
return executeRasterRaster(ctx, symTable);
} else {
return executeRasterNumber(ctx, symTable);
}
return true;
}
bool BinaryMath::prepareRasterRaster() {
QString gc = _expression.parm(0).value();
if (!_inputGC1.prepare(gc)) {
kernel()->issues()->log(TR(ERR_COULD_NOT_LOAD_2).arg(gc, ""));
return false;
}
gc = _expression.parm(1).value();
if (!_inputGC2.prepare(gc)) {
kernel()->issues()->log(TR(ERR_COULD_NOT_LOAD_2).arg(gc, ""));
return false;
}
bool isNumeric = _inputGC1->datadef().domain()->ilwisType() == itNUMERICDOMAIN && _inputGC2->datadef().domain()->ilwisType() == itNUMERICDOMAIN;
if (!isNumeric)
return false;
OperationHelperRaster helper;
_box = helper.initialize(_inputGC1, _outputGC, _expression.parm(0),
itRASTERSIZE | itENVELOPE | itCOORDSYSTEM | itGEOREF);
auto nrange1 = _inputGC1->datadef().range().dynamicCast<NumericRange>();
if (nrange1.isNull())
return false;
auto nrange2 = _inputGC2->datadef().range().dynamicCast<NumericRange>();
if (nrange2.isNull())
return false;
double rmax, rmin;
switch(_operator) {
case otPLUS:
rmin = nrange1->min() + nrange2->min();
rmax = nrange1->max() + nrange1->max();
break;
case otMINUS:
rmin = nrange1->min() - nrange2->min();
rmax = nrange1->max() - nrange1->max();
break;
case otDIV:
rmin = nrange2->min() != 0 ? nrange1->min() / nrange2->min() : std::min(nrange1->min(), nrange2->min());
rmax = nrange2->max() != 0 ? nrange1->max() / nrange2->max() : std::min(nrange1->max(), nrange2->max());
break;
case otMULT:
rmin = nrange1->min() * nrange2->min();
rmax = nrange1->max() * nrange1->max();
break;
}
NumericRange *newRange = new NumericRange(rmin,
rmax,
std::min(nrange1->step(), nrange2->step()));
IDomain dom;
dom.prepare("value");
_outputGC->datadef().domain(dom);
_outputGC->datadef().range(newRange);
_coveragecoverage = true;
return true;
}
bool BinaryMath::prepareRasterNumber(IlwisTypes ptype1, IlwisTypes ptype2) {
int mindex = (ptype1 & itNUMBER) == 0 ? 0 : 1;
int nindex = mindex ? 0 : 1;
QString gc = _expression.parm(mindex).value();
if (!_inputGC1.prepare(gc)) {
kernel()->issues()->log(TR(ERR_COULD_NOT_LOAD_2).arg(gc, ""));
return false;
}
if(_inputGC1->datadef().domain()->ilwisType() != itNUMERICDOMAIN)
return false;
_number = _expression.parm(nindex).value().toDouble();
OperationHelperRaster helper;
_box = helper.initialize(_inputGC1, _outputGC, _expression.parm(mindex),
itRASTERSIZE | itENVELOPE | itCOORDSYSTEM | itGEOREF);
auto nrange = _inputGC1->datadef().range().dynamicCast<NumericRange>();
if (nrange.isNull())
return false;
double rmax, rmin;
switch(_operator) {
case otPLUS:
rmin = nrange->min() + _number;
rmax = nrange->max() + _number;
break;
case otMINUS:
rmin = nrange->min() - _number;
rmax = nrange->max() - _number;
break;
case otDIV:
rmin = _number != 0 ? nrange->min() / _number : nrange->min();
rmax = _number != 0 ? nrange->max() / _number : nrange->max();
break;
case otMULT:
rmin = nrange->min() * _number;
rmax = nrange->max() * _number;
break;
}
NumericRange *newRange = new NumericRange(rmin,
rmax,
nrange->step());
IDomain dom;
dom.prepare("value");
_outputGC->datadef().domain(dom);
_outputGC->datadef().range(newRange);
return true;
}
OperationImplementation::State BinaryMath::prepare(ExecutionContext *,const SymbolTable&) {
if ( _expression.parameterCount() != 3){
return sPREPAREFAILED;
}
IlwisTypes ptype1 = _expression.parm(0).valuetype();
IlwisTypes ptype2 = _expression.parm(1).valuetype();
QString oper = _expression.parm(2).value();
if ( oper.toLower() == "add")
_operator = otPLUS;
else if ( oper.toLower() == "substract")
_operator = otMINUS;
else if ( oper == "divide")
_operator = otDIV;
else
_operator = otMULT;
if ( (ptype1 == itRASTER && hasType(ptype2,itNUMBER)) || (ptype2 == itRASTER && hasType(ptype1,itNUMBER)) ) {
if(!prepareRasterNumber(ptype1, ptype2))
return sPREPAREFAILED;
} else if ( ptype1 & ptype2 & itRASTER ) {
if(!prepareRasterRaster())
return sPREPAREFAILED;
}
return sPREPARED;
}
quint64 BinaryMath::createMetadata()
{
QString url = QString("ilwis://operations/binarymathraster");
Resource res(QUrl(url), itOPERATIONMETADATA);
res.addProperty("namespace","ilwis");
res.addProperty("longname","binarymathraster");
res.addProperty("syntax","binarymathraster(gridcoverage1,gridcoverage2|number,add|substract|divide|times|mod)");
res.addProperty("description",TR("generates a new numrical gridcoverage based on the operation, applied to all the pixels"));
res.addProperty("inparameters","3");
res.addProperty("pin_1_type", itRASTER | itNUMBER);
res.addProperty("pin_1_name", TR("input gridcoverage or number"));
res.addProperty("pin_1_domain","value");
res.addProperty("pin_1_desc",TR("input gridcoverage with a numerical domain or number"));
res.addProperty("pin_2_type", itRASTER | itNUMBER);
res.addProperty("pin_2_name", TR("input gridcoverage or number"));
res.addProperty("pin_2_domain","value");
res.addProperty("pin_2_desc",TR("input gridcoverage with a numerical domain or number"));
res.addProperty("pin_3_type", itSTRING);
res.addProperty("pin_3_name", TR("Operator"));
res.addProperty("pin_3_domain","string");
res.addProperty("pin_3_desc",TR("operator (add, substract,divide, multiply) applied to the other 2 input operators"));
res.addProperty("outparameters",1);
res.addProperty("pout_1_type", itRASTER);
res.addProperty("pout_1_name", TR("output gridcoverage"));
res.addProperty("pout_1_domain","value");
res.addProperty("pout_1_desc",TR("output gridcoverage with a numerical domain"));
res.prepare();
url += "=" + QString::number(res.id());
res.setUrl(url);
mastercatalog()->addItems({res});
return res.id();
}
| 33.721311 | 148 | 0.581624 | ridoo |
fe534add0e69038d2951136b4fb5c1bb8381d8a5 | 1,696 | cpp | C++ | TacticalFPS/Private/Weapons/WeaponStates/TacticalWeaponStateUnequipping.cpp | Tomura/TacticalPrototypeCPP | 0c8599a681222ad8e25f6db05e3e580b89c52974 | [
"MIT"
] | 6 | 2018-07-10T06:46:15.000Z | 2020-01-09T23:06:49.000Z | TacticalFPS/Private/Weapons/WeaponStates/TacticalWeaponStateUnequipping.cpp | Tomura/TacticalPrototypeCPP | 0c8599a681222ad8e25f6db05e3e580b89c52974 | [
"MIT"
] | null | null | null | TacticalFPS/Private/Weapons/WeaponStates/TacticalWeaponStateUnequipping.cpp | Tomura/TacticalPrototypeCPP | 0c8599a681222ad8e25f6db05e3e580b89c52974 | [
"MIT"
] | 1 | 2020-04-11T13:12:18.000Z | 2020-04-11T13:12:18.000Z | // Copyright (c) 2015-2016, Tammo Beil - All rights reserved
#include "TacticalFPS.h"
#include "TacticalCharacter.h"
#include "TacticalWeapon.h"
#include "TacticalWeaponState.h"
#include "TacticalWeaponStateEquipping.h"
#include "TacticalWeaponStateUnequipping.h"
UTacticalWeaponStateUnequipping::UTacticalWeaponStateUnequipping()
: Super()
{
}
void UTacticalWeaponStateUnequipping::BeginState(const UTacticalWeaponState* PrevState)
{
const UTacticalWeaponStateEquipping* PrevEquip = Cast<UTacticalWeaponStateEquipping>(PrevState);
float UnequipTime = GetWeapon()->UnequipTime;
GetWeapon()->SwitchLight(false);
// Remove Pending Unequips
GetWeapon()->bPendingUnequip = false;
// Simulate Unequip
GetWeapon()->LocalSimulateUnequip();
// Replicate Event to Clients
if (GetOwnerRole() == ROLE_Authority && !(GetNetMode() == ENetMode::NM_Standalone))
{
GetWeapon()->NetMulti_UnequipWeapon();
}
// Setup Timer or Finish it if time is 0
if (UnequipTime <= 0.f)
{
UnequipFinished();
}
else
{
GetWorldTimerManager().SetTimer(TimerUnequip, this, &UTacticalWeaponStateUnequipping::UnequipFinished, UnequipTime);
}
UE_LOG(LogInventory, Log, TEXT("Unequipping %s"), *GetName());
}
void UTacticalWeaponStateUnequipping::EndState(const UTacticalWeaponState* NextState)
{
GetWorldTimerManager().ClearTimer(TimerUnequip);
}
void UTacticalWeaponStateUnequipping::UnequipFinished()
{
GetWeapon()->GotoState(GetWeapon()->StateInactive);
GetWeapon()->WeaponUnequipped();
}
void UTacticalWeaponStateUnequipping::Equip()
{
PartialUnequipTime = FMath::Max(0.001f, GetWorldTimerManager().GetTimerElapsed(TimerUnequip));
GetWeapon()->GotoState(GetWeapon()->StateEquipping);
} | 26.092308 | 118 | 0.772995 | Tomura |
fe5368a2b513e51d16cb618d7cacb42b137e9138 | 1,992 | cpp | C++ | source/tests.cpp | GottaGoGitHub/programmiersprachen2020-aufgabe-1 | d7ec99a5f7cfd51bb54719887d7b51e5675b0b25 | [
"MIT"
] | null | null | null | source/tests.cpp | GottaGoGitHub/programmiersprachen2020-aufgabe-1 | d7ec99a5f7cfd51bb54719887d7b51e5675b0b25 | [
"MIT"
] | null | null | null | source/tests.cpp | GottaGoGitHub/programmiersprachen2020-aufgabe-1 | d7ec99a5f7cfd51bb54719887d7b51e5675b0b25 | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include <cmath>
int gcd(int a, int b)
{
if(b == 0)
return a;
return gcd(b, a % b);
}
TEST_CASE("describe_gcd", "[gcd]")
{
REQUIRE(gcd(2, 4) == 2);
REQUIRE(gcd(9, 6) == 3);
REQUIRE(gcd(3, 7) == 1);
}
int checksum(long num)
{
if(num < 0)
{
std::cout << "Error (negative Zahl)";
return 0;
}
else if(num < 10)
return num;
else
{
return num%10 + checksum(num/10);
}
}
TEST_CASE("describe_checksum", "[checksum]")
{
REQUIRE(checksum(120230) == 8);
REQUIRE(checksum(0) == 0);
REQUIRE(checksum(-124) == 0);
}
float fract(float num)
{
float res = num - (int)num;
return res;
}
TEST_CASE("describe_fract", "[fract]")
{
REQUIRE(fract(123.345) == Approx(0.345));
REQUIRE(fract(2.5564) == Approx(0.5564));
REQUIRE(fract(-1.23) == Approx(-0.23));
}
float cylvolume(float radius, float height)
{
float res = M_PI * radius * radius * height;
return res;
}
TEST_CASE("cylvolume", "[cylvolume]")
{
REQUIRE(cylvolume(5, 10) == Approx(785.4));
REQUIRE(cylvolume(0, 1000) == 0);
}
float cylsurface(float radius, float height)
{
int res = 2 * M_PI * radius * radius + ((2 * M_PI * radius) * height);
return res;
}
TEST_CASE("cylsurface", "[cylsurface]")
{
REQUIRE(cylsurface(5, 10) == Approx(471));
REQUIRE(cylsurface(0, 1000) == 0);
}
int factorial(int num)
{
int res = 1;
for(int i = 1; i <= num; ++i)
{
res *= i;
}
return res;
}
TEST_CASE("factorial", "[factorial]")
{
REQUIRE(factorial(4) == 24);
REQUIRE(factorial(3) == 6);
REQUIRE(factorial(0) == 1);
}
bool isPrime(int num)
{
if(num == 2) return true;
for(int i = 2; i <= num/2; ++i)
{
if(num % i != 0) return true;
else
{
return false;
}
}
}
TEST_CASE("isPrime", "[isPrime]")
{
REQUIRE(isPrime(2) == true);
REQUIRE(isPrime(7) == true);
REQUIRE(isPrime(1980) == false);
}
int main(int argc, char* argv[])
{
return Catch::Session().run(argc, argv);
} | 16.881356 | 72 | 0.585341 | GottaGoGitHub |
fe54c9b916c7940035eccb40afe61efb612f1909 | 6,652 | cpp | C++ | third/3rd_qwt/qwt_compass_rose.cpp | alexwang815/QWidgetDemo | 293a8d9c40d686397829c5d415fc531b6956883e | [
"MulanPSL-1.0"
] | 3,095 | 2019-10-11T03:00:33.000Z | 2022-03-31T08:15:13.000Z | third/3rd_qwt/qwt_compass_rose.cpp | alexwang815/QWidgetDemo | 293a8d9c40d686397829c5d415fc531b6956883e | [
"MulanPSL-1.0"
] | 28 | 2019-11-12T07:24:06.000Z | 2022-02-28T02:04:48.000Z | third/3rd_qwt/qwt_compass_rose.cpp | alexwang815/QWidgetDemo | 293a8d9c40d686397829c5d415fc531b6956883e | [
"MulanPSL-1.0"
] | 1,023 | 2019-10-09T12:54:07.000Z | 2022-03-30T04:02:07.000Z | /* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_compass_rose.h"
#include "qwt_point_polar.h"
#include "qwt_painter.h"
#include "qpainterpath.h"
#include "qpainter.h"
static QPointF qwtIntersection(
QPointF p11, QPointF p12, QPointF p21, QPointF p22 )
{
const QLineF line1( p11, p12 );
const QLineF line2( p21, p22 );
QPointF pos;
if ( line1.intersect( line2, &pos ) == QLineF::NoIntersection )
return QPointF();
return pos;
}
class QwtSimpleCompassRose::PrivateData
{
public:
PrivateData():
width( 0.2 ),
numThorns( 8 ),
numThornLevels( -1 ),
shrinkFactor( 0.9 )
{
}
double width;
int numThorns;
int numThornLevels;
double shrinkFactor;
};
/*!
Constructor
\param numThorns Number of thorns
\param numThornLevels Number of thorn levels
*/
QwtSimpleCompassRose::QwtSimpleCompassRose(
int numThorns, int numThornLevels )
{
d_data = new PrivateData();
d_data->numThorns = numThorns;
d_data->numThornLevels = numThornLevels;
const QColor dark( 128, 128, 255 );
const QColor light( 192, 255, 255 );
QPalette palette;
palette.setColor( QPalette::Dark, dark );
palette.setColor( QPalette::Light, light );
setPalette( palette );
}
//! Destructor
QwtSimpleCompassRose::~QwtSimpleCompassRose()
{
delete d_data;
}
/*!
Set the Factor how to shrink the thorns with each level
The default value is 0.9.
\param factor Shrink factor
\sa shrinkFactor()
*/
void QwtSimpleCompassRose::setShrinkFactor( double factor )
{
d_data->shrinkFactor = factor;
}
/*!
\return Factor how to shrink the thorns with each level
\sa setShrinkFactor()
*/
double QwtSimpleCompassRose::shrinkFactor() const
{
return d_data->shrinkFactor;
}
/*!
Draw the rose
\param painter Painter
\param center Center point
\param radius Radius of the rose
\param north Position
\param cg Color group
*/
void QwtSimpleCompassRose::draw( QPainter *painter, const QPointF ¢er,
double radius, double north, QPalette::ColorGroup cg ) const
{
QPalette pal = palette();
pal.setCurrentColorGroup( cg );
drawRose( painter, pal, center, radius, north, d_data->width,
d_data->numThorns, d_data->numThornLevels, d_data->shrinkFactor );
}
/*!
Draw the rose
\param painter Painter
\param palette Palette
\param center Center of the rose
\param radius Radius of the rose
\param north Position pointing to north
\param width Width of the rose
\param numThorns Number of thorns
\param numThornLevels Number of thorn levels
\param shrinkFactor Factor to shrink the thorns with each level
*/
void QwtSimpleCompassRose::drawRose(
QPainter *painter,
const QPalette &palette,
const QPointF ¢er, double radius, double north, double width,
int numThorns, int numThornLevels, double shrinkFactor )
{
if ( numThorns < 4 )
numThorns = 4;
if ( numThorns % 4 )
numThorns += 4 - numThorns % 4;
if ( numThornLevels <= 0 )
numThornLevels = numThorns / 4;
if ( shrinkFactor >= 1.0 )
shrinkFactor = 1.0;
if ( shrinkFactor <= 0.5 )
shrinkFactor = 0.5;
painter->save();
painter->setPen( Qt::NoPen );
for ( int j = 1; j <= numThornLevels; j++ )
{
double step = qPow( 2.0, j ) * M_PI / numThorns;
if ( step > M_PI_2 )
break;
double r = radius;
for ( int k = 0; k < 3; k++ )
{
if ( j + k < numThornLevels )
r *= shrinkFactor;
}
double leafWidth = r * width;
if ( 2.0 * M_PI / step > 32 )
leafWidth = 16;
const double origin = qwtRadians( north );
for ( double angle = origin;
angle < 2.0 * M_PI + origin; angle += step )
{
const QPointF p = qwtPolar2Pos( center, r, angle );
const QPointF p1 = qwtPolar2Pos( center, leafWidth, angle + M_PI_2 );
const QPointF p2 = qwtPolar2Pos( center, leafWidth, angle - M_PI_2 );
const QPointF p3 = qwtPolar2Pos( center, r, angle + step / 2.0 );
const QPointF p4 = qwtPolar2Pos( center, r, angle - step / 2.0 );
QPainterPath darkPath;
darkPath.moveTo( center );
darkPath.lineTo( p );
darkPath.lineTo( qwtIntersection( center, p3, p1, p ) );
painter->setBrush( palette.brush( QPalette::Dark ) );
painter->drawPath( darkPath );
QPainterPath lightPath;
lightPath.moveTo( center );
lightPath.lineTo( p );
lightPath.lineTo( qwtIntersection( center, p4, p2, p ) );
painter->setBrush( palette.brush( QPalette::Light ) );
painter->drawPath( lightPath );
}
}
painter->restore();
}
/*!
Set the width of the rose heads. Lower value make thinner heads.
The range is limited from 0.03 to 0.4.
\param width Width
*/
void QwtSimpleCompassRose::setWidth( double width )
{
d_data->width = width;
if ( d_data->width < 0.03 )
d_data->width = 0.03;
if ( d_data->width > 0.4 )
d_data->width = 0.4;
}
/*!
\return Width of the rose
\sa setWidth()
*/
double QwtSimpleCompassRose::width() const
{
return d_data->width;
}
/*!
Set the number of thorns on one level
The number is aligned to a multiple of 4, with a minimum of 4
\param numThorns Number of thorns
\sa numThorns(), setNumThornLevels()
*/
void QwtSimpleCompassRose::setNumThorns( int numThorns )
{
if ( numThorns < 4 )
numThorns = 4;
if ( numThorns % 4 )
numThorns += 4 - numThorns % 4;
d_data->numThorns = numThorns;
}
/*!
\return Number of thorns
\sa setNumThorns(), setNumThornLevels()
*/
int QwtSimpleCompassRose::numThorns() const
{
return d_data->numThorns;
}
/*!
Set the of thorns levels
\param numThornLevels Number of thorns levels
\sa setNumThorns(), numThornLevels()
*/
void QwtSimpleCompassRose::setNumThornLevels( int numThornLevels )
{
d_data->numThornLevels = numThornLevels;
}
/*!
\return Number of thorn levels
\sa setNumThorns(), setNumThornLevels()
*/
int QwtSimpleCompassRose::numThornLevels() const
{
return d_data->numThornLevels;
}
| 24.546125 | 81 | 0.622369 | alexwang815 |
fe5567630d6abdd647aac1141aaf146bce1d5381 | 221 | cpp | C++ | 4th semester/lab_7/src/Skaner.cpp | kmalski/cpp_labs | 52b0fc84319d6cc57ff7bfdb787aa5eb09edf592 | [
"MIT"
] | 1 | 2020-05-19T17:14:55.000Z | 2020-05-19T17:14:55.000Z | 4th semester/lab_7/src/Skaner.cpp | kmalski/CPP_Laboratories | 52b0fc84319d6cc57ff7bfdb787aa5eb09edf592 | [
"MIT"
] | null | null | null | 4th semester/lab_7/src/Skaner.cpp | kmalski/CPP_Laboratories | 52b0fc84319d6cc57ff7bfdb787aa5eb09edf592 | [
"MIT"
] | null | null | null | #include <string>
#include "Skaner.h"
Skaner::Skaner(Rozdzielczosc roz) : _roz(roz) {}
std::string Skaner::rodzaj() const {
return "Skaner";
}
std::string Skaner::rozdzielczosc() const {
return _roz.print();
}
| 17 | 48 | 0.669683 | kmalski |
fe5a3ab7a44bcbc4aaacb45888e5ae4959f9f768 | 4,600 | cpp | C++ | utils/eglplus/egl/src/EGL/glx/extensions.cpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 364 | 2015-01-01T09:38:23.000Z | 2022-03-22T05:32:00.000Z | utils/eglplus/egl/src/EGL/glx/extensions.cpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 55 | 2015-01-06T16:42:55.000Z | 2020-07-09T04:21:41.000Z | utils/eglplus/egl/src/EGL/glx/extensions.cpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 57 | 2015-01-07T18:35:49.000Z | 2022-03-22T05:32:04.000Z | /**
* .file EGL/glx/extension.cpp
* .brief EGL Extensions functionality implementation.
*
* @author Matus Chochlik
*
* Copyright 2012-2019 Matus Chochlik. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#include <EGL/egl.h>
#include <GL/glx.h>
#include <X11/Xlib.h>
#include <cstring>
#include "ext/NV_native_query.hpp"
//------------------------------------------------------------------------------
// EGL API
//------------------------------------------------------------------------------
extern "C" {
//------------------------------------------------------------------------------
// eglGetProcAddress
//------------------------------------------------------------------------------
EGLAPI void EGLAPIENTRY (*eglGetProcAddress(const char* procname))() {
using fnptr = void (*)();
// EGL 1.4
if(std::strcmp(procname, "eglGetError") == 0)
return fnptr(&eglGetError);
if(std::strcmp(procname, "eglGetDisplay") == 0)
return fnptr(&eglGetDisplay);
if(std::strcmp(procname, "eglInitialize") == 0)
return fnptr(&eglInitialize);
if(std::strcmp(procname, "eglTerminate") == 0)
return fnptr(&eglTerminate);
if(std::strcmp(procname, "eglQueryString") == 0)
return fnptr(&eglQueryString);
if(std::strcmp(procname, "eglGetConfigs") == 0)
return fnptr(&eglGetConfigs);
if(std::strcmp(procname, "eglChooseConfig") == 0)
return fnptr(&eglChooseConfig);
if(std::strcmp(procname, "eglGetConfigAttrib") == 0)
return fnptr(&eglGetConfigAttrib);
if(std::strcmp(procname, "eglCreateWindowSurface") == 0)
return fnptr(&eglCreateWindowSurface);
if(std::strcmp(procname, "eglCreatePbufferSurface") == 0)
return fnptr(&eglCreatePbufferSurface);
if(std::strcmp(procname, "eglCreatePixmapSurface") == 0)
return fnptr(&eglCreatePixmapSurface);
if(std::strcmp(procname, "eglDestroySurface") == 0)
return fnptr(&eglDestroySurface);
if(std::strcmp(procname, "eglQuerySurface") == 0)
return fnptr(&eglQuerySurface);
if(std::strcmp(procname, "eglBindAPI") == 0)
return fnptr(&eglBindAPI);
if(std::strcmp(procname, "eglQueryAPI") == 0)
return fnptr(&eglQueryAPI);
if(std::strcmp(procname, "eglWaitClient") == 0)
return fnptr(&eglWaitClient);
if(std::strcmp(procname, "eglReleaseThread") == 0)
return fnptr(&eglReleaseThread);
if(std::strcmp(procname, "eglCreatePbufferFromClientBuffer") == 0)
return fnptr(&eglCreatePbufferFromClientBuffer);
if(std::strcmp(procname, "eglSurfaceAttrib") == 0)
return fnptr(&eglSurfaceAttrib);
if(std::strcmp(procname, "eglBindTexImage") == 0)
return fnptr(&eglBindTexImage);
if(std::strcmp(procname, "eglReleaseTexImage") == 0)
return fnptr(&eglReleaseTexImage);
if(std::strcmp(procname, "eglSwapInterval") == 0)
return fnptr(&eglSwapInterval);
if(std::strcmp(procname, "eglCreateContext") == 0)
return fnptr(&eglCreateContext);
if(std::strcmp(procname, "eglDestroyContext") == 0)
return fnptr(&eglDestroyContext);
if(std::strcmp(procname, "eglMakeCurrent") == 0)
return fnptr(&eglMakeCurrent);
if(std::strcmp(procname, "eglGetCurrentContext") == 0)
return fnptr(&eglGetCurrentContext);
if(std::strcmp(procname, "eglGetCurrentSurface") == 0)
return fnptr(&eglGetCurrentSurface);
if(std::strcmp(procname, "eglGetCurrentDisplay") == 0)
return fnptr(&eglGetCurrentDisplay);
if(std::strcmp(procname, "eglQueryContext") == 0)
return fnptr(&eglQueryContext);
if(std::strcmp(procname, "eglWaitGL") == 0)
return fnptr(&eglWaitGL);
if(std::strcmp(procname, "eglWaitNative") == 0)
return fnptr(&eglWaitNative);
if(std::strcmp(procname, "eglSwapBuffers") == 0)
return fnptr(&eglSwapBuffers);
if(std::strcmp(procname, "eglCopyBuffers") == 0)
return fnptr(&eglCopyBuffers);
// EGL_NV_native_query
if(std::strcmp(procname, "eglQueryNativeDisplayNV") == 0)
return fnptr(&eglQueryNativeDisplayNV);
if(std::strcmp(procname, "eglQueryNativeWindowNV") == 0)
return fnptr(&eglQueryNativeWindowNV);
if(std::strcmp(procname, "eglQueryNativePixmapNV") == 0)
return fnptr(&eglQueryNativePixmapNV);
return ::glXGetProcAddress((GLubyte*)procname);
}
//------------------------------------------------------------------------------
} // extern "C"
| 42.201835 | 80 | 0.606087 | matus-chochlik |
fe602b75c04af56410af0af201b9448ed922edca | 16,407 | cpp | C++ | CaptureManagerSource/CustomisedMixerNode/CustomisedMixerNode.cpp | luoyingwen/CaptureManagerSDK | e96395a120175a45c56ff4e2b3283b807a42fd75 | [
"MIT"
] | 64 | 2020-07-20T09:35:16.000Z | 2022-03-27T19:13:08.000Z | CaptureManagerSource/CustomisedMixerNode/CustomisedMixerNode.cpp | luoyingwen/CaptureManagerSDK | e96395a120175a45c56ff4e2b3283b807a42fd75 | [
"MIT"
] | 8 | 2020-07-30T09:20:28.000Z | 2022-03-03T22:37:10.000Z | CaptureManagerSource/CustomisedMixerNode/CustomisedMixerNode.cpp | luoyingwen/CaptureManagerSDK | e96395a120175a45c56ff4e2b3283b807a42fd75 | [
"MIT"
] | 28 | 2020-07-20T13:02:42.000Z | 2022-03-18T07:36:05.000Z | /*
MIT License
Copyright(c) 2020 Evgeny Pereguda
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 "CustomisedMixerNode.h"
#include "../Common/MFHeaders.h"
#include "../Common/Common.h"
#include "../Common/GUIDs.h"
#include "../LogPrintOut/LogPrintOut.h"
#include "../MediaFoundationManager/MediaFoundationManager.h"
#include "../VideoRendererManager/IMixerStreamPositionControl.h"
#include "MixerWrapper.h"
namespace CaptureManager
{
namespace MediaSession
{
namespace CustomisedMediaSession
{
using namespace CaptureManager::Core;
CustomisedMixerNode::CustomisedMixerNode(
UINT32 aIndex,
IMixerWrapper* aPtrIMixerWrapper):
mIndex(aIndex)
{
mMixerWrapper = aPtrIMixerWrapper;
}
CustomisedMixerNode::~CustomisedMixerNode(){}
HRESULT CustomisedMixerNode::create(
DWORD aInputNodeAmount,
std::vector<CComPtrCustom<IUnknown>>& aRefOutputNodes)
{
HRESULT lresult = E_FAIL;
do
{
CComPtrCustom<IMixerWrapper> lMixerWrapper(new MixerWrapper(aInputNodeAmount));
for (UINT32 lIndex = 0; lIndex < aInputNodeAmount; lIndex++)
{
CComPtrCustom<CustomisedMixerNode> lCustomisedMixerNode(new CustomisedMixerNode(lIndex, lMixerWrapper));
CComPtrCustom<IMFTransform> lTransform;
LOG_INVOKE_QUERY_INTERFACE_METHOD(lCustomisedMixerNode, &lTransform);
CComPtrCustom<IMFTopologyNode> lCustomisedMixerTopologyNode;
LOG_INVOKE_MF_FUNCTION(MFCreateTopologyNode,
MF_TOPOLOGY_TYPE::MF_TOPOLOGY_TRANSFORM_NODE,
&lCustomisedMixerTopologyNode);
LOG_INVOKE_MF_METHOD(SetObject,
lCustomisedMixerTopologyNode,
lTransform);
LOG_INVOKE_MF_METHOD(SetUINT32,
lCustomisedMixerTopologyNode,
CM_MixerNode,
TRUE);
CComPtrCustom<IUnknown> lUnknown;
LOG_INVOKE_QUERY_INTERFACE_METHOD(lCustomisedMixerTopologyNode, &lUnknown);
aRefOutputNodes.push_back(lUnknown);
}
lresult = S_OK;
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::GetStreamLimits(DWORD* aPtrInputMinimum, DWORD* aPtrInputMaximum,
DWORD* aPtrOutputMinimum, DWORD* aPtrOutputMaximum)
{
HRESULT lresult = E_FAIL;
do
{
LOG_CHECK_STATE_DESCR(aPtrInputMinimum == NULL ||
aPtrInputMaximum == NULL ||
aPtrOutputMinimum == NULL ||
aPtrOutputMaximum == NULL, E_POINTER);
*aPtrInputMinimum = 1;
*aPtrInputMaximum = 1;
*aPtrOutputMinimum = 1;
*aPtrOutputMaximum = 1;
lresult = S_OK;
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::GetStreamIDs(DWORD aInputIDArraySize, DWORD* aPtrInputIDs,
DWORD aOutputIDArraySize, DWORD* aPtrOutputIDs)
{
return E_NOTIMPL;
}
STDMETHODIMP CustomisedMixerNode::GetStreamCount(DWORD* aPtrInputStreams, DWORD* aPtrOutputStreams)
{
HRESULT lresult = E_FAIL;
do
{
LOG_CHECK_STATE_DESCR(aPtrInputStreams == NULL || aPtrOutputStreams == NULL, E_POINTER);
*aPtrInputStreams = 1;
*aPtrOutputStreams = 1;
lresult = S_OK;
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::GetInputStreamInfo(DWORD aInputStreamID,
MFT_INPUT_STREAM_INFO* aPtrStreamInfo)
{
HRESULT lresult = S_OK;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrStreamInfo);
LOG_CHECK_STATE_DESCR(aInputStreamID != 0, MF_E_INVALIDSTREAMNUMBER);
aPtrStreamInfo->dwFlags = MFT_INPUT_STREAM_WHOLE_SAMPLES |
MFT_INPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER;
aPtrStreamInfo->cbMaxLookahead = 0;
aPtrStreamInfo->cbAlignment = 0;
aPtrStreamInfo->hnsMaxLatency = 0;
aPtrStreamInfo->cbSize = 0;
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::GetOutputStreamInfo(DWORD aOutputStreamID,
MFT_OUTPUT_STREAM_INFO* aPtrStreamInfo)
{
HRESULT lresult = S_OK;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrStreamInfo);
LOG_CHECK_STATE_DESCR(aOutputStreamID != 0, MF_E_INVALIDSTREAMNUMBER);
aPtrStreamInfo->dwFlags =
MFT_OUTPUT_STREAM_WHOLE_SAMPLES |
MFT_OUTPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER |
MFT_OUTPUT_STREAM_FIXED_SAMPLE_SIZE |
MFT_OUTPUT_STREAM_PROVIDES_SAMPLES;
aPtrStreamInfo->cbAlignment = 0;
aPtrStreamInfo->cbSize = 0;
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::GetInputStreamAttributes(DWORD aInputStreamID,
IMFAttributes** aPtrPtrAttributes)
{
return E_NOTIMPL;
}
STDMETHODIMP CustomisedMixerNode::GetOutputStreamAttributes(DWORD aOutputStreamID,
IMFAttributes** aPtrPtrAttributes)
{
return E_NOTIMPL;
}
STDMETHODIMP CustomisedMixerNode::DeleteInputStream(DWORD aStreamID)
{
return E_NOTIMPL;
}
STDMETHODIMP CustomisedMixerNode::AddInputStreams(DWORD aStreams, DWORD* aPtrStreamIDs)
{
return E_NOTIMPL;
}
STDMETHODIMP CustomisedMixerNode::GetInputAvailableType(DWORD aInputStreamID, DWORD aTypeIndex,
IMFMediaType** aPtrPtrType)
{
HRESULT lresult = S_OK;
CComPtrCustom<IMFMediaType> lMediaType;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrPtrType);
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::GetOutputAvailableType(DWORD aOutputStreamID, DWORD aTypeIndex,
IMFMediaType** aPtrPtrType)
{
HRESULT lresult = S_OK;
CComPtrCustom<IMFMediaType> lMediaType;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrPtrType);
LOG_CHECK_PTR_MEMORY(mMixerTransform);
LOG_INVOKE_MF_METHOD(GetOutputAvailableType, mMixerTransform, aOutputStreamID, aTypeIndex, aPtrPtrType);
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::SetInputType(DWORD aInputStreamID, IMFMediaType* aPtrType,
DWORD aFlags)
{
HRESULT lresult = S_OK;
do
{
LOG_CHECK_PTR_MEMORY(aPtrType);
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(mMixerWrapper);
if (mIndex == 0)
{
LOG_INVOKE_POINTER_METHOD(mMixerWrapper, initialize, aPtrType);
}
if (!mMixerTransform)
{
LOG_INVOKE_POINTER_METHOD(mMixerWrapper, getMixer, &mMixerTransform);
}
LOG_CHECK_PTR_MEMORY(mMixerTransform);
if (mIndex == 0)
{
LOG_INVOKE_MF_METHOD(SetOutputType, mMixerTransform, 0, aPtrType, MFT_SET_TYPE_TEST_ONLY);
LOG_INVOKE_MF_METHOD(SetOutputType, mMixerTransform, 0, aPtrType, 0);
}
LOG_INVOKE_MF_METHOD(SetInputType, mMixerTransform, mIndex, aPtrType, MFT_SET_TYPE_TEST_ONLY);
LOG_INVOKE_MF_METHOD(SetInputType, mMixerTransform, mIndex, aPtrType, 0);
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::SetOutputType(DWORD aOutputStreamID, IMFMediaType* aPtrType,
DWORD aFlags)
{
HRESULT lresult = S_OK;
do
{
std::lock_guard<std::mutex> lock(mMutex);
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::GetInputCurrentType(DWORD aInputStreamID, IMFMediaType** aPtrPtrType)
{
HRESULT lresult = S_OK;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrPtrType);
LOG_CHECK_PTR_MEMORY(mMixerTransform);
//if (mIndex == 0)
//{
// LOG_INVOKE_MF_METHOD(GetOutputCurrentType, mMixerTransform, 0, aPtrPtrType);
//}
//else
{
LOG_INVOKE_MF_METHOD(GetInputCurrentType, mMixerTransform, mIndex, aPtrPtrType);
}
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::GetOutputCurrentType(DWORD aOutputStreamID, IMFMediaType** aPtrPtrType)
{
HRESULT lresult = S_OK;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrPtrType);
LOG_CHECK_PTR_MEMORY(mMixerTransform);
LOG_INVOKE_MF_METHOD(GetOutputCurrentType, mMixerTransform, 0, aPtrPtrType);
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::GetInputStatus(DWORD aInputStreamID, DWORD* aPtrFlags)
{
HRESULT lresult = S_OK;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrFlags);
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::GetOutputStatus(DWORD* aPtrFlags)
{
return E_NOTIMPL;
}
STDMETHODIMP CustomisedMixerNode::SetOutputBounds(LONGLONG aLowerBound, LONGLONG aUpperBound)
{
return E_NOTIMPL;
}
STDMETHODIMP CustomisedMixerNode::ProcessEvent(DWORD aInputStreamID, IMFMediaEvent* aPtrEvent)
{
return E_NOTIMPL;
}
STDMETHODIMP CustomisedMixerNode::GetAttributes(IMFAttributes** aPtrPtrAttributes)
{
return E_NOTIMPL;
}
STDMETHODIMP CustomisedMixerNode::ProcessMessage(MFT_MESSAGE_TYPE aMessage, ULONG_PTR aParam)
{
HRESULT lresult = S_OK;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(mMixerTransform);
if (aMessage == MFT_MESSAGE_TYPE::MFT_MESSAGE_COMMAND_FLUSH)
{
CComPtrCustom<CaptureManager::Sinks::EVR::IMixerStreamPositionControl> lIMixerStreamPositionControl;
mMixerTransform->QueryInterface(IID_PPV_ARGS(&lIMixerStreamPositionControl));
if (lIMixerStreamPositionControl)
lIMixerStreamPositionControl->flush(mIndex);
LOG_INVOKE_MF_METHOD(ProcessMessage, mMixerTransform, aMessage, mIndex);
}
else
if (mIndex == 0)
{
LOG_INVOKE_MF_METHOD(ProcessMessage, mMixerTransform, aMessage, aParam);
}
else
{
LOG_INVOKE_MF_METHOD(ProcessMessage, mMixerTransform, aMessage, mIndex);
}
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::ProcessInput(DWORD aInputStreamID, IMFSample* aPtrSample,
DWORD aFlags)
{
HRESULT lresult = S_OK;
DWORD dwBufferCount = 0;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrSample);
LOG_CHECK_PTR_MEMORY(mMixerTransform);
LOG_INVOKE_MF_METHOD(ProcessInput,
mMixerTransform,
mIndex,
aPtrSample,
0);
if (mIndex == 0)
{
MFT_OUTPUT_DATA_BUFFER lBuffer;
ZeroMemory(&lBuffer, sizeof(lBuffer));
lBuffer.dwStreamID = 0;
DWORD lState(0);
LOG_INVOKE_MF_METHOD(ProcessOutput,
mMixerTransform,
0,
1,
&lBuffer,
&lState);
CComPtrCustom<IMFSample> lSample(lBuffer.pSample);
mSample = lSample;
}
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::ProcessOutput(DWORD aFlags, DWORD aOutputBufferCount,
MFT_OUTPUT_DATA_BUFFER* aPtrOutputSamples, DWORD* aPtrStatus)
{
HRESULT lresult = S_OK;
do
{
std::lock_guard<std::mutex> lock(mMutex);
LOG_CHECK_PTR_MEMORY(aPtrOutputSamples);
LOG_CHECK_PTR_MEMORY(aPtrStatus);
LOG_CHECK_STATE_DESCR(aOutputBufferCount != 1 || aFlags != 0, E_INVALIDARG);
LOG_CHECK_STATE_DESCR(!mSample, MF_E_TRANSFORM_NEED_MORE_INPUT);
aPtrOutputSamples[0].pSample = mSample.Detach();
aPtrOutputSamples[0].dwStatus = 0;
*aPtrStatus = 0;
} while (false);
return lresult;
}
// IVideoMixerControl implements
STDMETHODIMP CustomisedMixerNode::setPosition(
/* [in] */ FLOAT aLeft,
/* [in] */ FLOAT aRight,
/* [in] */ FLOAT aTop,
/* [in] */ FLOAT aBottom)
{
HRESULT lresult(E_FAIL);
do
{
if (mIndex == 0)
break;
LOG_CHECK_PTR_MEMORY(mMixerTransform);
CComPtrCustom<Sinks::EVR::IMixerStreamPositionControl> lIMixerStreamPositionControl;
LOG_INVOKE_QUERY_INTERFACE_METHOD(mMixerTransform, &lIMixerStreamPositionControl);
LOG_CHECK_PTR_MEMORY(lIMixerStreamPositionControl);
LOG_INVOKE_POINTER_METHOD(lIMixerStreamPositionControl, setPosition,
mIndex,
aLeft,
aRight,
aTop,
aBottom);
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::setSrcPosition(
/* [in] */ FLOAT aLeft,
/* [in] */ FLOAT aRight,
/* [in] */ FLOAT aTop,
/* [in] */ FLOAT aBottom)
{
HRESULT lresult(E_FAIL);
do
{
if (mIndex == 0)
break;
LOG_CHECK_PTR_MEMORY(mMixerTransform);
CComPtrCustom<Sinks::EVR::IMixerStreamPositionControl> lIMixerStreamPositionControl;
LOG_INVOKE_QUERY_INTERFACE_METHOD(mMixerTransform, &lIMixerStreamPositionControl);
LOG_CHECK_PTR_MEMORY(lIMixerStreamPositionControl);
LOG_INVOKE_POINTER_METHOD(lIMixerStreamPositionControl, setSrcPosition,
mIndex,
aLeft,
aRight,
aTop,
aBottom);
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::setZOrder(
/* [in] */ DWORD aZOrder)
{
HRESULT lresult(E_FAIL);
do
{
if (mIndex == 0)
break;
LOG_CHECK_PTR_MEMORY(mMixerTransform);
CComPtrCustom<Sinks::EVR::IMixerStreamPositionControl> lIMixerStreamPositionControl;
LOG_INVOKE_QUERY_INTERFACE_METHOD(mMixerTransform, &lIMixerStreamPositionControl);
LOG_CHECK_PTR_MEMORY(lIMixerStreamPositionControl);
LOG_INVOKE_POINTER_METHOD(lIMixerStreamPositionControl, setZOrder,
mIndex,
aZOrder);
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::setOpacity(
/* [in] */ FLOAT aOpacity)
{
HRESULT lresult(E_FAIL);
do
{
if (mIndex == 0)
break;
LOG_CHECK_PTR_MEMORY(mMixerTransform);
CComPtrCustom<Sinks::EVR::IMixerStreamPositionControl> lIMixerStreamPositionControl;
LOG_INVOKE_QUERY_INTERFACE_METHOD(mMixerTransform, &lIMixerStreamPositionControl);
LOG_CHECK_PTR_MEMORY(lIMixerStreamPositionControl);
LOG_INVOKE_POINTER_METHOD(lIMixerStreamPositionControl, setOpacity,
mIndex,
aOpacity);
} while (false);
return lresult;
}
STDMETHODIMP CustomisedMixerNode::flush()
{
HRESULT lresult(E_FAIL);
do
{
if (mIndex == 0)
break;
LOG_CHECK_PTR_MEMORY(mMixerTransform);
CComPtrCustom<Sinks::EVR::IMixerStreamPositionControl> lIMixerStreamPositionControl;
LOG_INVOKE_QUERY_INTERFACE_METHOD(mMixerTransform, &lIMixerStreamPositionControl);
LOG_CHECK_PTR_MEMORY(lIMixerStreamPositionControl);
LOG_INVOKE_POINTER_METHOD(lIMixerStreamPositionControl, flush,
mIndex);
} while (false);
return lresult;
}
// IAudioMixerControl implements
STDMETHODIMP CustomisedMixerNode::setRelativeVolume(
/* [in] */ FLOAT aRelativeVolume)
{
HRESULT lresult(E_FAIL);
do
{
if (mIndex == 0)
break;
LOG_CHECK_PTR_MEMORY(mMixerTransform);
CComPtrCustom<CaptureManager::MediaSession::CustomisedMediaSession::IAudioMixerStreamControl> lAudioMixerStreamControl;
LOG_INVOKE_QUERY_INTERFACE_METHOD(mMixerTransform, &lAudioMixerStreamControl);
LOG_CHECK_PTR_MEMORY(lAudioMixerStreamControl);
LOG_INVOKE_POINTER_METHOD(lAudioMixerStreamControl, setRelativeVolume,
mIndex,
aRelativeVolume);
} while (false);
return lresult;
}
}
}
} | 23.141044 | 124 | 0.702627 | luoyingwen |
fe62cbd256227776390af7b35737e37a567b36fc | 2,331 | cpp | C++ | 04_sequence_containers/03_list/01_intro.cpp | Gmrakari/STL | 1fc90b1c573a140efa695efd5c55e80ad03b7595 | [
"MIT"
] | null | null | null | 04_sequence_containers/03_list/01_intro.cpp | Gmrakari/STL | 1fc90b1c573a140efa695efd5c55e80ad03b7595 | [
"MIT"
] | null | null | null | 04_sequence_containers/03_list/01_intro.cpp | Gmrakari/STL | 1fc90b1c573a140efa695efd5c55e80ad03b7595 | [
"MIT"
] | null | null | null |
/*
* Date:2021-05-28 13:10
* filename:01_intro
*
*/
/*
* 相较于vector连续性空间,list复杂许多,它的好处是每次插入或和删除一个元素
* 就配置或释放一个元素空间
* 对于任何位置的元素插入或删除移除,list永远是常熟时间
*
*
* list和vector是两个最常被使用的容器
*
*/
/*
* list node
*/
template <class T>
struct __list_node {
typedef void* void_pointer;
void_pointer prev;
void_pointer next;
T data;
};
/*
* list 的 iterator
*
* list不能再像vector一样以普通指针作为迭代器,因为其节点不保证再存储空间连续存在
* list迭代器必须有能力指向list的节点,并有能力进行正确的递增、递减、取值、成员取值等操作
*
* 由于STL list是一个双向链表(double linked-list),迭代器必须具备前移、后移的能力
* 所以list提供的是Bidirectional Iterators
*
* list 有一个重要性质:插入操作(insert)和接合操作(splice)都不会造成原有list迭代器失效
*/
template <class T, class Ref, class Ptr>
struct __list_iterator {
typedef __list_iterator<T, T&, T*> iterator;
typedef __list_iterator<T, Ref, Ptr> self;
typedef bidirectional_iterator_tag iterator_category;
typedef T value_type;
typedef Ptr pointer;
typedef Ref reference;
typedef __list_node<T>* link_type;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
link_type node;
//constructor
__list_iterator(link_type x) : node(x) { }
__list_iterator() {}
__list_iterator(const iterator& x) : node(x.node) {}
bool operator==(const self& x) const { return node == x.node; }
bool operator!=(const self& x) const { return node != x.node; }
//以下迭代器取值(dereference),取的是节点的数据值
reference operator*() const {reutrn (*node).data;}
//以下是迭代器的成员存取(member access) 运算子的标准做法
pointer operator->() const { return & (operator*()); }
//对迭代器累加1,就是前进一个节点
self& operator++() {
node = (link_type)((*node).next);
return *this;
}
self operator++(int) {
self tmp = *this;
++*this;
return tmp;
}
//对迭代器减少1,就是后退一个节点
self& operator--(int) {
self tmp = *this;
--*this;
return tmp;
}
};
/*
* list data structure
* STL list 不仅是一个双向链表,而且还是一个环状双向链表,
* 所以它只需要一个指针,便开业i完整表现整个链表
*
*/
template <class T, class Alloc = alloc>
class list {
protected:
typedef __list_node<T> list_node;
public:
typeid list_node* link_type;
protected:
link_type node;
};
iterator begin() { return (link_type)((*node).next); }
iterator end() { return node; }
bool empty() const { return node->next == node; }
size_type size() const {
size_type result = 0;
destance(begin(), end(), result);
return result;
}
reference front() { return *begin(); }
reference back() { return *(--end()); }
| 18.95122 | 64 | 0.697555 | Gmrakari |
fe62d43f6963dd25b4bafee2dc27735d17e01046 | 193 | hpp | C++ | src/Griddly/Core/Observers/Vulkan/VulkanQueueFamilyIndices.hpp | DavidSlayback/Griddly | b97866905fd897f5e8d4c36e1f0cf48893b1fff6 | [
"MIT"
] | null | null | null | src/Griddly/Core/Observers/Vulkan/VulkanQueueFamilyIndices.hpp | DavidSlayback/Griddly | b97866905fd897f5e8d4c36e1f0cf48893b1fff6 | [
"MIT"
] | null | null | null | src/Griddly/Core/Observers/Vulkan/VulkanQueueFamilyIndices.hpp | DavidSlayback/Griddly | b97866905fd897f5e8d4c36e1f0cf48893b1fff6 | [
"MIT"
] | null | null | null | #pragma once
#include <vulkan/vulkan.h>
namespace vk {
struct VulkanQueueFamilyIndices {
uint32_t graphicsIndices = UINT32_MAX;
uint32_t computeIndices = UINT32_MAX;
};
} // namespace vk | 19.3 | 40 | 0.761658 | DavidSlayback |
fe6427d40627c5b921a651cdd224c9b0c236aadc | 1,146 | cpp | C++ | VDM/main.cpp | ALEHACKsp/VDM | 08983dc37f1ed371800d87305d07f30c6e7b3f42 | [
"MIT"
] | 1 | 2020-11-13T15:39:30.000Z | 2020-11-13T15:39:30.000Z | VDM/main.cpp | ALEHACKsp/VDM | 08983dc37f1ed371800d87305d07f30c6e7b3f42 | [
"MIT"
] | null | null | null | VDM/main.cpp | ALEHACKsp/VDM | 08983dc37f1ed371800d87305d07f30c6e7b3f42 | [
"MIT"
] | 1 | 2021-07-03T03:49:28.000Z | 2021-07-03T03:49:28.000Z | #include "vdm_ctx/vdm_ctx.h"
int __cdecl main(int argc, char** argv)
{
const auto [drv_handle, drv_key] = vdm::load_drv();
if (!drv_handle || drv_key.empty())
{
std::printf("[!] unable to load vulnerable driver...\n");
return -1;
}
vdm::vdm_ctx vdm;
const auto ntoskrnl_base =
reinterpret_cast<void*>(
util::get_module_base("ntoskrnl.exe"));
const auto ntoskrnl_memcpy =
util::get_kernel_export("ntoskrnl.exe", "memcpy");
std::printf("[+] drv_handle -> 0x%x, drv_key -> %s\n", drv_handle, drv_key.c_str());
std::printf("[+] %s physical address -> 0x%p\n", vdm::syscall_hook.first, vdm::syscall_address.load());
std::printf("[+] ntoskrnl base address -> 0x%p\n", ntoskrnl_base);
std::printf("[+] ntoskrnl memcpy address -> 0x%p\n", ntoskrnl_memcpy);
short mz_bytes = 0;
vdm.syscall<decltype(&memcpy)>(
ntoskrnl_memcpy,
&mz_bytes,
ntoskrnl_base,
sizeof mz_bytes
);
std::printf("[+] kernel MZ -> 0x%x\n", mz_bytes);
if (!vdm::unload_drv(drv_handle, drv_key))
{
std::printf("[!] unable to unload vulnerable driver...\n");
return -1;
}
std::printf("[+] press any key to close...\n");
std::getchar();
} | 27.285714 | 104 | 0.659686 | ALEHACKsp |
fe657894b85566eb097051da062ed6111f9c687e | 1,397 | cpp | C++ | TPDPHook/main.cpp | php42/TPDPHook | f80b71069f468e38f12157c6ea73eeaf1ab13c48 | [
"MIT"
] | 1 | 2021-08-14T13:49:58.000Z | 2021-08-14T13:49:58.000Z | TPDPHook/main.cpp | php42/TPDPHook | f80b71069f468e38f12157c6ea73eeaf1ab13c48 | [
"MIT"
] | null | null | null | TPDPHook/main.cpp | php42/TPDPHook | f80b71069f468e38f12157c6ea73eeaf1ab13c48 | [
"MIT"
] | null | null | null | #include <Windows.h>
#include <filesystem>
#include <sstream>
#include "ini_parser.h"
#include "hook.h"
#include "log.h"
#include "tpdp/hook_tpdp.h"
HMODULE g_hmodule = nullptr;
static void read_config()
{
IniFile::global.read("TPDPHook.ini");
if(IniFile::global["general"]["logging"] == "debug")
log_set_level(LogLevel::debug);
else if(IniFile::global["general"]["logging"] == "info")
log_set_level(LogLevel::info);
else if(IniFile::global["general"]["logging"] == "warning")
log_set_level(LogLevel::warn);
else if(IniFile::global["general"]["logging"] == "error")
log_set_level(LogLevel::error);
else if(IniFile::global["general"]["debug"] == "true") // backwards compatibility
log_set_level(LogLevel::debug);
else
log_set_level(LogLevel::error);
}
BOOL WINAPI DllMain(HMODULE hModule, DWORD fdwReason, [[maybe_unused]] LPVOID lpvReserved)
{
switch(fdwReason)
{
case DLL_PROCESS_ATTACH:
g_hmodule = hModule;
RVA::base((uintptr_t)GetModuleHandleW(nullptr));
// global config
read_config();
if(log_get_level() >= LogLevel::debug)
{
std::wstringstream msg;
msg << std::hex << std::showbase << L"Image Base: " << RVA::base();
log_debug(msg.str());
}
tpdp_install_hooks();
FlushInstructionCache(GetModuleHandleW(nullptr), nullptr, 0); // just in case
break;
case DLL_PROCESS_DETACH:
// ...
break;
default:
break;
}
return TRUE;
}
| 23.283333 | 90 | 0.691482 | php42 |
fe68d5c17ff590129a4cb082f65fc0dad860c1be | 8,769 | hh | C++ | EnergyPlus/OutsideEnergySources.hh | yurigabrich/EnergyPlusShadow | 396ca83aa82b842e6b177ba35c91b3f481dfbbf9 | [
"BSD-3-Clause"
] | null | null | null | EnergyPlus/OutsideEnergySources.hh | yurigabrich/EnergyPlusShadow | 396ca83aa82b842e6b177ba35c91b3f481dfbbf9 | [
"BSD-3-Clause"
] | 1 | 2020-07-08T13:32:09.000Z | 2020-07-08T13:32:09.000Z | EnergyPlus/OutsideEnergySources.hh | yurigabrich/EnergyPlusShadow | 396ca83aa82b842e6b177ba35c91b3f481dfbbf9 | [
"BSD-3-Clause"
] | null | null | null | // EnergyPlus, Copyright (c) 1996-2018, The Board of Trustees of the University of Illinois,
// The Regents of the University of California, through Lawrence Berkeley National Laboratory
// (subject to receipt of any required approvals from the U.S. Dept. of Energy), Oak Ridge
// National Laboratory, managed by UT-Battelle, Alliance for Sustainable Energy, LLC, and other
// contributors. All rights reserved.
//
// NOTICE: This Software was developed under funding from the U.S. Department of Energy and the
// U.S. Government consequently retains certain rights. As such, the U.S. Government has been
// granted for itself and others acting on its behalf a paid-up, nonexclusive, irrevocable,
// worldwide license in the Software to reproduce, distribute copies to the public, prepare
// derivative works, and perform publicly and display publicly, and to permit others to do so.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// (1) Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// (3) Neither the name of the University of California, Lawrence Berkeley National Laboratory,
// the University of Illinois, U.S. Dept. of Energy nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// (4) Use of EnergyPlus(TM) Name. If Licensee (i) distributes the software in stand-alone form
// without changes from the version obtained under this License, or (ii) Licensee makes a
// reference solely to the software portion of its product, Licensee must refer to the
// software as "EnergyPlus version X" software, where "X" is the version number Licensee
// obtained under this License and may not use a different name for the software. Except as
// specifically required in this Section (4), Licensee shall not use in a company name, a
// product name, in advertising, publicity, or other promotional activities any name, trade
// name, trademark, logo, or other designation of "EnergyPlus", "E+", "e+" or confusingly
// similar designation, without the U.S. Department of Energy's prior written consent.
//
// 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.
#ifndef OutsideEnergySources_hh_INCLUDED
#define OutsideEnergySources_hh_INCLUDED
// ObjexxFCL Headers
#include <ObjexxFCL/Array1D.hh>
// EnergyPlus Headers
#include <DataGlobals.hh>
#include <EnergyPlus.hh>
namespace EnergyPlus {
namespace OutsideEnergySources {
// Using/Aliasing
// Data
// MODULE PARAMETER DEFINITIONS
extern int const EnergyType_DistrictHeating;
extern int const EnergyType_DistrictCooling;
// DERIVED TYPE DEFINITIONS
// MODULE VARIABLE DECLARATIONS:
extern int NumDistrictUnits;
// SUBROUTINE SPECIFICATIONS FOR MODULE OutsideEnergySources
// Types
struct OutsideEnergySourceSpecs
{
// Members
std::string PlantLoopID; // main plant loop ID
std::string SecndryLoopID; // secondary chiller loop (cond loop) ID
std::string ScheduleID; // equipment availability schedule
std::string Name; // user identifier
Real64 NomCap; // design nominal capacity of district service
bool NomCapWasAutoSized; // ture if Nominal Capacity was autosize on input
int CapFractionSchedNum; // capacity modifier schedule number
int InletNodeNum; // Node number on the inlet side of the plant
int OutletNodeNum; // Node number on the inlet side of the plant
Real64 EnergyTransfer; // cooling energy provided in time step
Real64 EnergyRate; // cooling power
int EnergyType; // flag for district heating OR cooling
int MassFlowReSimIndex;
// loop topology variables
int LoopNum;
int LoopSideNum;
int BranchNum;
int CompNum;
// flags
bool OneTimeInitFlag;
bool BeginEnvrnInitFlag;
bool CheckEquipName;
// Default Constructor
OutsideEnergySourceSpecs()
: NomCap(0.0), NomCapWasAutoSized(false), CapFractionSchedNum(0), InletNodeNum(0), OutletNodeNum(0), EnergyTransfer(0.0), EnergyRate(0.0),
EnergyType(0), MassFlowReSimIndex(0), LoopNum(0), LoopSideNum(0), BranchNum(0), CompNum(0), OneTimeInitFlag(true),
BeginEnvrnInitFlag(true), CheckEquipName(true)
{
}
};
struct ReportVars
{
// Members
Real64 MassFlowRate;
Real64 InletTemp;
Real64 OutletTemp;
Real64 EnergyTransfer;
// Default Constructor
ReportVars() : MassFlowRate(0.0), InletTemp(0.0), OutletTemp(0.0), EnergyTransfer(0.0)
{
}
};
// Object Data
extern Array1D<OutsideEnergySourceSpecs> EnergySource;
extern Array1D<ReportVars> EnergySourceReport;
// Functions
void clear_state();
void SimOutsideEnergy(std::string const &EnergyType,
std::string const &EquipName,
int const EquipFlowCtrl, // Flow control mode for the equipment
int &CompIndex,
bool const RunFlag,
bool const InitLoopEquip,
Real64 &MyLoad,
Real64 &MaxCap,
Real64 &MinCap,
Real64 &OptCap,
bool const FirstHVACIteration);
// End OutsideEnergySources Module Driver Subroutines
//******************************************************************************
// Beginning of OutsideEnergySources Module Get Input subroutines
//******************************************************************************
void GetOutsideEnergySourcesInput();
// End of Get Input subroutines for the OutsideEnergySources Module
//******************************************************************************
// Beginning Initialization Section of the OutsideEnergySources Module
//******************************************************************************
void InitSimVars(int const EnergySourceNum, // Which item being initialized
Real64 &MassFlowRate,
Real64 &InletTemp,
Real64 &OutletTemp,
Real64 const MyLoad);
// End Initialization Section of the OutsideEnergySources Module
//******************************************************************************
// Beginning of OutsideEnergySources Module Utility Subroutines
// *****************************************************************************
void SizeDistrictEnergy(int const EnergySourceNum);
void SimDistrictEnergy(
bool const RunFlag, int const DistrictEqNum, Real64 &MyLoad, Real64 const MassFlowRate, Real64 const InletTemp, Real64 &OutletTemp);
// End of OutsideEnergySources Module Utility Subroutines
// *****************************************************************************
// Beginning of Record Keeping subroutines for the OutsideEnergySources Module
// *****************************************************************************
void UpdateRecords(Real64 const MyLoad, int const EqNum, Real64 const MassFlowRate, Real64 const OutletTemp);
// End of Record Keeping subroutines for the OutsideEnergySources Module
// *****************************************************************************
} // namespace OutsideEnergySources
} // namespace EnergyPlus
#endif
| 45.435233 | 150 | 0.63485 | yurigabrich |
fe6b398caa0a823511d6e7302cce6522173479b0 | 8,875 | cpp | C++ | sources/libcpp83gts_callback_and_action/iipg_scan.cpp | Savraska2/GTS | 78c8b4d634f1379eb3e33642716717f53bf7e1ad | [
"BSD-3-Clause"
] | 61 | 2016-03-26T03:04:43.000Z | 2021-09-17T02:11:18.000Z | sources/libcpp83gts_callback_and_action/iipg_scan.cpp | sahwar/GTS | b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd | [
"BSD-3-Clause"
] | 92 | 2016-04-10T23:40:22.000Z | 2022-03-11T21:49:12.000Z | sources/libcpp83gts_callback_and_action/iipg_scan.cpp | sahwar/GTS | b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd | [
"BSD-3-Clause"
] | 18 | 2016-03-26T11:19:14.000Z | 2021-08-07T00:26:02.000Z | #include <iostream>
#include <iomanip> // std::setprecision(-)
#include <limits> // std::numeric_limits<double>::max_digits10
#include <string>
#include "FL/fl_ask.H" // fl_alert(-)
#include "pri.h"
#include "gts_master.h"
#include "gts_gui.h"
int gts_master::iipg_scan_open_setup_unit_get_spec_( void )
{
/* すべてセンチメータ単位で処理する */
this->cl_iip_scan.i_centimeters_sw(ON);
/* TWAIN開く */
if (OK != this->cl_iip_scan.open()) {
pri_funct_err_bttvr(
"Error : this->cl_iip_scan.open() returns NG.");
return NG;
}
/* スキャナーに対して、スキャンの単位を一番始めに設定 */
if (OK != this->cl_iip_scan.setup_unit()) {
pri_funct_err_bttvr(
"Error : this->cl_iip_scan.setup_unit() returns NG.");
return NG;
}
/* スキャナーのハード情報を取って来て...
cap_get_dp_x_native_resolution()
cap_get_dp_y_native_resolution()
cap_get_dp_physical_width()
cap_get_dp_physical_height()
*/
if (OK != this->cl_iip_scan.get_physical_param()) {
pri_funct_err_bttvr(
"Error : this->cl_iip_scan.get_physical_param() returns NG.");
return NG;
}
std::cout
<< "Scanner Native Resolution\n" /* ハードウェア自体の解像度 */
<< std::setprecision(std::numeric_limits<double>::max_digits10)
<< " X=" << this->cl_iip_scan.d_x_native_resolution()
<< " Y=" << this->cl_iip_scan.d_y_native_resolution() << "\n"
<< "Scanner Physical Size\n" /* 物理的大きさ */
<< " W=" << this->cl_iip_scan.d_physical_width()
<< " H=" << this->cl_iip_scan.d_physical_height()
<< std::endl;
/* スキャナー幅と高さをユーザー指定の回転をする */
double d_maxcm_w=0 ,d_maxcm_h=0;
cl_gts_master.cl_area_and_rot90.calc_rot90_size(
cl_gts_gui.choice_rot90->value()
, cl_gts_master.cl_iip_scan.d_physical_width()
, cl_gts_master.cl_iip_scan.d_physical_height()
, &d_maxcm_w
, &d_maxcm_h
);
std::cout
<< "Scanner Physical Size Rotated\n"
<< std::setprecision(std::numeric_limits<double>::max_digits10)
<< " W=" << d_maxcm_w
<< " H=" << d_maxcm_h
<< std::endl;
/* スキャナー幅高さをユーザー指定の回転してメニューに設定 */
cl_gts_gui.valout_scanner_size_cm_w->value(d_maxcm_w);
cl_gts_gui.valout_scanner_size_cm_h->value(d_maxcm_h);
/* スキャナー型番をメニューに設定 */
cl_gts_gui.txtout_scanner_type->value(
cl_gts_master.cl_iip_scan.get_cp_machine_type()
);
return OK;
}
int gts_master::iipg_scan_action_( const bool full_area_sw )
{
/*
メニュー値からスキャナーへ渡す値を得る
*/
/* スキャン範囲を得る */
double d_cm_x=0,d_cm_y=0,d_cm_w=0,d_cm_h=0;
if (full_area_sw) {
/* スキャナーのフルサイズ */
this->cl_area_and_rot90.calc_rot90_offset_and_size(
-cl_gts_gui.choice_rot90->value()/* マイナス回転 */
, 0.0
, 0.0
, cl_gts_gui.valout_scanner_size_cm_w->value()
, cl_gts_gui.valout_scanner_size_cm_h->value()
, cl_gts_gui.valout_scanner_size_cm_w->value()
, cl_gts_gui.valout_scanner_size_cm_h->value()
, &d_cm_x
, &d_cm_y
, &d_cm_w
, &d_cm_h
);
}
else {
/* ユーザー指定サイズ */
this->cl_area_and_rot90.calc_rot90_offset_and_size(
-cl_gts_gui.choice_rot90->value()/* マイナス回転 */
, cl_gts_gui.valinp_area_offset_cm_x->value()
, cl_gts_gui.valinp_area_offset_cm_y->value()
, cl_gts_gui.valinp_area_size_cm_w->value()
, cl_gts_gui.valinp_area_size_cm_h->value()
, cl_gts_gui.valout_scanner_size_cm_w->value()
, cl_gts_gui.valout_scanner_size_cm_h->value()
, &d_cm_x
, &d_cm_y
, &d_cm_w
, &d_cm_h
);
}
std::cout
<< "TWAIN Scanner Area\n"
<< " Start X=" << d_cm_x << " Y=" << d_cm_y << "\n"
<< " Size W=" << d_cm_w << " H=" << d_cm_h
<< std::endl;
/* 左右 */
this->cl_iip_scan.d_left( d_cm_x );
this->cl_iip_scan.d_right( d_cm_x + d_cm_w );
/* 上下 */
this->cl_iip_scan.d_top( d_cm_y );
this->cl_iip_scan.d_bottom( d_cm_y + d_cm_h );
/* 解像度 */
this->cl_iip_scan.d_x_resolution(
cl_gts_gui.valinp_area_reso->value() );
this->cl_iip_scan.d_y_resolution(
cl_gts_gui.valinp_area_reso->value() );
#ifndef _WIN32
// the requested resolution may be adjusted, so update the GUI value
cl_gts_gui.valinp_area_reso->value(this->cl_iip_scan.d_x_resolution());
#endif
/* ピクセルタイプ */
switch (cl_gts_gui.choice_pixel_type->value()) {
case 0: /* bw */
this->cl_iip_scan.e_pixeltype( E_PIXELTYPE_BW );
this->cl_iip_scan.d_threshold(
cl_gts_gui.valinp_bw_threshold->value() );
break;
case 1: /* grayscale */
this->cl_iip_scan.e_pixeltype( E_PIXELTYPE_GRAYSCALE );
this->cl_iip_scan.d_brightness(
cl_gts_gui.valinp_grayscale_brightness->value() );
this->cl_iip_scan.d_contrast(
cl_gts_gui.valinp_grayscale_contrast->value() );
this->cl_iip_scan.d_gamma(
cl_gts_gui.valinp_grayscale_gamma->value() );
break;
case 2: /* rgb */
this->cl_iip_scan.e_pixeltype( E_PIXELTYPE_RGB );
this->cl_iip_scan.d_brightness(
cl_gts_gui.valinp_rgb_brightness->value() );
this->cl_iip_scan.d_contrast(
cl_gts_gui.valinp_rgb_contrast->value() );
this->cl_iip_scan.d_gamma(
cl_gts_gui.valinp_rgb_gamma->value() );
break;
}
/* 回転 */
/***this->cl_iip_scan.i_orientation(
cl_gts_gui.choice_rot90->value()
);***/
/* ...スキャナーへ送る */
if (OK != this->cl_iip_scan.setup_action()) {
pri_funct_err_bttvr(
"Error : this->cl_iip_scan.setup_action() returns NG.");
return NG;
}
/* 設定したスキャナー情報を表示 */
if (ON == this->_i_pv_sw) {
if (OK != this->cl_iip_scan.print_all()) {
pri_funct_err_bttvr(
"Error : this->cl_iip_scan.print_all() returns NG" );
return NG;
}
}
/* 画像をスキャンして読む */
const int ret = this->cl_iip_scan.read();
if (NG == ret) {
pri_funct_err_bttvr(
"Error : this->cl_iip_scan.read() returns NG.");
return NG;
}
/* ユーザー操作によるキャンセル */
if (ret == CANCEL) {
return CANCEL;
}
return OK;
}
/*---------------------------------------------------------*/
namespace {
void deactivate_scan_(void) /* scanを無効化 */
{
cl_gts_gui.menite_scan_crop->deactivate();
cl_gts_gui.menite_preview_scan->deactivate();
cl_gts_gui.menite_scan_save->deactivate();
cl_gts_gui.button_scan_crop->deactivate();
cl_gts_gui.button_preview_scan->deactivate();
cl_gts_gui.button_scan_save->deactivate();
}
void activate_scan_(void) /* scanを作動させる */
{
cl_gts_gui.menite_scan_crop->activate();
cl_gts_gui.menite_preview_scan->activate();
cl_gts_gui.menite_scan_save->activate();
cl_gts_gui.button_scan_crop->activate();
cl_gts_gui.button_preview_scan->activate();
cl_gts_gui.button_scan_save->activate();
}
}
iip_canvas *gts_master::iipg_scan(
int&return_code/* OK/NG/CANCEL*/ ,const bool full_area_sw
)
{
//deactivate_scan_();
if (OK != this->iipg_scan_open_setup_unit_get_spec_()) {
//activate_scan_();
return NULL;
}
return_code = this->iipg_scan_action_( full_area_sw );
if (return_code == NG) {
pri_funct_err_bttvr(
"Error : this->iipg_scan_action_(-) returns NG.");
/* ここでエラーがおきてもclose()はやる */
std::string str("Scan Critical Error!\nSave Config and Restart!");
fl_alert(str.c_str());
}
if (OK != this->cl_iip_scan.close()) {
pri_funct_err_bttvr(
"Error : this->cl_iip_scan.close() returns NG.");
std::string str("Scan Close Critical Error!\nSave Config and Restart!");
fl_alert(str.c_str());
//activate_scan_();
return NULL;
}
//activate_scan_();
return this->cl_iip_scan.get_clp_canvas();
}
/*---------------------------------------------------------*/
int gts_master::iipg_scan_get_scanner_info_( void )
{
if (OK != this->iipg_scan_open_setup_unit_get_spec_()) {
return NG;
}
#ifndef _WIN32
// override some GUI default values from gts_gui.fl
/* sane_scan.cppでthreshold/brightness/contrastを得ている */
/* Threshold/Brightness/Contrastの初期設定をGUIに表示 */
cl_gts_gui.valinp_bw_threshold->value(
this->cl_iip_scan.d_threshold()
);
((Fl_Valuator *)cl_gts_gui.scrbar_bw_threshold)->value(
this->cl_iip_scan.d_threshold()
);
cl_gts_gui.valinp_grayscale_brightness->value(
this->cl_iip_scan.d_brightness()
);
((Fl_Valuator *)cl_gts_gui.scrbar_grayscale_brightness)->value(
this->cl_iip_scan.d_brightness()
);
cl_gts_gui.valinp_rgb_brightness->value(
this->cl_iip_scan.d_brightness()
);
((Fl_Valuator *)cl_gts_gui.scrbar_rgb_brightness)->value(
this->cl_iip_scan.d_brightness()
);
cl_gts_gui.valinp_grayscale_contrast->value(
this->cl_iip_scan.d_contrast()
);
((Fl_Valuator *)cl_gts_gui.scrbar_grayscale_contrast)->value(
this->cl_iip_scan.d_contrast()
);
cl_gts_gui.valinp_rgb_contrast->value(
this->cl_iip_scan.d_contrast()
);
((Fl_Valuator *)cl_gts_gui.scrbar_rgb_contrast)->value(
this->cl_iip_scan.d_contrast()
);
#endif
/* Area位置とサイズの初期設定をGUIに表示 */
cl_gts_gui.valinp_area_offset_cm_x->value(0.0);
cl_gts_gui.valinp_area_offset_cm_y->value(0.0);
cl_gts_gui.valinp_area_size_cm_w->value(
cl_gts_gui.valout_scanner_size_cm_w->value()
);
cl_gts_gui.valinp_area_size_cm_h->value(
cl_gts_gui.valout_scanner_size_cm_h->value()
);
this->cl_area_and_rot90.getset_x_pixel_from_x_size();
this->cl_area_and_rot90.getset_y_pixel_from_y_size();
/* TWAIN閉じる */
if (OK != this->cl_iip_scan.close()) {
pri_funct_err_bttvr(
"Error : this->cl_iip_scan.close() returns NG.");
return NG;
}
return OK;
}
| 27.057927 | 75 | 0.706704 | Savraska2 |
fe6c0b8023dd5dd12a5c4fb9b5bf842a0a83aca7 | 6,036 | cpp | C++ | src/keep_backups.cpp | bluedevils23/slumbot2019 | a1b65b84c89ab2eff9e2e0c16cedcfcbd479dffd | [
"MIT"
] | 80 | 2019-03-28T02:57:51.000Z | 2022-03-17T05:41:48.000Z | src/keep_backups.cpp | bluedevils23/slumbot2019 | a1b65b84c89ab2eff9e2e0c16cedcfcbd479dffd | [
"MIT"
] | 19 | 2019-06-11T08:01:06.000Z | 2022-01-28T23:13:49.000Z | src/keep_backups.cpp | bluedevils23/slumbot2019 | a1b65b84c89ab2eff9e2e0c16cedcfcbd479dffd | [
"MIT"
] | 28 | 2019-07-18T01:36:35.000Z | 2021-12-26T14:37:10.000Z | #include <stdio.h>
#include <stdlib.h>
#include <string.h> // strcpy()
#include <sys/wait.h> // waitpid()
#include <unistd.h> // vfork
#include <string>
#include <vector>
#include "io.h"
#include "split.h"
using std::string;
using std::vector;
// 2019-06-13 16:31:28 1187056 regrets.x.0.0.0.0.p0.i
// 2019-06-13 16:31:28 1187732 regrets.x.0.0.0.0.p1.i
// 2019-06-13 16:31:28 69054405888 regrets.x.0.0.1.0.p0.c
// 2019-06-13 16:31:28 69054405888 regrets.x.0.0.1.0.p1.c
// 2019-06-13 16:31:28 2233180000 regrets.x.0.0.2.0.p0.s
// 2019-06-13 16:31:28 2233180000 regrets.x.0.0.2.0.p1.s
// 2019-06-13 16:31:28 3839620000 regrets.x.0.0.3.0.p0.s
// 2019-06-13 16:32:34 3839620000 regrets.x.0.0.3.0.p1.s
// 2019-06-13 16:32:34 1187056 sumprobs.x.0.0.0.0.p0.i
// 2019-06-13 16:32:34 1187732 sumprobs.x.0.0.0.0.p1.i
// 2019-06-13 16:32:34 276217623552 sumprobs.x.0.0.1.0.p0.i
// 2019-06-13 16:33:39 276217623552 sumprobs.x.0.0.1.0.p1.i
// 2019-06-13 16:35:53 4466360000 sumprobs.x.0.0.2.0.p0.i
// 2019-06-13 16:40:13 4466360000 sumprobs.x.0.0.2.0.p1.i
// 2019-06-13 16:44:30 7679240000 sumprobs.x.0.0.3.0.p0.i
// 2019-06-13 16:51:52 7679240000 sumprobs.x.0.0.3.0.p1.i
const char *kDir = "/data/poker2019/cfr/holdem.2.b.13.4.3.big4sym.tcfrqcss";
static long long int TargetSize(int st, bool regrets, int p) {
if (st == 0) {
// Preflop regrets and sumprobs are the same size, but P0 and P1 differ
if (p == 0) {
return 1187056LL;
} else {
return 1187732LL;
}
} else if (st == 1) {
if (regrets) {
return 69054405888LL;
} else {
return 276217623552LL;
}
} else if (st == 2) {
if (regrets) {
return 2233180000LL;
} else {
return 4466360000LL;
}
} else {
if (regrets) {
return 3839620000LL;
} else {
return 7679240000LL;
}
}
}
static bool Ready(int it) {
char buf[500];
for (int st = 0; st <= 3; ++st) {
for (int r = 0; r <= 1; ++r) {
for (int p = 0; p <= 1; ++p) {
if (r) {
sprintf(buf, "%s/regrets.x.0.0.%i.%i.p%i.%c", kDir, st, it, p,
st == 1 ? 'c' : (st >= 2 ? 's' : 'i'));
} else {
sprintf(buf, "%s/sumprobs.x.0.0.%i.%i.p%i.i", kDir, st, it, p);
}
if (! FileExists(buf)) return false;
long long int target_size = TargetSize(st, r, p);
if (FileSize(buf) != target_size) return false;
}
}
}
return true;
}
// Uses vfork() and execvp() to fork off a child process to copy the files to S3.
// Unfortunate that we have to hard code the location of aws (/usr/bin).
static void Backup(void) {
int pid = vfork();
if (pid == 0) {
// Child
char const *binary = "/usr/bin/aws";
char const * newargv[] = { binary, "s3", "cp", kDir, "s3://slumbot2019cfr", "--recursive",
"--quiet", NULL };
execvp(binary, (char * const *)newargv);
fprintf(stderr, "Failed to execvp aws s3 cp process\n");
exit(-1);
}
int return_status;
waitpid(pid, &return_status, 0);
if (return_status != 0) {
fprintf(stderr, "aws s3 cp failed\n");
exit(-1);
}
}
static bool BackupDone(int target_it) {
char cmd[500], output[500];
strcpy(cmd, "/usr/bin/aws s3 ls s3://slumbot2019cfr");
FILE *fp = popen(cmd, "r");
vector<string> lines;
while (fgets(output, sizeof(output), fp)) {
string line = output;
lines.push_back(line);
}
int num_lines = lines.size();
int num_done = 0;
vector<string> comps1, comps2;
for (int i = 0; i < num_lines; ++i) {
const string &line = lines[i];
Split(line.c_str(), ' ', false, &comps1);
if (comps1.size() != 4) {
fprintf(stderr, "Not 4 components in %s\n", line.c_str());
exit(-1);
}
const string &sz_str = comps1[2];
const string &fn = comps1[3];
long long int file_size;
if (sscanf(sz_str.c_str(), "%lli", &file_size) != 1) {
fprintf(stderr, "Couldn't parse file size: %s\n", line.c_str());
exit(-1);
}
Split(fn.c_str(), '.', false, &comps2);
if (comps2.size() != 8) {
fprintf(stderr, "Not 8 components in file name in %s\n", line.c_str());
exit(-1);
}
int it, st, p;
bool regrets;
if (sscanf(comps2[5].c_str(), "%i", &it) != 1) {
fprintf(stderr, "Couldn't parse iteration from file name in %s\n", line.c_str());
exit(-1);
}
if (target_it == it) {
if (sscanf(comps2[4].c_str(), "%i", &st) != 1) {
fprintf(stderr, "Couldn't parse street from file name in %s\n", line.c_str());
exit(-1);
}
if (comps2[0] == "regrets") {
regrets = true;
} else if (comps2[0] == "sumprobs") {
regrets = false;
} else {
fprintf(stderr, "Not regrets or sumprobs?!? %s\n", line.c_str());
exit(-1);
}
if (comps2[6] == "p0") {
p = 0;
} else if (comps2[6] == "p1") {
p = 1;
} else {
fprintf(stderr, "Not p0 or p1?!? %s\n", line.c_str());
exit(-1);
}
long long int target_size = TargetSize(st, regrets, p);
if (target_size == file_size) ++num_done;
}
}
return num_done == 16;
}
static void EmptyDirectory(void) {
int pid = vfork();
if (pid == 0) {
// Child
// We delete the directory as well as the contents. run_tcfr will recreate it when it
// checkpoints the next iteration.
char const *binary = "/usr/bin/rm";
char const * newargv[] = { binary, "-rf", kDir, NULL };
execvp(binary, (char * const *)newargv);
fprintf(stderr, "Failed to execvp rm -rf process\n");
exit(-1);
}
int return_status;
waitpid(pid, &return_status, 0);
if (return_status != 0) {
fprintf(stderr, "rm -rf failed\n");
exit(-1);
}
}
static void Usage(const char *prog_name) {
fprintf(stderr, "USAGE: %s <it>\n", prog_name);
exit(-1);
}
int main(int argc, char *argv[]) {
if (argc != 2) Usage(argv[0]);
int it;
if (sscanf(argv[1], "%i", &it) != 1) Usage(argv[0]);
while (true) {
if (Ready(it)) {
Backup();
while (true) {
if (BackupDone(it)) {
EmptyDirectory();
++it;
break;
} else {
sleep(60);
}
}
} else {
sleep(60);
}
}
}
| 27.944444 | 94 | 0.578694 | bluedevils23 |
fe6f096ec60c53d73625682edbd30debb3663395 | 2,492 | cpp | C++ | ftsoftds_vc6/ch7/prg7_3.cpp | guarana-x/fwg | 5a56dcb4caee5dca6744fca8e21b987b07106513 | [
"MIT"
] | null | null | null | ftsoftds_vc6/ch7/prg7_3.cpp | guarana-x/fwg | 5a56dcb4caee5dca6744fca8e21b987b07106513 | [
"MIT"
] | null | null | null | ftsoftds_vc6/ch7/prg7_3.cpp | guarana-x/fwg | 5a56dcb4caee5dca6744fca8e21b987b07106513 | [
"MIT"
] | null | null | null | // File: prg7_3.cpp
// the program inputs an infix expression until the user enters an empty
// string. it uses the class infix2Postfix to convert the infix expression
// to postfix, handling errors that may occur by catching the corresponding
// expressionError exception. if there is no error, the postfix string is
// correctly formatted. use the class postfixEval to evaluate the postfix
// expression and output the result. this is the value of the original
// infix expression
#include <iostream>
#include <string>
// if Microsoft VC++, compensate for a getline() bug in <string>
#ifdef _MSC_VER
#include "d_util.h"
#endif _MSC_VER
#include "d_inftop.h" // infix2Postfix class
#include "d_rpn.h" // postfixEval class
using namespace std;
int main()
{
// use iexp for infix to postfix conversion
infix2Postfix iexp;
// infix expression input and postfix expression output
string infixExp, postfixExp;
// use pexp to evaluate postfix expressions
postfixEval pexp;
// input and evaluate infix expressions until the
// user enters an empty string
// get the first expression
cout << "Enter an infix expression: ";
getline(cin, infixExp);
while (infixExp != "")
{
// an exception may occur. enclose the conversion
// to postfix and the output of the expression
// value in a try block
try
{
// convert to postfix
iexp.setInfixExp(infixExp);
postfixExp = iexp.postfix();
// output the postfix expression
cout << "The postfix form is " << postfixExp
<< endl;
// use pexp to evaluate the postfix expression
pexp.setPostfixExp(postfixExp);
cout << "Value of the expression = "
<< pexp.evaluate() << endl << endl;
}
// catch an exception and output the error
catch (const expressionError& ee)
{
cout << ee.what() << endl << endl;
}
// input another expression
cout << "Enter an infix expression: ";
getline(cin, infixExp);
}
return 0;
}
/*
Run:
Enter an infix expression: 3 ^ 2 ^ (1+2)
The postfix form is 3 2 1 2 + ^ ^
Value of the expression = 6561
Enter an infix expression: 3 * (4 - 2 ^ 5) + 6
The postfix form is 3 4 2 5 ^ - * 6 +
Value of the expression = -78
Enter an infix expression: (7 + 8*7
infix2Postfix: Missing ')'
Enter an infix expression: (9 + 7) 4
infix2Postfix: Operator expected
Enter an infix expression: 2*4*8/
infix2Postfix: Operand expected
Enter an infix expression:
*/
| 25.958333 | 76 | 0.67496 | guarana-x |
fe6f5ce548265109884ba8bf7d1513ea1da92abb | 57 | cpp | C++ | CompetitonTemplate_23:53:33/output/main.cpp | ehami/VexCodingStudioExtractor | 29bfe9091f4e6ac650bd3e7339739d70a4d9f0d0 | [
"MIT"
] | null | null | null | CompetitonTemplate_23:53:33/output/main.cpp | ehami/VexCodingStudioExtractor | 29bfe9091f4e6ac650bd3e7339739d70a4d9f0d0 | [
"MIT"
] | null | null | null | CompetitonTemplate_23:53:33/output/main.cpp | ehami/VexCodingStudioExtractor | 29bfe9091f4e6ac650bd3e7339739d70a4d9f0d0 | [
"MIT"
] | null | null | null | #include "robot-config.h"
int main() {
} | 9.5 | 25 | 0.45614 | ehami |
fe73180f8a4e5e330d118332ed30c097b6474aa9 | 5,208 | cpp | C++ | src/frontend/combine.cpp | Jelinek-J/INSPiRE | 425c6fba18170b34001b1f00b3f827b83c80ce68 | [
"Apache-2.0"
] | 2 | 2020-10-20T11:29:11.000Z | 2022-03-24T09:08:30.000Z | src/frontend/combine.cpp | Jelinek-J/INSPiRE | 425c6fba18170b34001b1f00b3f827b83c80ce68 | [
"Apache-2.0"
] | 1 | 2018-11-23T11:02:11.000Z | 2018-11-23T11:02:11.000Z | src/frontend/combine.cpp | Jelinek-J/INSPiRE | 425c6fba18170b34001b1f00b3f827b83c80ce68 | [
"Apache-2.0"
] | 1 | 2021-06-22T08:53:23.000Z | 2021-06-22T08:53:23.000Z | // mine.cpp : Defines the entry point for the console application.
//
#include "../backend/combine.h"
#include "../common/exception.h"
#include "../common/string.h"
#include <iostream>
#include <fstream>
//#define TESTING
void help() {
std::cout << "Help\n\n";
std::cout << "Combine multiple optimization files into one file\n\n";
std::cout << "Usage:\t[-m] [-o] <OUTPUT-FILE> -t (<HEADER> <INPUT-FILE>)+\n";
std::cout << " \t[-m] [-o] <OUTPUT-FILE> [-p<PREFIX>] [-s<SUFFIX>] [-i] <INPUT-FILE>+\n";
std::cout << " \t-h\n\n";
std::cout << "Options:\t-o <OUTPUT-FILE> \tWhere to store the output file. '-o' is mandatory only in the case <OUTPUT-FILE> starts with minus sign.\n";
std::cout << " \t-i <INPUT-FILE> \tInput file that should be added to the output file. '-i' is mandatory only in the case the first <INPUT-FILE> starts with minus sign and implicit headers.\n";
std::cout << " \t-m \tUse median to combine values from input files. (Defaultly, the mean value is used.)\n";
std::cout << " \t-t \tA flag indicating that each input file will be preceded by a header used in the output file.\n";
std::cout << " \t<HEADER> \tHeader that shoul be used in the output file to represen the following input file.\n";
std::cout << " \t-p<PREFIX> \tPrefix <PREFIX> should be removed from input file names to get corresponding headers for input files.\n";
std::cout << " \t-s<SUFFIX> \tSuffix <SUFFIX> should be removed from input file names to get corresponding headers for input files.\n";
std::cout << " \t-h \tShow informations about the program\n\n";
}
int main(int argc, const char** argv) {
#ifdef TESTING
// Errors log for testing reasons
std::ofstream log("C:\\Inspire\\error-optimize.log");
argc = 7;
const char* args[] = {argv[0],
"C:\\Inspire\\combine\\pure-sasapercentil8.sed",
"-t",
"test",
"C:\\Inspire\\combine\\2LTD.B-pure-sasapercentil8.sed",
"pokus",
"C:\\Inspire\\combine\\3VNI.D-pure-sasapercentil8.sed"
};
argv = args;
#endif // TESTING
if (argc < 4) {
if (argc > 1 && strcmp(argv[1], "-h")) {
std::cerr << "Not enough arguments" << std::endl;
}
help();
return 0;
}
inspire::backend::MutuallyOptimizer* optimizer;
try {
size_t argv_index = 1;
bool median = false;
if (strcmp("-m", argv[argv_index]) == 0) {
median = true;
++argv_index;
}
if (strcmp("-o", argv[argv_index]) == 0) {
++argv_index;
}
if (median) {
optimizer = new inspire::backend::MedianMutuallyOptimize(argv[argv_index]);
} else {
optimizer = new inspire::backend::AverageMutuallyOptimize(argv[argv_index]);
}
if (strcmp("-t", argv[++argv_index])) {
std::string prefix;
if (common::string::starts_with(argv[argv_index], "-p")) {
prefix = std::string(argv[argv_index]).substr(2);
++argv_index;
}
std::string suffix;
if (common::string::starts_with(argv[argv_index], "-s")) {
suffix = std::string(argv[argv_index]).substr(2);
++argv_index;
}
if (strcmp("-i", argv[argv_index]) == 0) {
++argv_index;
}
for ( ; argv_index < argc; ++argv_index) {
std::string header = argv[argv_index];
if (common::string::starts_with(header, prefix)) {
header = header.substr(prefix.size());
} else {
throw common::exception::TitledException("Filename '" + std::string(argv[argv_index]) + "' does not start with the given prefix '" + prefix + "'.");
}
if (common::string::ends_with(header, suffix)) {
header = header.substr(0, header.size() - suffix.size());
} else {
throw common::exception::TitledException("Filename '" + std::string(argv[argv_index]) + "' does not end with the given suffix '" + suffix + "'.");
}
optimizer->add_input(header, argv[argv_index]);
}
} else {
++argv_index;
if ((argc-argv_index)%2) {
throw common::exception::TitledException("Invalid pairing of headers and input files: even number of corresponding arguments expected.");
}
while (argv_index < argc) {
optimizer->add_input(argv[argv_index], argv[argv_index+1]);
argv_index += 2;
}
}
optimizer->combine();
} catch (const common::exception::TitledException& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
return 1;
#ifdef TESTING
log << "ERROR: " << e.what() << std::endl;
#endif // TESTING
} catch (const std::exception& e) {
std::cerr << "ERROR: " << e.what() << std::endl;
help();
return 2;
#ifdef TESTING
log << "ERROR: " << e.what() << std::endl;
#endif // TESTING
} catch (...) {
std::cerr << "UNKNOWN ERROR" << std::endl;
help();
return 3;
#ifdef TESTING
log << "UNKNOWN ERROR" << std::endl;
#endif // TESTING
}
if (optimizer != nullptr) {
delete optimizer;
}
return 0;
}
| 37.73913 | 206 | 0.572389 | Jelinek-J |
fe7845388df6648a69594ee993e70fd76eead9e4 | 408 | cpp | C++ | subseque.cpp | sagar-sam/codechef-solutions | ea414d17435f0cfbc84b0c6b172ead0b22f32a23 | [
"MIT"
] | null | null | null | subseque.cpp | sagar-sam/codechef-solutions | ea414d17435f0cfbc84b0c6b172ead0b22f32a23 | [
"MIT"
] | null | null | null | subseque.cpp | sagar-sam/codechef-solutions | ea414d17435f0cfbc84b0c6b172ead0b22f32a23 | [
"MIT"
] | null | null | null | #include <iostream>
#include <map>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
string s;
cin>>s;
map<char,int> mp;
for(int i=0;i<s.length();i++)
{
mp[s[i]]++;
}
int flag=0;
for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++)
{
if(it->second>=2)
{
flag=1;
break;
}
}
if(flag==0)
printf("no\n");
else printf("yes\n");
}
} | 12.75 | 62 | 0.509804 | sagar-sam |
fe7f859214ff95ecc923fbccbd0f185a3176b8be | 8,760 | cpp | C++ | libs/locale/src/icu/time_zone.cpp | lijgame/boost | ec2214a19cdddd1048058321a8105dd0231dac47 | [
"BSL-1.0"
] | 198 | 2015-01-13T05:47:18.000Z | 2022-03-09T04:46:46.000Z | libs/boost/libs/locale/src/icu/time_zone.cpp | flingone/frameworks_base_cmds_remoted | 4509d9f0468137ed7fd8d100179160d167e7d943 | [
"Apache-2.0"
] | 9 | 2015-01-28T16:33:19.000Z | 2020-04-12T23:03:28.000Z | libs/boost/libs/locale/src/icu/time_zone.cpp | flingone/frameworks_base_cmds_remoted | 4509d9f0468137ed7fd8d100179160d167e7d943 | [
"Apache-2.0"
] | 139 | 2015-01-15T20:09:31.000Z | 2022-01-31T15:21:16.000Z | //
// Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#define BOOST_LOCALE_SOURCE
#include "time_zone.hpp"
//
// Bug - when ICU tries to find a file that is equivalent to /etc/localtime it finds /usr/share/zoneinfo/localtime
// that is just a symbolic link to /etc/localtime.
//
// It started in 4.0 and was fixed in version 4.6, also the fix was backported to the 4.4 branch so it should be
// available from 4.4.3... So we test if the workaround is required
//
// It is also relevant only for Linux, BSD and Apple (as I see in ICU code)
//
#if U_ICU_VERSION_MAJOR_NUM == 4 && (U_ICU_VERSION_MINOR_NUM * 100 + U_ICU_VERSION_PATCHLEVEL_NUM) <= 402
# if defined(__linux) || defined(__FreeBSD__) || defined(__APPLE__)
# define BOOST_LOCALE_WORKAROUND_ICU_BUG
# endif
#endif
#ifdef BOOST_LOCALE_WORKAROUND_ICU_BUG
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>
#include <pthread.h>
#include <string.h>
#include <memory>
#endif
namespace boost {
namespace locale {
namespace impl_icu {
#ifndef BOOST_LOCALE_WORKAROUND_ICU_BUG
// This is normal behavior
icu::TimeZone *get_time_zone(std::string const &time_zone)
{
if(time_zone.empty()) {
return icu::TimeZone::createDefault();
}
else {
return icu::TimeZone::createTimeZone(time_zone.c_str());
}
}
#else
//
// This is a workaround for an ICU timezone detection bug.
// It is \b very ICU specific and should not be used
// in general. It is also designed to work only on
// specific patforms: Linux, BSD and Apple, where this bug may actually
// occur
//
namespace {
// Under BSD, Linux and Mac OS X dirent has normal size
// so no issues with readdir_r
class directory {
public:
directory(char const *name) : d(0),read_result(0)
{
d=opendir(name);
if(!d)
return;
}
~directory()
{
if(d)
closedir(d);
}
bool is_open()
{
return d;
}
char const *next()
{
if(d && readdir_r(d,&de,&read_result)==0 && read_result!=0)
return de.d_name;
return 0;
}
private:
DIR *d;
struct dirent de;
struct dirent *read_result;
};
bool files_equal(std::string const &left,std::string const &right)
{
char l[256],r[256];
std::ifstream ls(left.c_str());
if(!ls)
return false;
std::ifstream rs(right.c_str());
if(!rs)
return false;
do {
ls.read(l,sizeof(l));
rs.read(r,sizeof(r));
size_t n;
if((n=ls.gcount())!=size_t(rs.gcount()))
return false;
if(memcmp(l,r,n)!=0)
return false;
}while(!ls.eof() || !rs.eof());
if(bool(ls.eof())!=bool(rs.eof()))
return false;
return true;
}
std::string find_file_in(std::string const &ref,size_t size,std::string const &dir)
{
directory d(dir.c_str());
if(!d.is_open())
return std::string();
char const *name=0;
while((name=d.next())!=0) {
std::string file_name = name;
if( file_name == "."
|| file_name ==".."
|| file_name=="posixrules"
|| file_name=="localtime")
{
continue;
}
struct stat st;
std::string path = dir+"/"+file_name;
if(stat(path.c_str(),&st)==0) {
if(S_ISDIR(st.st_mode)) {
std::string res = find_file_in(ref,size,path);
if(!res.empty())
return file_name + "/" + res;
}
else {
if(size_t(st.st_size) == size && files_equal(path,ref)) {
return file_name;
}
}
}
}
return std::string();
}
// This actually emulates ICU's search
// algorithm... just it ignores localtime
std::string detect_correct_time_zone()
{
char const *tz_dir = "/usr/share/zoneinfo";
char const *tz_file = "/etc/localtime";
struct stat st;
if(::stat(tz_file,&st)!=0)
return std::string();
size_t size = st.st_size;
std::string r = find_file_in(tz_file,size,tz_dir);
if(r.empty())
return r;
if(r.compare(0,6,"posix/")==0 || r.compare(0,6,"right/",6)==0)
return r.substr(6);
return r;
}
//
// Using pthread as:
// - This bug is relevant for only Linux, BSD, Mac OS X and
// pthreads are native threading API
// - The dependency on boost.thread may be removed when using
// more recent ICU versions (so TLS would not be needed)
//
// This the dependency on Boost.Thread is eliminated
//
pthread_once_t init_tz = PTHREAD_ONCE_INIT;
std::string default_time_zone_name;
extern "C" {
static void init_tz_proc()
{
try {
default_time_zone_name = detect_correct_time_zone();
}
catch(...){}
}
}
std::string get_time_zone_name()
{
pthread_once(&init_tz,init_tz_proc);
return default_time_zone_name;
}
} // namespace
icu::TimeZone *get_time_zone(std::string const &time_zone)
{
if(!time_zone.empty()) {
return icu::TimeZone::createTimeZone(time_zone.c_str());
}
std::auto_ptr<icu::TimeZone> tz(icu::TimeZone::createDefault());
icu::UnicodeString id;
tz->getID(id);
// Check if there is a bug?
if(id != icu::UnicodeString("localtime"))
return tz.release();
// Now let's deal with the bug and run the fixed
// search loop as that of ICU
std::string real_id = get_time_zone_name();
if(real_id.empty()) {
// if we failed fallback to ICU's time zone
return tz.release();
}
return icu::TimeZone::createTimeZone(real_id.c_str());
}
#endif // bug workaround
}
}
}
// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
| 36.806723 | 115 | 0.410502 | lijgame |
fe86a4b07c452ab0781075448b14386c7eda3cf7 | 1,007 | cpp | C++ | src/Interface/Resource/Factory/Factory.cpp | korenandr/poco_restful_webservice | 864b02fb0cd500c9c74fb2f6931c44ecd6f4d019 | [
"Apache-2.0"
] | 1 | 2021-07-01T18:45:35.000Z | 2021-07-01T18:45:35.000Z | src/Interface/Resource/Factory/Factory.cpp | korenandr/poco_restful_webservice | 864b02fb0cd500c9c74fb2f6931c44ecd6f4d019 | [
"Apache-2.0"
] | null | null | null | src/Interface/Resource/Factory/Factory.cpp | korenandr/poco_restful_webservice | 864b02fb0cd500c9c74fb2f6931c44ecd6f4d019 | [
"Apache-2.0"
] | null | null | null | #include "Interface/Resource/Factory/Factory.h"
#include "Interface/Resource/Factory/VoteFactory.h"
#include "Interface/Resource/Factory/PollFactory.h"
#include "Interface/Resource/Factory/ApplicationFactory.h"
#include "log/logger.hpp"
namespace Interface::Resource::Factory {
IFactory * Factory::createResourceFactory(std::string & index)
{
LOG_TRACE("create resource: " << index)
IFactory * factory = nullptr;
if ( index == "Interface::Resource::Factory::PollFactory" ) {
LOG_TRACE("created poll factory")
factory = new PollFactory();
}
if ( index == "Interface::Resource::Factory::PollVoteFactory" ) {
LOG_TRACE("created vote factory")
factory = new VoteFactory();
}
if ( index == "Interface::Resource::Factory::ApplicationFactory" ) {
LOG_TRACE("created application factory")
factory = new ApplicationFactory();
}
return factory;
}
}
| 26.5 | 76 | 0.630586 | korenandr |
fe8de6a5bbe81139cfa0cf451a14ce5b3e737c32 | 559 | cpp | C++ | C++/number-of-distinct-substrings-in-a-string.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/number-of-distinct-substrings-in-a-string.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/number-of-distinct-substrings-in-a-string.cpp | Priyansh2/LeetCode-Solutions | d613da1881ec2416ccbe15f20b8000e36ddf1291 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(n^2)
// Space: O(t), t is the number of trie nodes
class Solution {
public:
int countDistinct(string s) {
vector<array<int, 26>> trie(1);
for (int i = 0; i < size(s); ++i) {
int curr = 0;
for (int j = i; j < size(s); ++j) {
if (!trie[curr][s[j] - 'a']) {
trie.emplace_back();
trie[curr][s[j] - 'a'] = size(trie) - 1;
}
curr = trie[curr][s[j] - 'a'];
}
}
return size(trie) - 1;
}
};
| 26.619048 | 60 | 0.388193 | Priyansh2 |
fe914df8ab3ec9073582dfd5b3db38c6d8b32e81 | 2,654 | cc | C++ | April/20220407/practice/cow2.cc | RecklessTeikon/MyCPPJourney | 0f11b810703f487cdbaf7a19e1ed6f999340a66a | [
"MIT"
] | 1 | 2022-03-28T15:59:22.000Z | 2022-03-28T15:59:22.000Z | April/20220407/practice/cow2.cc | RecklessTeikon/MyCPPJourney | 0f11b810703f487cdbaf7a19e1ed6f999340a66a | [
"MIT"
] | null | null | null | April/20220407/practice/cow2.cc | RecklessTeikon/MyCPPJourney | 0f11b810703f487cdbaf7a19e1ed6f999340a66a | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstring>
using std::cout;
using std::endl;
class Mystring
{
public:
Mystring()
:_ptr(new char[1 + 4])
,_charproxy(this, 0)
{
_ptr += 4;
getRefCount() = 1;
*_ptr = '\0';
}
Mystring(const char *str)
:_ptr(new char[strlen(str + 1) + 4])
,_charproxy(this, 0)
{
_ptr += 4;
getRefCount() = 1;
strcpy(_ptr, str);
}
Mystring(const Mystring &str)
:_ptr(str._ptr)
,_charproxy(this, 0)
{
++getRefCount();
}
Mystring &operator=(const Mystring &str)
{
release();
_ptr = str._ptr;
++getRefCount();
return *this;
}
void release()
{
--getRefCount();
if(!getRefCount())
{
delete [] (_ptr - 4);
}
_ptr = nullptr;
}
~Mystring()
{
release();
}
int &getRefCount()
{
return *(reinterpret_cast<int*>(_ptr - 4));
}
char *&getstr()
{
return _ptr;
}
class CharProxy
{
public:
CharProxy(Mystring *str, unsigned idx)
:_str(str)
,_idx(idx)
{}
unsigned &getidx()
{
return _idx;
}
CharProxy &operator=(const char x)
{
if(_str->getstr()[_idx] != x)
{
char *temp = new char[strlen(_str->getstr() + 1 + 4)];
strcpy(temp + 4, _str->getstr());
*(temp + 4 + _idx) = x;
_str->release();
_str->getstr() = temp + 4;
_str->getRefCount() = 1;
}
return *this;
}
friend std::ostream &operator<<(std::ostream &os, const Mystring::CharProxy &charproxy);
private:
Mystring *_str;
unsigned _idx;
};
CharProxy &operator[](unsigned idx)
{
_charproxy.getidx() = idx;
return _charproxy;
}
friend std::ostream &operator<<(std::ostream &os, const Mystring &str);
private:
char *_ptr;
CharProxy _charproxy;
};
std::ostream &operator<<(std::ostream &os, const Mystring &str)
{
os << str._ptr;
return os;
}
std::ostream &operator<<(std::ostream &os, const Mystring::CharProxy &charproxy)
{
os << (charproxy._str->getstr())[charproxy._idx];
return os;
}
void test()
{
Mystring s1("hello");
Mystring s2;
Mystring s3("world");
Mystring s4("hello world");
s2 = s1;
s1[1] = 'o';
//cout << s1 << endl;
cout << s1.getRefCount() << endl;
cout << s2.getRefCount() << endl;
}
int main()
{
test();
return 0;
} | 21.063492 | 96 | 0.487189 | RecklessTeikon |
fe9153155f5c4a7d0d8290c0d5d2c3b3792d97f9 | 1,176 | cpp | C++ | OJ/LeetCode/leetcode/problems/1299.cpp | ONGOING-Z/DataStructure | 9099393d1c7dfabc3e2939586ea6d1d254631eb2 | [
"MIT"
] | null | null | null | OJ/LeetCode/leetcode/problems/1299.cpp | ONGOING-Z/DataStructure | 9099393d1c7dfabc3e2939586ea6d1d254631eb2 | [
"MIT"
] | 2 | 2021-10-31T10:05:45.000Z | 2022-02-12T15:17:53.000Z | OJ/LeetCode/leetcode/problems/1299.cpp | ONGOING-Z/DataStructure | 9099393d1c7dfabc3e2939586ea6d1d254631eb2 | [
"MIT"
] | null | null | null | /* 1299. Replace Elements with Greatest Element on Right Side
* Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1.
After doing so, return the array.
Example 1:
Input: arr = [17,18,5,4,6,1]
Output: [18,6,6,6,1,-1]
Constraints:
1 <= arr.length <= 10^4
1 <= arr[i] <= 10^5
*/
/* my solution */
class Solution {
public:
vector<int> replaceElements(vector<int>& arr) {
int len = arr.size();
for (int i = 0; i < len - 1; i++) {
int max = -1;
// 找出arr[i]右方最大的数
for (int j = i + 1; j < len; j++) {
if (arr[j] > max) max = arr[j];
}
arr[i] = max;
}
arr[len-1] = -1;
return arr;
}
};
/* better solution */
class Solution {
public:
vector<int> replaceElements(vector<int>& arr) {
int maxv = -1, temp;
for (int i = arr.size() - 1; i >= 0; i--) {
temp = arr[i];
arr[i] = maxv;
maxv = max(maxv, temp);
}
return arr;
}
};
/* 一些总结 */
// 1. c++ max()函数掌握
// 2. 从右向左遍历,因为总是在找右边最大的。
| 22.188679 | 155 | 0.511054 | ONGOING-Z |
fe9a41298452cc760db43faef72c4ca90c316034 | 28,314 | cpp | C++ | test/recognizer_float_tests.cpp | spavloff/conversion | bd8128487ede0d4500df5c760c6c70355ff2ed9a | [
"BSD-2-Clause"
] | null | null | null | test/recognizer_float_tests.cpp | spavloff/conversion | bd8128487ede0d4500df5c760c6c70355ff2ed9a | [
"BSD-2-Clause"
] | null | null | null | test/recognizer_float_tests.cpp | spavloff/conversion | bd8128487ede0d4500df5c760c6c70355ff2ed9a | [
"BSD-2-Clause"
] | 1 | 2020-08-14T06:21:29.000Z | 2020-08-14T06:21:29.000Z | //===--- recognizer_float_tests.cpp -----------------------------*- C++ -*-===//
//
// Copyright(c) 2016, Serge Pavlov.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and / or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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
/// Unit tests for recognition of floating strings.
///
//===----------------------------------------------------------------------===//
//------ Dependencies ----------------------------------------------------------
#include "conversion/number_recognizer.h"
#include <boost/test/unit_test.hpp>
#include <memory>
//------------------------------------------------------------------------------
using namespace conversion;
BOOST_AUTO_TEST_CASE(FloatTest5) {
NumberRecognizer<> Recog;
Recog.recognize("-1.2");
BOOST_REQUIRE(Recog.get_options() == DefaultOptions);
BOOST_REQUIRE_EQUAL(Recog.get_base(), 10);
BOOST_REQUIRE_EQUAL(Recog.size(), 4);
BOOST_REQUIRE(Recog.is_float());
BOOST_REQUIRE(!Recog.is_empty());
BOOST_REQUIRE(Recog.recognized());
BOOST_REQUIRE(Recog.success());
BOOST_REQUIRE(!Recog.failure());
BOOST_REQUIRE(!Recog.partial());
BOOST_REQUIRE(Recog.has_sign());
BOOST_REQUIRE(!Recog.has_plus());
BOOST_REQUIRE(Recog.has_minus());
BOOST_REQUIRE(!Recog.is_positive());
BOOST_REQUIRE(Recog.is_negative());
BOOST_REQUIRE(!Recog.has_exp_sign());
BOOST_REQUIRE(!Recog.has_exp_plus());
BOOST_REQUIRE(!Recog.has_exp_minus());
BOOST_REQUIRE(Recog.is_exp_positive());
BOOST_REQUIRE(!Recog.is_exp_negative());
BOOST_REQUIRE_EQUAL(Recog.get_leading_ws(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_leading_zeros(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_trailing_zeros(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_trailing_ws(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_prefix_length(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_int_length(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_frac_length(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_exp_length(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_mantissa_length(), 3);
BOOST_REQUIRE_EQUAL(Recog.get_number_length(), 4);
BOOST_REQUIRE_EQUAL(Recog.get_prefix_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_int_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_frac_start(), 3);
BOOST_REQUIRE_EQUAL(Recog.get_exp_start(), 4);
BOOST_REQUIRE_EQUAL(Recog.get_mantissa_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_number_start(), 0);
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_prefix()), "1.2");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_int()), "1.2");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_frac()), "2");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_exp()), "");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_rest()), "");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_mantissa()), "1.2");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_number()), "-1.2");
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_prefix()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_int()), 1);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_frac()), 1);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_exp()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_rest()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_mantissa()), 3);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_number()), 4);
BOOST_REQUIRE(Recog.prefix_part().empty());
BOOST_REQUIRE_EQUAL(Recog.int_part().size(), 1);
auto p = Recog.int_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "1"));
BOOST_REQUIRE_EQUAL(Recog.frac_part().size(), 1);
p = Recog.frac_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "2"));
BOOST_REQUIRE(Recog.exp_part().empty());
BOOST_REQUIRE(Recog.rest_part().empty());
BOOST_REQUIRE_EQUAL(Recog.number_text().size(), 4);
p = Recog.number_text();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "-1.2"));
BOOST_REQUIRE(Recog.get_status() == OK);
BOOST_REQUIRE_EQUAL(Recog.to<int>(), -1);
BOOST_REQUIRE(Recog.to<double>() == -1.2);
BOOST_REQUIRE(Recog.get_status() == OK);
}
BOOST_AUTO_TEST_CASE(Float1Test) {
NumberRecognizer<> Recog;
Recog.remove_options(Floating);
Recog.recognize("1e2");
BOOST_REQUIRE(Recog.get_options() == (DefaultOptions & ~Floating));
BOOST_REQUIRE_EQUAL(Recog.get_base(), 10);
BOOST_REQUIRE_EQUAL(Recog.size(), 3);
BOOST_REQUIRE(!Recog.is_float());
BOOST_REQUIRE(!Recog.is_empty());
BOOST_REQUIRE(Recog.recognized());
BOOST_REQUIRE(!Recog.success());
BOOST_REQUIRE(!Recog.failure());
BOOST_REQUIRE(Recog.partial());
BOOST_REQUIRE(!Recog.has_sign());
BOOST_REQUIRE(!Recog.has_plus());
BOOST_REQUIRE(!Recog.has_minus());
BOOST_REQUIRE(Recog.is_positive());
BOOST_REQUIRE(!Recog.is_negative());
BOOST_REQUIRE(!Recog.has_exp_sign());
BOOST_REQUIRE(!Recog.has_exp_plus());
BOOST_REQUIRE(!Recog.has_exp_minus());
BOOST_REQUIRE(Recog.is_exp_positive());
BOOST_REQUIRE(!Recog.is_exp_negative());
BOOST_REQUIRE_EQUAL(Recog.get_leading_ws(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_leading_zeros(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_trailing_zeros(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_trailing_ws(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_prefix_length(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_int_length(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_frac_length(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_exp_length(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_rest_length(), 2);
BOOST_REQUIRE_EQUAL(Recog.get_mantissa_length(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_number_length(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_prefix_start(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_int_start(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_frac_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_exp_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_mantissa_start(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_number_start(), 0);
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_prefix()), "1e2");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_int()), "1e2");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_frac()), "e2");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_exp()), "e2");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_rest()), "e2");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_mantissa()), "1e2");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_number()), "1e2");
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_prefix()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_int()), 1);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_frac()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_exp()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_rest()), 2);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_mantissa()), 1);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_number()), 1);
BOOST_REQUIRE(Recog.prefix_part().empty());
BOOST_REQUIRE_EQUAL(Recog.int_part().size(), 1);
auto p = Recog.int_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "1"));
BOOST_REQUIRE(Recog.frac_part().empty());
BOOST_REQUIRE(Recog.exp_part().empty());
BOOST_REQUIRE_EQUAL(Recog.rest_part().size(), 2);
p = Recog.rest_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "e2"));
BOOST_REQUIRE_EQUAL(Recog.number_text().size(), 1);
p = Recog.number_text();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "1"));
BOOST_REQUIRE(Recog.get_status() == OK);
BOOST_REQUIRE_EQUAL(Recog.to<int>(), 1);
BOOST_REQUIRE(Recog.to<double>() == 1);
BOOST_REQUIRE(Recog.get_status() == OK);
}
BOOST_AUTO_TEST_CASE(FloatTest5a) {
NumberRecognizer<> Recog;
Recog.recognize("-1.20");
BOOST_REQUIRE(Recog.get_options() == DefaultOptions);
BOOST_REQUIRE_EQUAL(Recog.get_base(), 10);
BOOST_REQUIRE_EQUAL(Recog.size(), 5);
BOOST_REQUIRE(Recog.is_float());
BOOST_REQUIRE(!Recog.is_empty());
BOOST_REQUIRE(Recog.recognized());
BOOST_REQUIRE(Recog.success());
BOOST_REQUIRE(!Recog.failure());
BOOST_REQUIRE(!Recog.partial());
BOOST_REQUIRE(Recog.has_sign());
BOOST_REQUIRE(!Recog.has_plus());
BOOST_REQUIRE(Recog.has_minus());
BOOST_REQUIRE(!Recog.is_positive());
BOOST_REQUIRE(Recog.is_negative());
BOOST_REQUIRE(!Recog.has_exp_sign());
BOOST_REQUIRE(!Recog.has_exp_plus());
BOOST_REQUIRE(!Recog.has_exp_minus());
BOOST_REQUIRE(Recog.is_exp_positive());
BOOST_REQUIRE(!Recog.is_exp_negative());
BOOST_REQUIRE(Recog.is_float());
BOOST_REQUIRE_EQUAL(Recog.get_leading_ws(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_leading_zeros(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_trailing_zeros(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_trailing_ws(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_prefix_length(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_int_length(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_frac_length(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_exp_length(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_rest_length(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_mantissa_length(), 3);
BOOST_REQUIRE_EQUAL(Recog.get_number_length(), 5);
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_prefix()), "1.20");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_int()), "1.20");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_frac()), "20");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_exp()), "");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_rest()), "");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_mantissa()), "1.20");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_number()), "-1.20");
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_prefix()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_int()), 1);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_frac()), 1);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_exp()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_rest()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_mantissa()), 3);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_number()), 5);
BOOST_REQUIRE(Recog.prefix_part().empty());
BOOST_REQUIRE_EQUAL(Recog.int_part().size(), 1);
auto p = Recog.int_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "1"));
BOOST_REQUIRE_EQUAL(Recog.frac_part().size(), 1);
p = Recog.frac_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "2"));
BOOST_REQUIRE(Recog.exp_part().empty());
BOOST_REQUIRE(Recog.rest_part().empty());
BOOST_REQUIRE_EQUAL(Recog.number_text().size(), 5);
p = Recog.number_text();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "-1.20"));
BOOST_REQUIRE(Recog.get_status() == OK);
BOOST_REQUIRE_EQUAL(Recog.to<int>(), -1);
BOOST_REQUIRE(Recog.to<double>() == -1.2);
BOOST_REQUIRE(Recog.get_status() == OK);
}
BOOST_AUTO_TEST_CASE(FloatTest5b) {
NumberRecognizer<> Recog;
Recog.recognize("-12.e1");
BOOST_REQUIRE(Recog.get_options() == DefaultOptions);
BOOST_REQUIRE_EQUAL(Recog.get_base(), 10);
BOOST_REQUIRE_EQUAL(Recog.size(), 6);
BOOST_REQUIRE(Recog.is_float());
BOOST_REQUIRE(!Recog.is_empty());
BOOST_REQUIRE(Recog.recognized());
BOOST_REQUIRE(Recog.success());
BOOST_REQUIRE(!Recog.failure());
BOOST_REQUIRE(!Recog.partial());
BOOST_REQUIRE(Recog.has_sign());
BOOST_REQUIRE(!Recog.has_plus());
BOOST_REQUIRE(Recog.has_minus());
BOOST_REQUIRE(!Recog.is_positive());
BOOST_REQUIRE(Recog.is_negative());
BOOST_REQUIRE(!Recog.has_exp_sign());
BOOST_REQUIRE(!Recog.has_exp_plus());
BOOST_REQUIRE(!Recog.has_exp_minus());
BOOST_REQUIRE(Recog.is_exp_positive());
BOOST_REQUIRE(!Recog.is_exp_negative());
BOOST_REQUIRE_EQUAL(Recog.get_leading_ws(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_leading_zeros(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_trailing_zeros(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_trailing_ws(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_prefix_length(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_int_length(), 2);
BOOST_REQUIRE_EQUAL(Recog.get_frac_length(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_exp_length(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_mantissa_length(), 2);
BOOST_REQUIRE_EQUAL(Recog.get_number_length(), 6);
BOOST_REQUIRE_EQUAL(Recog.get_prefix_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_int_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_frac_start(), 4);
BOOST_REQUIRE_EQUAL(Recog.get_exp_start(), 5);
BOOST_REQUIRE_EQUAL(Recog.get_mantissa_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_number_start(), 0);
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_prefix()), "12.e1");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_int()), "12.e1");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_frac()), "e1");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_exp()), "1");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_rest()), "");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_mantissa()), "12.e1");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_number()), "-12.e1");
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_prefix()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_int()), 2);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_frac()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_exp()), 1);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_rest()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_mantissa()), 2);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_number()), 6);
BOOST_REQUIRE(Recog.prefix_part().empty());
BOOST_REQUIRE_EQUAL(Recog.int_part().size(), 2);
auto p = Recog.int_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "12"));
BOOST_REQUIRE_EQUAL(Recog.frac_part().size(), 0);
p = Recog.frac_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), ""));
BOOST_REQUIRE_EQUAL(Recog.exp_part().size(), 1);
p = Recog.exp_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "1"));
BOOST_REQUIRE(Recog.rest_part().empty());
BOOST_REQUIRE_EQUAL(Recog.number_text().size(), 6);
p = Recog.number_text();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "-12.e1"));
BOOST_REQUIRE(Recog.get_status() == OK);
BOOST_REQUIRE_EQUAL(Recog.to<int>(), -120);
BOOST_REQUIRE(Recog.to<double>() == -120);
BOOST_REQUIRE(Recog.get_status() == OK);
}
BOOST_AUTO_TEST_CASE(FloatTest7) {
NumberRecognizer<> Recog;
Recog.recognize("+1.2e3");
BOOST_REQUIRE(Recog.get_options() == DefaultOptions);
BOOST_REQUIRE_EQUAL(Recog.get_base(), 10);
BOOST_REQUIRE_EQUAL(Recog.size(), 6);
BOOST_REQUIRE(Recog.is_float());
BOOST_REQUIRE(!Recog.is_empty());
BOOST_REQUIRE(Recog.recognized());
BOOST_REQUIRE(Recog.success());
BOOST_REQUIRE(!Recog.failure());
BOOST_REQUIRE(!Recog.partial());
BOOST_REQUIRE(Recog.has_sign());
BOOST_REQUIRE(Recog.has_plus());
BOOST_REQUIRE(!Recog.has_minus());
BOOST_REQUIRE(Recog.is_positive());
BOOST_REQUIRE(!Recog.is_negative());
BOOST_REQUIRE(!Recog.has_exp_sign());
BOOST_REQUIRE(!Recog.has_exp_plus());
BOOST_REQUIRE(!Recog.has_exp_minus());
BOOST_REQUIRE(Recog.is_exp_positive());
BOOST_REQUIRE(!Recog.is_exp_negative());
BOOST_REQUIRE_EQUAL(Recog.get_leading_ws(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_leading_zeros(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_trailing_zeros(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_trailing_ws(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_prefix_length(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_int_length(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_frac_length(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_exp_length(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_mantissa_length(), 3);
BOOST_REQUIRE_EQUAL(Recog.get_number_length(), 6);
BOOST_REQUIRE_EQUAL(Recog.get_prefix_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_int_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_frac_start(), 3);
BOOST_REQUIRE_EQUAL(Recog.get_exp_start(), 5);
BOOST_REQUIRE_EQUAL(Recog.get_mantissa_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_number_start(), 0);
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_prefix()), "1.2e3");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_int()), "1.2e3");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_frac()), "2e3");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_exp()), "3");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_rest()), "");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_mantissa()), "1.2e3");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_number()), "+1.2e3");
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_prefix()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_int()), 1);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_frac()), 1);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_exp()), 1);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_rest()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_mantissa()), 3);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_number()), 6);
BOOST_REQUIRE_EQUAL(Recog.prefix_part().size(), 0);
auto p = Recog.prefix_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), ""));
BOOST_REQUIRE_EQUAL(Recog.int_part().size(), 1);
p = Recog.int_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "1"));
BOOST_REQUIRE_EQUAL(Recog.frac_part().size(), 1);
p = Recog.frac_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "2"));
BOOST_REQUIRE_EQUAL(Recog.exp_part().size(), 1);
p = Recog.exp_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "3"));
BOOST_REQUIRE(Recog.rest_part().empty());
BOOST_REQUIRE_EQUAL(Recog.number_text().size(), 6);
p = Recog.number_text();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "+1.2e3"));
BOOST_REQUIRE(Recog.get_status() == OK);
BOOST_REQUIRE_EQUAL(Recog.to<int>(), 1200);
BOOST_REQUIRE(Recog.to<double>() == 1200);
BOOST_REQUIRE(Recog.get_status() == OK);
}
BOOST_AUTO_TEST_CASE(FloatTest8) {
NumberRecognizer<> Recog;
Recog.recognize("+1.2e+3");
BOOST_REQUIRE(Recog.get_options() == DefaultOptions);
BOOST_REQUIRE_EQUAL(Recog.get_base(), 10);
BOOST_REQUIRE_EQUAL(Recog.size(), 7);
BOOST_REQUIRE(Recog.is_float());
BOOST_REQUIRE(!Recog.is_empty());
BOOST_REQUIRE(Recog.recognized());
BOOST_REQUIRE(Recog.success());
BOOST_REQUIRE(!Recog.failure());
BOOST_REQUIRE(!Recog.partial());
BOOST_REQUIRE(Recog.has_sign());
BOOST_REQUIRE(Recog.has_plus());
BOOST_REQUIRE(!Recog.has_minus());
BOOST_REQUIRE(Recog.is_positive());
BOOST_REQUIRE(!Recog.is_negative());
BOOST_REQUIRE(Recog.has_exp_sign());
BOOST_REQUIRE(Recog.has_exp_plus());
BOOST_REQUIRE(!Recog.has_exp_minus());
BOOST_REQUIRE(Recog.is_exp_positive());
BOOST_REQUIRE(!Recog.is_exp_negative());
BOOST_REQUIRE_EQUAL(Recog.get_leading_ws(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_leading_zeros(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_trailing_zeros(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_trailing_ws(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_prefix_length(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_int_length(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_frac_length(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_exp_length(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_mantissa_length(), 3);
BOOST_REQUIRE_EQUAL(Recog.get_number_length(), 7);
BOOST_REQUIRE_EQUAL(Recog.get_prefix_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_int_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_frac_start(), 3);
BOOST_REQUIRE_EQUAL(Recog.get_exp_start(), 6);
BOOST_REQUIRE_EQUAL(Recog.get_mantissa_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_number_start(), 0);
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_prefix()), "1.2e+3");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_int()), "1.2e+3");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_frac()), "2e+3");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_exp()), "3");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_rest()), "");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_mantissa()), "1.2e+3");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_number()), "+1.2e+3");
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_prefix()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_int()), 1);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_frac()), 1);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_exp()), 1);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_rest()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_mantissa()), 3);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_number()), 7);
BOOST_REQUIRE(Recog.prefix_part().empty());
BOOST_REQUIRE_EQUAL(Recog.int_part().size(), 1);
auto p = Recog.int_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "1"));
BOOST_REQUIRE_EQUAL(Recog.frac_part().size(), 1);
p = Recog.frac_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "2"));
BOOST_REQUIRE_EQUAL(Recog.exp_part().size(), 1);
p = Recog.exp_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "3"));
BOOST_REQUIRE(Recog.rest_part().empty());
BOOST_REQUIRE(Recog.get_status() == OK);
BOOST_REQUIRE_EQUAL(Recog.to<int>(), 1200);
BOOST_REQUIRE(Recog.to<double>() == 1200);
BOOST_REQUIRE(Recog.get_status() == OK);
}
BOOST_AUTO_TEST_CASE(FloatTest9) {
NumberRecognizer<> Recog;
Recog.recognize("-123.456E-789");
BOOST_REQUIRE(Recog.get_options() == DefaultOptions);
BOOST_REQUIRE_EQUAL(Recog.get_base(), 10);
BOOST_REQUIRE_EQUAL(Recog.size(), 13);
BOOST_REQUIRE(Recog.is_float());
BOOST_REQUIRE(!Recog.is_empty());
BOOST_REQUIRE(Recog.recognized());
BOOST_REQUIRE(Recog.success());
BOOST_REQUIRE(!Recog.failure());
BOOST_REQUIRE(!Recog.partial());
BOOST_REQUIRE(Recog.has_sign());
BOOST_REQUIRE(!Recog.has_plus());
BOOST_REQUIRE(Recog.has_minus());
BOOST_REQUIRE(!Recog.is_positive());
BOOST_REQUIRE(Recog.is_negative());
BOOST_REQUIRE(Recog.has_exp_sign());
BOOST_REQUIRE(!Recog.has_exp_plus());
BOOST_REQUIRE(Recog.has_exp_minus());
BOOST_REQUIRE(!Recog.is_exp_positive());
BOOST_REQUIRE(Recog.is_exp_negative());
BOOST_REQUIRE_EQUAL(Recog.get_leading_ws(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_leading_zeros(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_trailing_zeros(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_trailing_ws(), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_int()), 3);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_frac()), 3);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_exp()), 3);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_rest()), 0);
BOOST_REQUIRE_EQUAL(Recog.get_mantissa_length(), 7);
BOOST_REQUIRE_EQUAL(Recog.get_number_length(), 13);
BOOST_REQUIRE_EQUAL(Recog.get_prefix_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_int_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_frac_start(), 5);
BOOST_REQUIRE_EQUAL(Recog.get_exp_start(), 10);
BOOST_REQUIRE_EQUAL(Recog.get_mantissa_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_number_start(), 0);
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_prefix()), "123.456E-789");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_int()), "123.456E-789");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_frac()), "456E-789");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_exp()), "789");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_rest()), "");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_mantissa()), "123.456E-789");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_number()), "-123.456E-789");
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_prefix()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_int()), 3);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_frac()), 3);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_exp()), 3);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_rest()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_mantissa()), 7);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_number()), 13);
BOOST_REQUIRE(Recog.prefix_part().empty());
BOOST_REQUIRE_EQUAL(Recog.int_part().size(), 3);
auto p = Recog.int_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "123"));
BOOST_REQUIRE_EQUAL(Recog.frac_part().size(), 3);
p = Recog.frac_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "456"));
BOOST_REQUIRE_EQUAL(Recog.exp_part().size(), 3);
p = Recog.exp_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "789"));
BOOST_REQUIRE(Recog.rest_part().empty());
BOOST_REQUIRE_EQUAL(Recog.number_text().size(), 13);
p = Recog.number_text();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "-123.456E-789"));
BOOST_REQUIRE(Recog.get_status() == OK);
BOOST_REQUIRE_EQUAL(Recog.to<int>(), 0);
BOOST_REQUIRE(Recog.get_status() == DoubleToInt);
BOOST_REQUIRE(Recog.to<double>() == -0);
BOOST_REQUIRE(Recog.get_status() == DoubleUnderflow);
}
BOOST_AUTO_TEST_CASE(FloatTest12) {
NumberRecognizer<> Recog;
Recog.recognize("-123.4567E+8E");
BOOST_REQUIRE(Recog.get_options() == DefaultOptions);
BOOST_REQUIRE_EQUAL(Recog.get_base(), 10);
BOOST_REQUIRE_EQUAL(Recog.size(), 13);
BOOST_REQUIRE(Recog.is_float());
BOOST_REQUIRE(!Recog.is_empty());
BOOST_REQUIRE(Recog.recognized());
BOOST_REQUIRE(!Recog.success());
BOOST_REQUIRE(!Recog.failure());
BOOST_REQUIRE(Recog.partial());
BOOST_REQUIRE(Recog.has_sign());
BOOST_REQUIRE(!Recog.has_plus());
BOOST_REQUIRE(Recog.has_minus());
BOOST_REQUIRE(!Recog.is_positive());
BOOST_REQUIRE(Recog.is_negative());
BOOST_REQUIRE(Recog.has_exp_sign());
BOOST_REQUIRE(Recog.has_exp_plus());
BOOST_REQUIRE(!Recog.has_exp_minus());
BOOST_REQUIRE(Recog.is_exp_positive());
BOOST_REQUIRE(!Recog.is_exp_negative());
BOOST_REQUIRE_EQUAL(Recog.get_leading_ws(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_leading_zeros(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_trailing_zeros(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_trailing_ws(), 0);
BOOST_REQUIRE_EQUAL(Recog.get_prefix_length(), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_int()), 3);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_frac()), 4);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_exp()), 1);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_rest()), 1);
BOOST_REQUIRE_EQUAL(Recog.get_mantissa_length(), 8);
BOOST_REQUIRE_EQUAL(Recog.get_number_length(), 12);
BOOST_REQUIRE_EQUAL(Recog.get_prefix_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_int_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_frac_start(), 5);
BOOST_REQUIRE_EQUAL(Recog.get_exp_start(), 11);
BOOST_REQUIRE_EQUAL(Recog.get_mantissa_start(), 1);
BOOST_REQUIRE_EQUAL(Recog.get_number_start(), 0);
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_prefix()), "123.4567E+8E");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_int()), "123.4567E+8E");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_frac()), "4567E+8E");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_exp()), "8E");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_rest()), "E");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_mantissa()), "123.4567E+8E");
BOOST_REQUIRE_EQUAL(std::get<0>(Recog.get_number()), "-123.4567E+8E");
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_prefix()), 0);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_int()), 3);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_frac()), 4);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_exp()), 1);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_rest()), 1);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_mantissa()), 8);
BOOST_REQUIRE_EQUAL(std::get<1>(Recog.get_number()), 12);
BOOST_REQUIRE(Recog.prefix_part().empty());
BOOST_REQUIRE_EQUAL(Recog.int_part().size(), 3);
auto p = Recog.int_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "123"));
BOOST_REQUIRE_EQUAL(Recog.frac_part().size(), 4);
p = Recog.frac_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "4567"));
BOOST_REQUIRE_EQUAL(Recog.exp_part().size(), 1);
p = Recog.exp_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "8"));
BOOST_REQUIRE_EQUAL(Recog.rest_part().size(), 1);
p = Recog.rest_part();
BOOST_REQUIRE(std::equal(p.begin(), p.end(), "E"));
BOOST_REQUIRE(Recog.get_status() == OK);
BOOST_REQUIRE_EQUAL(Recog.to<int>(), std::numeric_limits<int>::min());
BOOST_REQUIRE(Recog.to<double>() == -12345670000);
BOOST_REQUIRE(Recog.get_status() == OK);
}
| 39.053793 | 80 | 0.714311 | spavloff |
fe9c5bb6dc65190c3b5fe33c9394c358dd96a5c1 | 4,916 | cpp | C++ | test/PegtlExecutableTests.cpp | gitmodimo/cppgraphqlgen | bee89894653ad12f574f941d27c156354b1d497c | [
"MIT"
] | 52 | 2018-08-12T15:36:12.000Z | 2019-05-04T09:22:34.000Z | test/PegtlExecutableTests.cpp | gitmodimo/cppgraphqlgen | bee89894653ad12f574f941d27c156354b1d497c | [
"MIT"
] | 30 | 2018-09-10T18:05:16.000Z | 2019-05-02T00:43:01.000Z | test/PegtlExecutableTests.cpp | gitmodimo/cppgraphqlgen | bee89894653ad12f574f941d27c156354b1d497c | [
"MIT"
] | 13 | 2018-08-20T03:40:22.000Z | 2019-04-19T08:15:46.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include <gtest/gtest.h>
#include "graphqlservice/GraphQLParse.h"
#include "graphqlservice/internal/Grammar.h"
#include <tao/pegtl/contrib/analyze.hpp>
using namespace graphql;
using namespace graphql::peg;
using namespace tao::graphqlpeg;
TEST(PegtlExecutableCase, ParseKitchenSinkQuery)
{
memory_input<> input(R"gql(
# Copyright (c) 2015-present, Facebook, Inc.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
query queryName($foo: ComplexType, $site: Site = MOBILE) {
whoever123is: node(id: [123, 456]) {
id ,
... on User @defer {
field2 {
id ,
alias: field1(first:10, after:$foo,) @include(if: $foo) {
id,
...frag
}
}
}
... @skip(unless: $foo) {
id
}
... {
id
}
}
}
mutation likeStory {
like(story: 123) @defer {
story {
id
}
}
}
subscription StoryLikeSubscription($input: StoryLikeSubscribeInput) {
storyLikeSubscribe(input: $input) {
story {
likers {
count
}
likeSentence {
text
}
}
}
}
fragment frag on Friend {
foo(size: $size, bar: $b, obj: {key: "value", block: """
block string uses \"""
"""})
}
{
unnamed(truthy: true, falsey: false, nullish: null),
query
})gql",
"ParseKitchenSinkQuery");
const bool result = parse<executable_document>(input);
ASSERT_TRUE(result) << "we should be able to parse the doc";
}
TEST(PegtlExecutableCase, ParseTodayQuery)
{
memory_input<> input(R"gql(
query Everything {
appointments {
edges {
node {
id
subject
when
isNow
}
}
}
tasks {
edges {
node {
id
title
isComplete
}
}
}
unreadCounts {
edges {
node {
id
name
unreadCount
}
}
}
})gql",
"ParseTodayQuery");
const bool result = parse<executable_document>(input);
ASSERT_TRUE(result) << "we should be able to parse the doc";
}
TEST(PegtlExecutableCase, ParseVariableDefaultEmptyList)
{
memory_input<> input(R"gql(
query QueryWithEmptyListVariable($empty: [Boolean!]! = []) {
fieldWithArg(arg: $empty)
})gql",
"ParseVariableDefaultEmptyList");
const bool result = parse<executable_document>(input);
ASSERT_TRUE(result) << "we should be able to parse the doc";
}
TEST(PegtlExecutableCase, AnalyzeExecutableGrammar)
{
ASSERT_EQ(size_t { 0 }, analyze<executable_document>(true))
<< "there shouldn't be any infinite loops in the PEG version of the grammar";
}
TEST(PegtlExecutableCase, InvalidStringEscapeSequence)
{
bool parsedQuery = false;
bool caughtException = false;
try
{
memory_input<> input(R"gql(query { foo @something(arg: "\.") })gql",
"InvalidStringEscapeSequence");
parsedQuery = parse<executable_document>(input);
}
catch (const peg::parse_error& e)
{
ASSERT_NE(nullptr, e.what());
using namespace std::literals;
const std::string_view error { e.what() };
constexpr auto c_start = "InvalidStringEscapeSequence:1:31: parse error matching "sv;
constexpr auto c_end = " graphql::peg::string_escape_sequence_content"sv;
ASSERT_TRUE(error.size() > c_start.size()) << "error message is too short";
ASSERT_TRUE(error.size() > c_end.size()) << "error message is too short";
EXPECT_TRUE(error.substr(0, c_start.size()) == c_start) << e.what();
EXPECT_TRUE(error.substr(error.size() - c_end.size()) == c_end) << e.what();
caughtException = true;
}
EXPECT_TRUE(caughtException) << "should catch a parse exception";
EXPECT_FALSE(parsedQuery) << "should not successfully parse the query";
}
using namespace std::literals;
constexpr auto queryWithDepth3 = R"gql(query {
foo {
bar
}
})gql"sv;
TEST(PegtlExecutableCase, ParserDepthLimitNotExceeded)
{
bool parsedQuery = false;
try
{
auto query = peg::parseString(queryWithDepth3, 3);
parsedQuery = query.root != nullptr;
}
catch (const peg::parse_error& ex)
{
FAIL() << ex.what();
}
EXPECT_TRUE(parsedQuery) << "should parse the query";
}
TEST(PegtlExecutableCase, ParserDepthLimitExceeded)
{
bool parsedQuery = false;
bool caughtException = false;
try
{
auto query = peg::parseString(queryWithDepth3, 2);
parsedQuery = query.root != nullptr;
}
catch (const peg::parse_error& ex)
{
ASSERT_NE(nullptr, ex.what());
using namespace std::literals;
const std::string_view error { ex.what() };
constexpr auto expected =
"GraphQL:4:3: Exceeded nested depth limit: 2 for https://spec.graphql.org/October2021/#SelectionSet"sv;
EXPECT_TRUE(error == expected) << ex.what();
caughtException = true;
}
EXPECT_TRUE(caughtException) << "should catch a parse exception";
EXPECT_FALSE(parsedQuery) << "should not successfully parse the query";
} | 21.189655 | 106 | 0.664158 | gitmodimo |
fe9f9f022b8b0fa0dd71c3e8cdc030200a5cb9c9 | 4,387 | cpp | C++ | qplacesearchsuggestionreplyimpl.cpp | mfbernardes/googlemaps | 7ce7124b385b2ebac0f72c38b094f436d4fe5c58 | [
"MIT"
] | 123 | 2016-07-18T07:53:34.000Z | 2022-02-21T20:30:27.000Z | qplacesearchsuggestionreplyimpl.cpp | mfbernardes/googlemaps | 7ce7124b385b2ebac0f72c38b094f436d4fe5c58 | [
"MIT"
] | 30 | 2016-07-18T07:55:30.000Z | 2022-03-06T02:03:24.000Z | qplacesearchsuggestionreplyimpl.cpp | mfbernardes/googlemaps | 7ce7124b385b2ebac0f72c38b094f436d4fe5c58 | [
"MIT"
] | 66 | 2016-09-17T12:41:41.000Z | 2021-12-28T16:39:48.000Z | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qplacesearchsuggestionreplyimpl.h"
#include "qgeoerror_messages.h"
#include <QCoreApplication>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonArray>
QT_BEGIN_NAMESPACE
QPlaceSearchSuggestionReplyImpl::QPlaceSearchSuggestionReplyImpl(QNetworkReply *reply,
QObject *parent)
: QPlaceSearchSuggestionReply(parent), m_reply(reply)
{
if (!m_reply)
return;
m_reply->setParent(this);
connect(m_reply, SIGNAL(finished()), this, SLOT(replyFinished()));
}
QPlaceSearchSuggestionReplyImpl::~QPlaceSearchSuggestionReplyImpl()
{
}
void QPlaceSearchSuggestionReplyImpl::abort()
{
if (m_reply)
m_reply->abort();
}
void QPlaceSearchSuggestionReplyImpl::setError(QPlaceReply::Error error_,
const QString &errorString)
{
QPlaceReply::setError(error_, errorString);
emit error(error_, errorString);
setFinished(true);
emit finished();
}
void QPlaceSearchSuggestionReplyImpl::replyFinished()
{
if (m_reply->error() != QNetworkReply::NoError) {
switch (m_reply->error()) {
case QNetworkReply::OperationCanceledError:
setError(CancelError, "Request canceled.");
break;
default:
setError(CommunicationError, "Network error.");
}
return;
}
QJsonDocument document = QJsonDocument::fromJson(m_reply->readAll());
if (!document.isObject()) {
setError(ParseError, QCoreApplication::translate(NOKIA_PLUGIN_CONTEXT_NAME, PARSE_ERROR));
emit error(error(), errorString());
return;
}
QJsonObject object = document.object();
QJsonValue status = object.value(QStringLiteral("status"));
if(status.toString().toLatin1() != "OK")
{
QJsonValue errorMessage = object.value(QStringLiteral("error_message"));
setError(UnknownError, QString("%1: %2").arg(status.toString()).arg(errorMessage.toString()).toLatin1());
return;
}
QJsonArray suggestions = object.value(QStringLiteral("predictions")).toArray();
QStringList s;
for (int i = 0; i < suggestions.count(); ++i) {
if(suggestions.at(i).isObject()) {
QJsonObject suggestion = suggestions.at(i).toObject();
QJsonValue description = suggestion.value("description");
if (description.isString()) {
s.append(description.toString());
}
}
}
setSuggestions(s);
m_reply->deleteLater();
m_reply = 0;
setFinished(true);
emit finished();
}
QT_END_NAMESPACE
| 34.007752 | 113 | 0.662412 | mfbernardes |
fea080aeeb2048c21d10127d23cbe7461383c40e | 694 | cpp | C++ | src/test-last-n.cpp | pmcharrison/ppm | d58e7598e02a6df8a4ef013f5e19987311295196 | [
"MIT"
] | 9 | 2019-12-28T16:03:48.000Z | 2021-07-02T07:59:17.000Z | src/test-last-n.cpp | pmcharrison/ppm | d58e7598e02a6df8a4ef013f5e19987311295196 | [
"MIT"
] | null | null | null | src/test-last-n.cpp | pmcharrison/ppm | d58e7598e02a6df8a4ef013f5e19987311295196 | [
"MIT"
] | 3 | 2021-09-15T10:34:16.000Z | 2022-03-17T21:36:44.000Z | #include <testthat.h>
typedef std::vector<int> sequence;
sequence last_n (const sequence&, int);
context("last_n") {
test_that("example 1") {
sequence input;
input.push_back(1);
input.push_back(2);
input.push_back(3);
sequence output = last_n(input, 0);
expect_true(output.size() == 0);
output = last_n(input, 1);
expect_true(output.size() == 1);
expect_true(output[0] == 3);
output = last_n(input, 2);
expect_true(output.size() == 2);
expect_true(output[0] == 2);
expect_true(output[1] == 3);
}
test_that("example 2") {
sequence input2;
sequence output2 = last_n(input2, 0);
expect_true(output2.size() == 0);
}
}
| 20.411765 | 41 | 0.616715 | pmcharrison |
fea162c41c1c26929a5f008a7542780dd89aa75f | 678 | hpp | C++ | DataStructures/Model/Structures/Linear/List.hpp | PearsonAnimates/DataStructures | 79732365ad4f0b84f40b6b3c5280dec3032ee99d | [
"Unlicense"
] | null | null | null | DataStructures/Model/Structures/Linear/List.hpp | PearsonAnimates/DataStructures | 79732365ad4f0b84f40b6b3c5280dec3032ee99d | [
"Unlicense"
] | null | null | null | DataStructures/Model/Structures/Linear/List.hpp | PearsonAnimates/DataStructures | 79732365ad4f0b84f40b6b3c5280dec3032ee99d | [
"Unlicense"
] | null | null | null | //
// List.hpp
// DataStructures
//
// Created by Amaya Penunuri, Yael on 2/8/18.
// Copyright © 2018 Amaya Penunuri, Yael. All rights reserved.
//
#ifndef List_hpp
#define List_hpp
#include <assert.h>
#include "../../Nodes/LinearNode.cpp"
template <class Type>
class List
{
protected:
int size;
public:
//Structures
virtual void add(Type item) = 0;
virtual void addAtIndex(int index, Type item) = 0;
virtual Type remove(int index) = 0;
virtual Type getFromIndex(int index) = 0;
//Helper
virtual int getSize() const = 0;
virtual LinearNode<Type> * getFront() = 0;
virtual LinearNode<Type> * getEnd() = 0;
};
#endif /* List_hpp */
| 20.545455 | 63 | 0.654867 | PearsonAnimates |
fea5013266bd04ee8f3e0c90fe308ea553cb70f4 | 283 | cpp | C++ | Test/MockWatch.cpp | Unitrunker/Tile | 71b8b0e33bf8100090be6d9ac45e7d300f812cbc | [
"Apache-2.0"
] | null | null | null | Test/MockWatch.cpp | Unitrunker/Tile | 71b8b0e33bf8100090be6d9ac45e7d300f812cbc | [
"Apache-2.0"
] | 1 | 2017-11-14T16:56:26.000Z | 2017-11-20T02:00:23.000Z | Test/MockWatch.cpp | Unitrunker/Tile | 71b8b0e33bf8100090be6d9ac45e7d300f812cbc | [
"Apache-2.0"
] | 2 | 2017-11-14T14:18:51.000Z | 2019-06-16T11:58:47.000Z | #include "stdafx.h"
#include "MockWatch.h"
#include "../Tile/ITile.h"
/*
Copyright 2011 Rick Parrish
*/
/// <param name="pDraw">control in need of redrawing.</param>
void MockWatch::Redraw(ITile *pTile)
{
printf("%ld called %s\n", pTile->identity(), __FUNCTION__);
}
| 20.214286 | 62 | 0.65371 | Unitrunker |
fea5ca89b90ac5dcfd1a8bdf5f0c3a1f80f43167 | 591 | cc | C++ | apps/rosetta/python/test/test_pybind.cc | YaoYinYing/rifdock | cbde6bbeefd29a066273bdf2937cf36b0d2e6335 | [
"Apache-2.0"
] | 25 | 2019-07-23T01:03:48.000Z | 2022-03-31T04:16:08.000Z | apps/rosetta/python/test/test_pybind.cc | YaoYinYing/rifdock | cbde6bbeefd29a066273bdf2937cf36b0d2e6335 | [
"Apache-2.0"
] | 13 | 2018-01-30T17:45:57.000Z | 2022-03-28T11:02:44.000Z | apps/rosetta/python/test/test_pybind.cc | YaoYinYing/rifdock | cbde6bbeefd29a066273bdf2937cf36b0d2e6335 | [
"Apache-2.0"
] | 14 | 2018-02-08T01:42:28.000Z | 2022-03-31T12:56:17.000Z | #include <pybind11/pybind11.h>
#include <memory>
#include <iostream>
namespace py = pybind11;
struct Foo : public std::enable_shared_from_this<Foo> {
Foo(){}
void bar() const {
std::cout << "bar" << std::endl;
}
};
std::shared_ptr<Foo> make_Foo(){
return std::make_shared<Foo>();
}
PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);
PYBIND11_PLUGIN(test_pybind) {
py::module m("test_pybind", "test pybind11");
py::class_< Foo, std::shared_ptr<Foo> >(m, "Foo")
.def( py::init<>() )
.def( "bar", &Foo::bar )
;
m.def( "make_Foo", &make_Foo );
return m.ptr();
}
| 17.909091 | 55 | 0.637902 | YaoYinYing |
fea9b83df94e6af234c8279993feb2596801cfa1 | 2,386 | cpp | C++ | src/NewTileDialog.cpp | lawadr/gridiron | 950aa96a7574a825fb3eb56e802f54c311587413 | [
"MIT"
] | 1 | 2020-01-03T07:04:32.000Z | 2020-01-03T07:04:32.000Z | src/NewTileDialog.cpp | lawadr/gridiron | 950aa96a7574a825fb3eb56e802f54c311587413 | [
"MIT"
] | null | null | null | src/NewTileDialog.cpp | lawadr/gridiron | 950aa96a7574a825fb3eb56e802f54c311587413 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2012-2013 Lawrence Adranghi
See LICENSE in root directory.
*/
#include "NewTileDialog.h"
#include "TileSet.h"
#include "Tile.h"
#include "ResourceModel.h"
#include <QtGui/qboxlayout.h>
#include <QtGui/qformlayout.h>
#include <QtGui/qspinbox.h>
#include <QtGui/qdialogbuttonbox.h>
#include <QtCore/qsettings.h>
#include <QtGui/qlineedit.h>
#include <QtGui/qcombobox.h>
#include <QtGui/qcompleter.h>
#include <QtGui/qfilesystemmodel.h>
#include <OGRE/OgreMaterialManager.h>
NewTileDialog::NewTileDialog(QWidget* parent, Qt::WindowFlags flags)
: QDialog(parent, flags)
{
setWindowTitle(tr("New Tile"));
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
QBoxLayout* layout = new QBoxLayout(QBoxLayout::Down, this);
layout->setSizeConstraint(QLayout::SetFixedSize);
QFormLayout* formLayout = new QFormLayout;
ResourceModel* model = new ResourceModel(this);
model->setResourceManager(Ogre::MaterialManager::getSingletonPtr());
model->setResourceGroup("General");
mName = new QLineEdit;
formLayout->addRow(tr("Name: "), mName);
mMaterial = new QComboBox;
mMaterial->setModel(model);
formLayout->addRow(tr("Material: "), mMaterial);
layout->addLayout(formLayout);
QDialogButtonBox* buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
layout->addWidget(buttonBox);
//QSettings settings;
//settings.beginGroup("NewMapDialog");
//xSize_->setValue(settings.value("xSize", 32).toInt());
//ySize_->setValue(settings.value("ySize", 32).toInt());
//zSize_->setValue(settings.value("zSize", 1).toInt());
//settings.endGroup();
}
Tile* NewTileDialog::createTile(TileSet* tileSet) {
Tile* tile = 0;
if (exec() == QDialog::Accepted) {
//QSettings settings;
//settings.beginGroup("NewMapDialog");
//settings.setValue("xSize", xSize_->value());
//settings.setValue("ySize", ySize_->value());
//settings.setValue("zSize", zSize_->value());
//settings.endGroup();
tile = static_cast<Tile*>(tileSet->createItem());
tile->setName(mName->text());
tile->setMaterial(mMaterial->currentText().toStdString());
}
return tile;
}
| 31.394737 | 104 | 0.686505 | lawadr |
fead2a1d883a9d0b85e83943358bc70996257301 | 10,686 | hh | C++ | gazebo/gui/building/RectItem.hh | otamachan/ros-indigo-gazebo7-deb | abc6b40247cdce14d9912096a0ad5135d420ce04 | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2017-07-14T19:36:51.000Z | 2020-04-01T06:47:59.000Z | gazebo/gui/building/RectItem.hh | otamachan/ros-indigo-gazebo7-deb | abc6b40247cdce14d9912096a0ad5135d420ce04 | [
"ECL-2.0",
"Apache-2.0"
] | 20 | 2017-07-20T21:04:49.000Z | 2017-10-19T19:32:38.000Z | gazebo/gui/building/RectItem.hh | otamachan/ros-indigo-gazebo7-deb | abc6b40247cdce14d9912096a0ad5135d420ce04 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2012-2016 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _GAZEBO_GUI_BUILDING_RECTITEM_HH_
#define _GAZEBO_GUI_BUILDING_RECTITEM_HH_
#include <memory>
#include <vector>
#include <ignition/math/Vector2.hh>
#include <ignition/math/Vector3.hh>
#include "gazebo/common/Color.hh"
#include "gazebo/gui/qt.h"
#include "gazebo/gui/building/EditorItem.hh"
#include "gazebo/util/system.hh"
namespace gazebo
{
namespace gui
{
class GrabberHandle;
class MeasureItem;
class RotateHandle;
// Forward declare private data.
class RectItemPrivate;
/// \addtogroup gazebo_gui
/// \{
/// \class RectItem RectItem.hh
/// \brief 2D rectangle.
class GZ_GUI_VISIBLE RectItem :
public EditorItem, public QGraphicsRectItem
{
Q_OBJECT
/// \brief Resize flags used to indicate which dimension can be resized.
public: enum ResizeFlags
{
/// \brief No dimensions.
NONE = 0x00,
/// \brief Width
ITEM_WIDTH = 0x01,
/// \brief Height
ITEM_HEIGHT = 0x02
};
/// \brief Constructor
public: RectItem();
/// \brief Destructor
public: virtual ~RectItem();
/// \brief Set the width of the rect item.
/// \param[in] _width Width of the rect item in pixels.
public: void SetWidth(const int _width);
/// \brief Set the height of the rect item.
/// \param[in] _height Height of the rect item in pixels.
public: void SetHeight(const int _height);
/// \brief Set the size of the rect item.
/// \param[in] _size Size of the rect item in pixels.
public: void SetSize(const ignition::math::Vector2i &_size);
/// \brief Get the width of the rect item.
/// \return Width of the rect item in pixels.
public: double Width() const;
/// \brief Get the height of the rect item.
/// \return Height of the rect item in pixels.
public: double Height() const;
/// \brief Set the position of this item inside its parent wall.
/// \param[in] _positionOnWall New normalized position on wall.
public: void SetPositionOnWall(const double _positionOnWall);
/// \brief Get the position of this item inside its parent wall.
/// \return Normalized position on parent wall.
public: double PositionOnWall() const;
/// \brief Set the angle of this item inside its parent wall.
/// \param[in] _angleOnWall New angle on wall, either 0 or 180 degrees.
public: void SetAngleOnWall(const double _angleOnWall);
/// \brief Get the angle of this item inside its parent wall.
/// \return Angle on parent wall in degrees.
public: double AngleOnWall() const;
/// \brief Show the grabber and rotate handles of the rect item.
/// \param[in] _show True to draw the handles, and false to hide them.
public: void ShowHandles(const bool _show);
// Documentation inherited
public: void SetHighlighted(const bool _highlighted);
/// \brief Detach the rect item from its parent.
public: void DetachFromParent();
/// \brief Helper method for Updating the corner positions of the rect
/// item.
protected: void UpdateCornerPositions();
/// \brief Draw bounding box
/// \param[in] _painter Qt painter object.
protected: void DrawBoundingBox(QPainter *_painter);
/// \brief Set the position of the rect item
/// \param[in] _pos Position in pixel coordinates.
public: virtual void SetPosition(const ignition::math::Vector2d &_pos);
/// \brief Set the position of the rect item
/// \param[in] _x X position in pixel coordinates.
/// \param[in] _y Y position in pixel coordinates.
public: virtual void SetPosition(const double _x, const double _y);
/// \brief Set the rotation of the rect item.
/// \param[in] _angle Rotation angle in degrees.
public: virtual void SetRotation(const double _angle);
/// \brief Set the resize flag of the rect item.
/// \param[in] _flag Resize flag which controls how the item can be
/// resized.
public: virtual void SetResizeFlag(const unsigned int _flag);
/// \brief Get the rotation of the rect item
/// \return Rotation in degrees.
public: virtual double Rotation() const;
// Documentation inherited
public: virtual ignition::math::Vector3d Size() const;
// Documentation inherited
public: virtual ignition::math::Vector3d ScenePosition() const;
// Documentation inherited
public: virtual double SceneRotation() const;
/// \brief Get the bounding box of the rect item.
/// \return The bounding box of the rect item.
protected: virtual QRectF boundingRect() const;
/// \brief Update this item's measures.
protected: void UpdateMeasures();
/// \brief Filter Qt events and redirect them to the rotate handle.
/// \param[in] _rotateHandle Rotate handle that will handle the event.
/// \param[in] _event Qt event
private: virtual bool RotateEventFilter(RotateHandle *_rotateHandle,
QEvent *_event);
/// \brief Filter Qt events and redirect them to the grabber handle.
/// \param[in] _grabber Grabber handle that will handle the event.
/// \param[in] _event Qt event
private: virtual bool GrabberEventFilter(GrabberHandle *_grabber,
QEvent *_event);
/// \brief Qt paint function for drawing the rect item.
/// \param[in] _painter Qt painter object.
/// \param[in] _option Qt style options for the item.
/// \param[in] _widget Qt widget being painted on.
private: virtual void paint(QPainter *_painter,
const QStyleOptionGraphicsItem *_option, QWidget *_widget);
/// \brief Qt mouse hover enter event.
/// \param[in] _event Qt mouse hover event.
private: void hoverEnterEvent(QGraphicsSceneHoverEvent *_event);
/// \brief Qt mouse hover move event.
/// \param[in] _event Qt mouse hover event.
private: void hoverMoveEvent(QGraphicsSceneHoverEvent *_event);
/// \brief Qt mouse hover leave event.
/// \param[in] _event Qt mouse hover event.
private: void hoverLeaveEvent(QGraphicsSceneHoverEvent *_event);
/// \brief Qt mouse move event.
/// \param[in] _event Qt mouse event.
private: virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *_event);
/// \brief Qt mouse press event.
/// \param[in] _event Qt mouse event.
private: virtual void mousePressEvent(QGraphicsSceneMouseEvent *_event);
/// \brief Qt mouse release event.
/// \param[in] _event Qt mouse event.
private: virtual void mouseReleaseEvent(
QGraphicsSceneMouseEvent *_event);
/// \brief Qt mouse press event during drag and drop.
/// \param[in] _event Qt mouse drag and drop event.
private: virtual void mousePressEvent(
QGraphicsSceneDragDropEvent *_event);
/// \brief Qt mouse move event during drag and drop.
/// \param[in] _event Qt mouse drag and drop event.
private: virtual void mouseMoveEvent(
QGraphicsSceneDragDropEvent *_event);
/// \brief Qt mouse double click event.
/// \param[in] _event Qt mouse event.
private: virtual void mouseDoubleClickEvent(
QGraphicsSceneMouseEvent *_event);
/// \brief Filter Qt events and redirect them to another item.
/// \param[in] _watched Item that handle that will handle the event.
/// \param[in] _event Qt event.
private: virtual bool sceneEventFilter(QGraphicsItem *_watched,
QEvent *_event);
/// \brief React to item changes notified by Qt.
/// \param[in] _change Qt change type, e.g. selected change, position
/// change.
/// \param[in] _value Value to changed to.
private: QVariant itemChange(GraphicsItemChange _change,
const QVariant &_value);
/// \brief Qt context menu event received on a mouse right click.
/// \param[in] Qt context menu event.
private: virtual void contextMenuEvent(
QGraphicsSceneContextMenuEvent *_event);
/// brief Emit size changed Qt signals.
private: virtual void SizeChanged();
/// brief Helper function for resizing the rect item.
/// \param[in] _x Change in x (width).
/// \param[in] _y Change in y (height).
private: void AdjustSize(const double _x, const double _y);
/// \brief Qt callback for opening the item inspector
private slots: virtual void OnOpenInspector();
/// \brief Qt callback when the item is being deleted.
private slots: virtual void OnDeleteItem();
/// \brief Width of rect item in pixels.
protected: double width;
/// \brief Height of rect item in pixels.
protected: double height;
/// \brief Actual width of rect item drawn in pixels.
protected: double drawingWidth;
/// \brief Actual height of rect item drawn in pixels.
protected: double drawingHeight;
/// \brief X origin of the rect item in pixels.
protected: double drawingOriginX;
/// \brief Y origin of the rect item in pixels.
protected: double drawingOriginY;
/// \brief Border color of the rect item.
protected: common::Color borderColor;
/// \brief Rotation angle of the rect item in degrees.
protected: double rotationAngle;
/// \brief Qt action for opening the inspector.
protected: QAction *openInspectorAct;
/// \brief Qt action for deleting the item.
protected: QAction *deleteItemAct;
/// \brief A vector containing this item's measure items.
/// Currently only used for windows and doors, containing one measure
/// towards each end of this item's parent wall.
protected: std::vector<MeasureItem *> measures;
/// \internal
/// \brief Pointer to private data.
private: std::unique_ptr<RectItemPrivate> dataPtr;
};
/// \}
}
}
#endif
| 35.62 | 78 | 0.659929 | otamachan |
feb478a9424a3108034b69a3c9074bf7d4840633 | 6,324 | cxx | C++ | ivp/ivp_physics/ivp_performancecounter.cxx | DannyParker0001/Kisak-Strike | 99ed85927336fe3aff2efd9b9382b2b32eb1d05d | [
"Unlicense"
] | 252 | 2020-12-16T15:34:43.000Z | 2022-03-31T23:21:37.000Z | ivp/ivp_physics/ivp_performancecounter.cxx | DannyParker0001/Kisak-Strike | 99ed85927336fe3aff2efd9b9382b2b32eb1d05d | [
"Unlicense"
] | 23 | 2020-12-20T18:02:54.000Z | 2022-03-28T16:58:32.000Z | ivp/ivp_physics/ivp_performancecounter.cxx | DannyParker0001/Kisak-Strike | 99ed85927336fe3aff2efd9b9382b2b32eb1d05d | [
"Unlicense"
] | 42 | 2020-12-19T04:32:33.000Z | 2022-03-30T06:00:28.000Z | // Copyright (C) Ipion Software GmbH 1999-2000. All rights reserved.
#include <ivp_physics.hxx>
#ifndef WIN32
# pragma implementation "ivp_performancecounter.hxx"
#endif
#include <ivp_performancecounter.hxx>
void IVP_PerformanceCounter_Simple::reset_and_print_performance_counters(IVP_Time current_time){
IVP_DOUBLE diff = count_PSIs;
if (diff == 0.0f) return;
IVP_DOUBLE collision = counter[IVP_PE_PSI_UNIVERSE][0] + counter[IVP_PE_PSI_SHORT_MINDISTS][0] +
counter[IVP_PE_PSI_CRITICAL_MINDISTS][0] + counter[IVP_PE_PSI_HULL][0] +
counter[IVP_PE_AT_INIT][0];
IVP_DOUBLE dynamics = counter[IVP_PE_PSI_CONTROLLERS][0] + counter[IVP_PE_PSI_INTEGRATORS][0] ;
IVP_DOUBLE sum = collision + dynamics;
IVP_DOUBLE factor = .001f / diff;
#if defined(PSX2)
ivp_message( "UNIV: %2.2f,%2.2f CONTR: %2.2f,%2.2f INTEGR: %2.2f,%2.2f "
"HULL: %2.2f,%2.2f SHORT: %2.2f,%2.2f CRITIC: %2.2f,%2.2f "
"USR: %2.2f,%2.2f\n",
counter[IVP_PE_PSI_UNIVERSE][0] * factor,
counter[IVP_PE_PSI_UNIVERSE][1] * factor,
counter[IVP_PE_PSI_CONTROLLERS][0] * factor,
counter[IVP_PE_PSI_CONTROLLERS][1] * factor,
counter[IVP_PE_PSI_INTEGRATORS][0] * factor,
counter[IVP_PE_PSI_INTEGRATORS][1] * factor,
counter[IVP_PE_PSI_HULL][0] * factor,
counter[IVP_PE_PSI_HULL][1] * factor,
counter[IVP_PE_PSI_SHORT_MINDISTS][0] * factor,
counter[IVP_PE_PSI_SHORT_MINDISTS][1] * factor,
counter[IVP_PE_PSI_CRITICAL_MINDISTS][0] * factor,
counter[IVP_PE_PSI_CRITICAL_MINDISTS][1] * factor,
counter[IVP_PE_USR1][0] * factor,
counter[IVP_PE_USR1][1] * factor);
#elif 1
ivp_message( "TOT %2.1f%% %2.2f COLL %2.2f DYN %2.2f det: UNIV: %2.2f CONTR: %2.2f INTEGR: %2.2f "
"HULL: %2.2f SHORT: %2.2f CRITIC: %2.2f AT %2.2f\n",
sum * factor * 66.0f * (100.0 * 0.001),
sum * factor, collision * factor , dynamics * factor,
counter[IVP_PE_PSI_UNIVERSE][0] * factor,
counter[IVP_PE_PSI_CONTROLLERS][0] * factor,
counter[IVP_PE_PSI_INTEGRATORS][0] * factor,
counter[IVP_PE_PSI_HULL][0] * factor,
counter[IVP_PE_PSI_SHORT_MINDISTS][0] * factor,
counter[IVP_PE_PSI_CRITICAL_MINDISTS][0] * factor,
counter[IVP_PE_AT_INIT][0] * factor);
#endif
P_MEM_CLEAR_M4(this);
time_of_last_reset = current_time;
}
void IVP_PerformanceCounter_Simple::environment_is_going_to_be_deleted(IVP_Environment *){
P_DELETE_THIS(this);
}
IVP_PerformanceCounter_Simple::~IVP_PerformanceCounter_Simple(){
;
}
IVP_PerformanceCounter_Simple::IVP_PerformanceCounter_Simple(){
P_MEM_CLEAR_M4(this);
}
#if defined(PSXII)
/*
* Include file for the performance counters. Link with libpc.a.
* Note that the performance counters will not be implemented
* in the retail version of the hardware so it sould not be
* compiled into the final release app.
*
* Refer to the libpc.txt documentation for the defines to set
* up the performance counter. Below are some commonly used
* settings.
*/
#include <libpc.h>
/*
* Count CPU cycles in Counter0 and DCache Misses
* in Counter1
*/
#define PROFILE_CPU_DCACHE \
( SCE_PC_CTE | \
\
SCE_PC0_CPU_CYCLE | \
SCE_PC_U0|SCE_PC_S0|SCE_PC_K0|SCE_PC_EXL0 | \
\
SCE_PC1_DCACHE_MISS | \
SCE_PC_U1|SCE_PC_S1|SCE_PC_K1|SCE_PC_EXL1 \
)
/*
* Count ICache misses in Counter0 and CPU cycles
* in Counter1.
*/
#define PROFILE_ICACHE_CPU \
( SCE_PC_CTE | \
\
SCE_PC1_CPU_CYCLE | \
SCE_PC_U1|SCE_PC_S1|SCE_PC_K1|SCE_PC_EXL1 | \
\
SCE_PC0_ICACHE_MISS | \
SCE_PC_U0|SCE_PC_S0|SCE_PC_K0|SCE_PC_EXL0 \
)
/*
* Count Address bus busy(0) and Data bus busy(1)
*/
#define PROFILE_ADDRBUS_DATABUS \
( SCE_PC_CTE | \
\
SCE_PC0_ADDR_BUS_BUSY | \
SCE_PC_U0|SCE_PC_S0|SCE_PC_K0|SCE_PC_EXL0 | \
\
SCE_PC1_DATA_BUS_BUSY | \
SCE_PC_U1|SCE_PC_S1|SCE_PC_K1|SCE_PC_EXL1 \
)
/*
* Refer to the Sony libpc documentation for the flags.
*/
void IVP_PerformanceCounter_Simple::start_pcount(){
int flags = PROFILE_CPU_DCACHE;
count_PSIs++;
counting = IVP_PE_PSI_START;
scePcStart(flags,0,0);
}
void IVP_PerformanceCounter_Simple::stop_pcount(){
scePcStart(SCE_PC0_NO_EVENT|SCE_PC1_NO_EVENT,0,0);
}
void IVP_PerformanceCounter_Simple::pcount( IVP_PERFORMANCE_ELEMENT el){
/*
* This could be += or = depending on how pcount() is called
*/
int c0 = scePcGetCounter0();
int diff0 = c0 - ref_counter[0];
ref_counter[0] = c0;
int c1 = scePcGetCounter1();
int diff1 = c1 - ref_counter[1];
ref_counter[1] = c1;
counter[counting][0] += diff0;
counter[counting][1] += diff1;
counting = el;
}
#elif defined(WIN32)
# ifndef _XBOX
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
# else
# ifndef WINVER
# define WINVER 0x0500
# endif
# ifndef _X86_
# define _X86_
# endif /* _X86_ */
# include <excpt.h>
# include <stdarg.h>
# include <windef.h>
# include <winbase.h>
# endif
void IVP_PerformanceCounter_Simple::pcount( IVP_PERFORMANCE_ELEMENT el){
__int64 Profile_Counter;
__int64 Profile_Freq;
if (el == IVP_PE_PSI_UNIVERSE ){
count_PSIs++;
}
QueryPerformanceCounter((LARGE_INTEGER*)(&Profile_Counter));
QueryPerformanceFrequency( (LARGE_INTEGER*) &Profile_Freq); // address of current frequency
int diff0 = Profile_Counter - ref_counter64;
ref_counter64 = Profile_Counter;
counter[counting][0] += 1e6 * double(diff0) / double (Profile_Freq);
counting = el;
}
void IVP_PerformanceCounter_Simple::start_pcount(){
counting = IVP_PE_PSI_START;
}
void IVP_PerformanceCounter_Simple::stop_pcount(){ ; }
#else
void IVP_PerformanceCounter_Simple::pcount( IVP_PERFORMANCE_ELEMENT ){;}
void IVP_PerformanceCounter_Simple::start_pcount(){ ; }
void IVP_PerformanceCounter_Simple::stop_pcount(){ ; }
#endif
| 29.830189 | 107 | 0.656072 | DannyParker0001 |
feb7932ca8430e2c00e70afd578fd077c8217f3e | 41,396 | cpp | C++ | Windflower/src/Parser.cpp | Ornibyl/Windflower | 5a8f18aa970d8145faf065170b4541e2bf1e592c | [
"MIT"
] | null | null | null | Windflower/src/Parser.cpp | Ornibyl/Windflower | 5a8f18aa970d8145faf065170b4541e2bf1e592c | [
"MIT"
] | null | null | null | Windflower/src/Parser.cpp | Ornibyl/Windflower | 5a8f18aa970d8145faf065170b4541e2bf1e592c | [
"MIT"
] | null | null | null | #include "Parser.hpp"
#include <unordered_map>
#include <filesystem>
#include <fstream>
#include "Utils/Format.hpp"
namespace wf
{
Parser::Parser(std::string_view file_name, std::string_view text, Compiler::Flags& flags)
: flags(flags)
{
file_tokenizers.emplace_back(file_name, text);
advance();
}
Tokenizer& Parser::get_tokenizer()
{
return file_tokenizers[file_tokenizers.size() - 1];
}
void Parser::advance()
{
previous_token = current_token;
current_token = get_tokenizer().advance();
while(current_token.type == Token::Type::ERROR)
{
errors.ignore_errors = false;
errors.push_error(current_token.position, current_token.value.value());
current_token = get_tokenizer().advance();
}
}
void Parser::rewind(Tokenizer::RewindInfo info)
{
get_tokenizer().rewind(info);
current_token = get_tokenizer().advance();
while(current_token.type == Token::Type::ERROR)
{
errors.ignore_errors = false;
errors.push_error(current_token.position, current_token.value.value());
current_token = get_tokenizer().advance();
}
}
void Parser::push_newline_ignore(bool value)
{
ignore_newline_stack.push_back(value);
get_tokenizer().set_ignore_newline(value);
if(value)
{
while(current_token.type == Token::Type::NEWLINE)
{
advance();
}
}
}
void Parser::pop_newline_ignore()
{
if(ignore_newline_stack.size() == 0)
{
throw std::runtime_error("Compiler bug: ignore_newline_stack was popped when the size is zero.");
}
ignore_newline_stack.pop_back();
get_tokenizer().set_ignore_newline(ignore_newline_stack.size() == 0? false : ignore_newline_stack[ignore_newline_stack.size() - 1]);
}
bool Parser::expect_expression(const FilePosition& pos, std::shared_ptr<ExpressionNode> expr)
{
if(expr == nullptr)
{
errors.push_error(pos, "Expected an expression.");
return false;
}
return true;
}
bool Parser::expect_ttype(Token::Type ttype, std::string_view error_message)
{
advance();
if(previous_token.type != ttype)
{
errors.push_error(previous_token.position, error_message);
return false;
}
return true;
}
bool Parser::expect_func_type(std::string& type_string)
{
advance();
if(!expect_ttype(Token::Type::KW_FUNC, "Expected 'func'.")) return false;
if(!expect_ttype(Token::Type::PAREN_OPEN, "Expected a '('.")) return false;
type_string += "func(";
if(current_token.type != Token::Type::PAREN_CLOSE)
{
if(!expect_type_no_void(type_string)) return false;
while(current_token.type == Token::Type::COMMA)
{
advance();
type_string += ", ";
if(!expect_type_no_void(type_string)) return false;
}
if(!expect_ttype(Token::Type::PAREN_CLOSE, "Expected a ')'.")) return false;
type_string += ")";
}
else
{
advance();
type_string += ")";
}
if(!expect_ttype(Token::Type::ARROW, "Expected a '->'.")) return false;
type_string += " -> ";
if(!expect_type(type_string)) return false;
if(!expect_ttype(Token::Type::PAREN_CLOSE, "Expected a ')'.")) return false;
return true;
}
bool Parser::expect_type(std::string& type_string)
{
if(current_token.type == Token::Type::IDENTIFIER)
{
advance();
type_string += previous_token.value.value();
return true;
}
else if(current_token.type == Token::Type::PAREN_OPEN)
{
return expect_func_type(type_string);
}
advance();
switch(previous_token.type)
{
case Token::Type::KW_ANY:
type_string += "any";
return true;
case Token::Type::KW_VOID:
type_string += "void";
return true;
case Token::Type::KW_STRING:
type_string += "string";
return true;
case Token::Type::KW_INT:
type_string += "int";
return true;
case Token::Type::KW_FLOAT:
type_string += "float";
return true;
case Token::Type::KW_BOOL:
type_string += "bool";
return true;
default:
break;
}
errors.push_error(previous_token.position, "Expected a valid type.");
return false;
}
bool Parser::expect_type_no_void(std::string& type_string)
{
if(current_token.type == Token::Type::IDENTIFIER)
{
advance();
type_string += previous_token.value.value();
return true;
}
else if(current_token.type == Token::Type::PAREN_OPEN)
{
return expect_func_type(type_string);
}
advance();
switch(previous_token.type)
{
case Token::Type::KW_ANY:
type_string += "any";
return true;
case Token::Type::KW_VOID:
errors.push_error(previous_token.position, "'void' cannot be used here.");
return false;
case Token::Type::KW_STRING:
type_string += "string";
return true;
case Token::Type::KW_INT:
type_string += "int";
return true;
case Token::Type::KW_FLOAT:
type_string += "float";
return true;
case Token::Type::KW_BOOL:
type_string += "bool";
return true;
default:
break;
}
errors.push_error(previous_token.position, "Expected a valid type.");
return false;
}
bool Parser::expect_identifier()
{
advance();
if(previous_token.type != Token::Type::IDENTIFIER)
{
errors.push_error(previous_token.position, "Expected an identifier.");
return false;
}
return true;
}
std::shared_ptr<Node> Parser::parse_text()
{
push_newline_ignore(false);
std::shared_ptr<ProgramNode> ast = parse_program();
pop_newline_ignore();
if(ast != nullptr && current_token.type != Token::Type::TT_EOF)
{
errors.push_error(current_token.position, "Expected a newline.");
}
return ast;
}
std::shared_ptr<ProgramNode> Parser::parse_program()
{
std::shared_ptr<ProgramNode> program = std::make_shared<ProgramNode>();
program->position = current_token.position;
program->main_module = parse_module(program);
return program;
}
std::shared_ptr<ModuleNode> Parser::parse_module(std::shared_ptr<ProgramNode> program, bool is_main)
{
std::shared_ptr<ModuleNode> node = std::make_shared<ModuleNode>();
node->position = current_token.position;
node->unique_path = std::filesystem::absolute(node->position.file).generic_string();
while(current_token.type == Token::Type::NEWLINE)
{
advance();
}
while(current_token.type == Token::Type::KW_IMPORT)
{
bool is_success = parse_import(program, node);
errors.ignore_errors = false;
if(!is_success)
{
while(current_token.type != Token::Type::NEWLINE && current_token.type != Token::Type::TT_EOF)
{
advance();
}
}
uint32_t new_line_count = 0;
while(current_token.type == Token::Type::NEWLINE)
{
advance();
new_line_count++;
}
if(new_line_count == 0)
{
break;
}
}
node->statements = parse_statement_list();
return node;
}
bool Parser::parse_import(std::shared_ptr<ProgramNode> program, std::shared_ptr<ModuleNode> importer)
{
FilePosition import_position = current_token.position;
advance();
if(current_token.type != Token::Type::STRING_LITERAL)
{
errors.push_error(current_token.position, "Expected a string for the import file path.");
return false;
}
std::string raw_import_path = current_token.value.value();
std::filesystem::path import_path = importer->position.file;
import_path = import_path.parent_path();
import_path /= raw_import_path;
if(!std::filesystem::exists(import_path))
{
bool found = false;
for(const auto& search_path : flags.import_paths)
{
import_path = search_path;
import_path /= raw_import_path;
if(std::filesystem::exists(import_path))
{
found = true;
break;
}
}
if(!found)
{
errors.push_error(import_position, "Cannot import the file at this path as it could not be found.");
return false;
}
}
std::string import_path_string = std::filesystem::absolute(import_path).generic_string();
if(program->loaded_module_names.find(import_path_string)
!= program->loaded_module_names.end())
{
advance();
return true;
}
std::ifstream file;
file.open(import_path);
if(!file.is_open())
{
errors.push_error(import_position,
format::format("Could not open file '{0}'.", import_path.generic_string()));
advance();
return false;
}
std::stringstream file_text;
file_text << file.rdbuf();
file.close();
file_tokenizers.emplace_back(import_path.generic_string(), file_text.str());
advance();
if(current_token.type != Token::Type::KW_MODULE)
{
errors.push_error(current_token.position,
"File was imported but was not marked as a module. Add 'module' at the beginning to make it one.");
errors.push_error(import_position, "File imported is not a module.");
file_tokenizers.pop_back();
advance();
return false;
}
advance();
bool saved_is_decl_only = is_decl_only;
is_decl_only = true;
std::shared_ptr<ModuleNode> imported_module = parse_module(program);
is_decl_only = saved_is_decl_only;
file_tokenizers.pop_back();
advance();
program->loaded_modules.push_back(imported_module);
program->loaded_module_names.insert(import_path_string);
return true;
}
std::shared_ptr<StatementListNode> Parser::parse_statement_list()
{
std::shared_ptr<StatementListNode> node = std::make_shared<StatementListNode>();
node->position = current_token.position;
scope_level++;
while(current_token.type == Token::Type::NEWLINE)
{
advance();
}
while(current_token.type != Token::Type::TT_EOF
&& current_token.type != Token::Type::KW_ELIF
&& current_token.type != Token::Type::KW_ELSE
&& current_token.type != Token::Type::KW_END)
{
std::shared_ptr<Node> stmt = parse_statement();
errors.ignore_errors = false;
if(stmt == nullptr)
{
while(current_token.type != Token::Type::NEWLINE && current_token.type != Token::Type::TT_EOF)
{
advance();
}
}
else
{
node->statements.emplace_back(stmt);
}
uint32_t new_line_count = 0;
while(current_token.type == Token::Type::NEWLINE)
{
advance();
new_line_count++;
}
if(new_line_count == 0)
{
break;
}
}
scope_level--;
return node;
}
std::shared_ptr<Node> Parser::parse_statement()
{
switch(current_token.type)
{
case Token::Type::KW_CLASS:
return parse_class_statement();
case Token::Type::KW_TYPE:
return parse_type_alias();
case Token::Type::KW_WHILE:
return parse_while_statement();
case Token::Type::KW_IF:
return parse_if_statement();
case Token::Type::KW_EXTERN:
return parse_extern_func_statement();
case Token::Type::KW_FUNC:
return parse_func_statement();
case Token::Type::KW_RETURN:
return parse_return_statement();
case Token::Type::KW_CONTINUE:
return parse_continue_statement();
case Token::Type::KW_BREAK:
return parse_break_statement();
case Token::Type::KW_VAR:
return parse_var_statement(false);
case Token::Type::KW_CONST:
return parse_var_statement(true);
default:
break;
}
FilePosition expression_position = current_token.position;
std::shared_ptr<ExpressionNode> expr = parse_expression();
if(expr == nullptr)
{
errors.push_error(expression_position, "Expected a statement.");
return nullptr;
}
return expr;
}
std::shared_ptr<ClassNode> Parser::parse_class_statement()
{
if(scope_level != 1)
{
errors.push_error(current_token.position, "A class declaration is only allowed at the top level of a program.");
return nullptr;
}
std::shared_ptr<ClassNode> node = std::make_shared<ClassNode>();
node->position = current_token.position;
advance();
if(!expect_identifier()) return nullptr;
node->name = previous_token.value.value();
while(current_token.type == Token::Type::NEWLINE)
{
advance();
}
while(current_token.type != Token::Type::KW_END)
{
bool is_success = true;
switch(current_token.type)
{
case Token::Type::KW_VAR:
{
std::shared_ptr<VarNode> property = parse_var_statement(false);
if(property != nullptr)
{
node->properties.emplace_back(property);
}
else
{
is_success = false;
}
break;
}
case Token::Type::KW_CONST:
{
std::shared_ptr<VarNode> property = parse_var_statement(true);
if(property != nullptr)
{
node->properties.emplace_back(property);
}
else
{
is_success = false;
}
break;
}
case Token::Type::KW_FUNC:
{
std::shared_ptr<FuncNode> method = parse_func_statement();
if(method != nullptr)
{
node->methods.emplace_back(method);
}
else
{
is_success = false;
}
break;
}
default:
errors.push_error(current_token.position, "Expected a declaration.");
parse_statement(); // Parse whatever was provided anyways to prevent cascading errors
is_success = false;
}
errors.ignore_errors = false;
if(!is_success)
{
while(current_token.type != Token::Type::NEWLINE && current_token.type != Token::Type::TT_EOF)
{
advance();
}
}
uint32_t new_line_count = 0;
while(current_token.type == Token::Type::NEWLINE)
{
advance();
new_line_count++;
}
if(new_line_count == 0)
{
break;
}
}
if(!expect_ttype(Token::Type::KW_END, "Expected an 'end'.")) return nullptr;
return node;
}
std::shared_ptr<WhileNode> Parser::parse_while_statement()
{
std::shared_ptr<WhileNode> node = std::make_shared<WhileNode>();
node->position = current_token.position;
advance();
FilePosition condition_position = current_token.position;
node->condition = parse_expression();
if(!expect_expression(condition_position, node->condition)) return nullptr;
if(!expect_ttype(Token::Type::KW_DO, "Expected a 'do'.")) return nullptr;
node->statements = parse_statement_list();
if(!expect_ttype(Token::Type::KW_END, "Expected an 'end'.")) return nullptr;
return node;
}
std::shared_ptr<IfNode> Parser::parse_if_statement()
{
std::shared_ptr<IfNode> node = std::make_shared<IfNode>();
node->position = current_token.position;
do
{
advance();
IfNode::IfCaseInfo& if_case = node->if_cases.emplace_back();
if_case.position = current_token.position;
if_case.condition = parse_expression();
if(!expect_expression(if_case.position, if_case.condition)) return nullptr;
if(!expect_ttype(Token::Type::KW_THEN, "Expected a 'then'.")) return nullptr;
if_case.statements = parse_statement_list();
}
while(current_token.type == Token::Type::KW_ELIF);
if(current_token.type == Token::Type::KW_ELSE)
{
advance();
node->else_case = parse_statement_list();
}
if(!expect_ttype(Token::Type::KW_END, "Expected an 'end'.")) return nullptr;
return node;
}
std::shared_ptr<VarNode> Parser::parse_var_statement(bool is_readonly)
{
std::shared_ptr<VarNode> node = std::make_shared<VarNode>();
node->position = current_token.position;
node->is_readonly = is_readonly;
advance();
if(!expect_identifier()) return nullptr;
node->name = previous_token.value.value();
if(!expect_ttype(Token::Type::COLON, "Expected a ':'.")) return nullptr;
if(!expect_type_no_void(node->type_annotation)) return nullptr;
if(current_token.type != Token::Type::ASSIGN)
{
node->initial_value = nullptr;
return node;
}
advance();
FilePosition expression_position = current_token.position;
node->initial_value = parse_expression();
if(!expect_expression(expression_position, node->initial_value)) return nullptr;
return node;
}
bool Parser::parse_function_parameter(FuncParamInfo& info, bool is_lambda)
{
if(!expect_identifier()) return false;
info.label = previous_token.value.value();
info.position = previous_token.position;
if(current_token.type == Token::Type::IDENTIFIER)
{
if(is_lambda)
{
errors.push_error(info.position, "Argument labels cannot be used in lambda functions.");
return false;
}
advance();
info.name = previous_token.value.value();
}
else
{
info.name = info.label;
}
if(!expect_ttype(Token::Type::COLON, "Expected a ':'.")) return false;
if(!expect_type(info.type_annotation)) return false;
return true;
}
bool Parser::parse_function_header(std::string& name, std::string& return_type,
std::vector<wf::FuncParamInfo>& parameters, bool is_lambda)
{
if(is_lambda)
{
if(current_token.type == Token::Type::IDENTIFIER)
{
errors.push_error(current_token.position, "A lambda function cannot include a function name.");
return false;
}
}
else
{
if(!expect_identifier()) return false;
}
name = previous_token.value.value();
if(current_token.type == Token::Type::PAREN_OPEN)
{
push_newline_ignore(true);
}
if(!expect_ttype(Token::Type::PAREN_OPEN, "Expected a '('.")) return false;
FilePosition paren_pos = previous_token.position;
if(current_token.type != Token::Type::PAREN_CLOSE)
{
if(!parse_function_parameter(parameters.emplace_back(), is_lambda))
{
pop_newline_ignore();
return false;
}
while(current_token.type == Token::Type::COMMA)
{
advance();
if(!parse_function_parameter(parameters.emplace_back(), is_lambda))
{
pop_newline_ignore();
return false;
}
}
}
if(current_token.type != Token::Type::PAREN_CLOSE)
{
errors.push_error(current_token.position,
format::format("Expected a closing ')' for the opening '(' at (ln: {0}, col: {1}).",
paren_pos.line, paren_pos.column));
pop_newline_ignore();
return false;
}
pop_newline_ignore();
advance();
if(!expect_ttype(Token::Type::ARROW, "Expected a '->'.")) return false;
if(!expect_type(return_type)) return false;
return true;
}
std::shared_ptr<ExternFuncNode> Parser::parse_extern_func_statement()
{
std::shared_ptr<ExternFuncNode> node = std::make_shared<ExternFuncNode>();
node->position = current_token.position;
advance();
if(!parse_function_header(node->name, node->return_type_annotation, node->parameters)) return nullptr;
return node;
}
std::shared_ptr<FuncNode> Parser::parse_func_statement()
{
std::shared_ptr<FuncNode> node = std::make_shared<FuncNode>();
node->position = current_token.position;
advance();
if(!parse_function_header(node->name, node->return_type_annotation, node->parameters)) return nullptr;
node->statements = parse_statement_list();
if(!expect_ttype(Token::Type::KW_END, "Expected an 'end'.")) return nullptr;
return node;
}
std::shared_ptr<ReturnNode> Parser::parse_return_statement()
{
std::shared_ptr<ReturnNode> node = std::make_shared<ReturnNode>();
node->position = current_token.position;
advance();
if(current_token.type == Token::Type::KW_RETURN)
{
return node;
}
FilePosition expression_position = current_token.position;
node->value = parse_expression();
if(!expect_expression(expression_position, node->value)) return nullptr;
return node;
}
std::shared_ptr<ContinueNode> Parser::parse_continue_statement()
{
std::shared_ptr<ContinueNode> node = std::make_shared<ContinueNode>();
node->position = current_token.position;
advance();
return node;
}
std::shared_ptr<BreakNode> Parser::parse_break_statement()
{
std::shared_ptr<BreakNode> node = std::make_shared<BreakNode>();
node->position = current_token.position;
advance();
return node;
}
std::shared_ptr<TypeAliasNode> Parser::parse_type_alias()
{
std::shared_ptr<TypeAliasNode> node = std::make_shared<TypeAliasNode>();
node->position = current_token.position;
advance();
if(!expect_identifier()) return nullptr;
node->alias = previous_token.value.value();
if(!expect_ttype(Token::Type::ASSIGN, "Expected a ':='.")) return nullptr;
if(!expect_type_no_void(node->aliased_type_string)) return nullptr;
return node;
}
std::shared_ptr<ExpressionNode> Parser::parse_expression()
{
return parse_expression_with_precedence(PREC_ASSIGN);
}
std::shared_ptr<ExpressionNode> Parser::parse_expression_with_precedence(ExprPrecedence precedence)
{
PrefixParseFunc prefix_func = get_rule(current_token.type).prefix;
if(prefix_func == nullptr)
{
return nullptr;
}
std::shared_ptr<ExpressionNode> prev = (this->*prefix_func)();
if(prev == nullptr)
{
return nullptr;
}
if(get_rule(current_token.type).infix == nullptr)
{
return prev;
}
while(precedence <= get_rule(current_token.type).precedence)
{
InfixParseFunc infix_func = get_rule(current_token.type).infix;
prev = (this->*infix_func)(prev);
if(prev == nullptr)
{
return nullptr;
}
}
return prev;
}
std::shared_ptr<ExpressionNode> Parser::parse_assignment(std::shared_ptr<ExpressionNode> prev)
{
if(prev->type != Node::Type::SYM_ACCESS && prev->type != Node::Type::MEMBER_ACCESS)
{
errors.push_error(current_token.position, "Can only assign to variables and member access. ");
return nullptr;
}
std::shared_ptr<AssignNode> node = std::make_shared<AssignNode>();
node->position = current_token.position;
node->assignee = prev;
advance();
FilePosition expression_position;
node->new_value = parse_expression();
if(!expect_expression(expression_position, node->new_value)) return nullptr;
return node;
}
std::shared_ptr<ExpressionNode> Parser::parse_call(std::shared_ptr<ExpressionNode> prev)
{
std::shared_ptr<CallNode> node = std::make_shared<CallNode>();
node->position = current_token.position;
node->callee = prev;
Tokenizer::RewindInfo arg_rewind = get_tokenizer().get_current_rewind_info();
advance();
if(current_token.type != Token::Type::PAREN_CLOSE)
{
do
{
FilePosition expression_position;
CallNode::ArgInfo& info = node->arguments.emplace_back();
advance();
if(current_token.type != Token::Type::COLON)
{
rewind(arg_rewind);
expression_position = current_token.position;
info.position = previous_token.position;
info.value = parse_expression();
if(!expect_expression(expression_position, info.value)) return nullptr;
arg_rewind = get_tokenizer().get_current_rewind_info();
advance();
continue;
}
rewind(arg_rewind);
if(!expect_identifier()) return nullptr;
info.position = previous_token.position;
info.label = previous_token.value.value();
if(!expect_ttype(Token::Type::COLON, "Expected a ':'.")) return nullptr;
expression_position = current_token.position;
info.value = parse_expression();
if(!expect_expression(expression_position, info.value)) return nullptr;
arg_rewind = get_tokenizer().get_current_rewind_info();
advance();
}
while(previous_token.type == Token::Type::COMMA);
rewind(arg_rewind);
}
else
{
advance();
}
if(previous_token.type != Token::Type::PAREN_CLOSE)
{
errors.push_error(current_token.position,
format::format("Expected a closing ')' for the opening '(' at (ln: {0}, col: {1}).",
node->position.line, node->position.column));
return nullptr;
}
return node;
}
std::shared_ptr<ExpressionNode> Parser::parse_binary_op(std::shared_ptr<ExpressionNode> prev)
{
Token op_tok = current_token;
advance();
std::shared_ptr<BinaryOpNode> node = std::make_shared<BinaryOpNode>();
node->position = op_tok.position;
node->left_operand = prev;
ExprPrecedence precedence = static_cast<ExprPrecedence>(get_rule(op_tok.type).precedence + 1);
FilePosition right_pos = current_token.position;
node->right_operand = parse_expression_with_precedence(precedence);
if(!expect_expression(right_pos, node->right_operand)) return nullptr;
switch(op_tok.type)
{
case Token::Type::PLUS:
node->operation = BinaryOpNode::OpType::ADD;
break;
case Token::Type::MINUS:
node->operation = BinaryOpNode::OpType::SUB;
break;
case Token::Type::MUL:
node->operation = BinaryOpNode::OpType::MUL;
break;
case Token::Type::DIV:
node->operation = BinaryOpNode::OpType::DIV;
break;
case Token::Type::MOD:
node->operation = BinaryOpNode::OpType::MOD;
break;
case Token::Type::EQ:
node->operation = BinaryOpNode::OpType::EQ;
break;
case Token::Type::NEQ:
node->operation = BinaryOpNode::OpType::NEQ;
break;
case Token::Type::LT:
node->operation = BinaryOpNode::OpType::LT;
break;
case Token::Type::GT:
node->operation = BinaryOpNode::OpType::GT;
break;
case Token::Type::LTE:
node->operation = BinaryOpNode::OpType::LTE;
break;
case Token::Type::GTE:
node->operation = BinaryOpNode::OpType::GTE;
break;
case Token::Type::KW_OR:
node->operation = BinaryOpNode::OpType::OR;
break;
case Token::Type::KW_AND:
node->operation = BinaryOpNode::OpType::AND;
break;
default:
return nullptr; // Unreachable
}
return node;
}
std::shared_ptr<ExpressionNode> Parser::parse_unary_op()
{
std::shared_ptr<UnaryOpNode> node = std::make_shared<UnaryOpNode>();
node->position = current_token.position;
ExprPrecedence precedence;
switch(current_token.type)
{
case Token::Type::MINUS:
precedence = PREC_SIGN;
node->operation = UnaryOpNode::OpType::NEGATION;
break;
case Token::Type::BIT_NOT:
precedence = PREC_SIGN;
node->operation = UnaryOpNode::OpType::BIT_NOT;
break;
case Token::Type::KW_NOT:
precedence = PREC_NOT_EXPR;
node->operation = UnaryOpNode::OpType::NOT;
break;
default:
return nullptr; // Unreachable.
}
advance();
FilePosition operand_position = current_token.position;
node->operand = parse_expression_with_precedence(precedence);
if(!expect_expression(operand_position, node->operand)) return nullptr;
return node;
}
std::shared_ptr<ExpressionNode> Parser::parse_primary()
{
advance();
switch(previous_token.type)
{
case Token::Type::IDENTIFIER:
{
std::shared_ptr<SymAccessNode> node = std::make_shared<SymAccessNode>();
node->sym_name = previous_token.value.value();
node->position = previous_token.position;
return node;
}
case Token::Type::STRING_LITERAL:
{
std::shared_ptr<StringNode> node = std::make_shared<StringNode>();
node->value = previous_token.value.value();
node->position = previous_token.position;
return node;
}
case Token::Type::INT_LITERAL:
{
std::shared_ptr<IntNode> node = std::make_shared<IntNode>();
node->value = std::stoll(previous_token.value.value());
node->position = previous_token.position;
return node;
}
case Token::Type::FLOAT_LITERAL:
{
std::shared_ptr<FloatNode> node = std::make_shared<FloatNode>();
node->value = std::stod(previous_token.value.value());
node->position = previous_token.position;
return node;
}
case Token::Type::KW_FALSE:
case Token::Type::KW_TRUE:
{
std::shared_ptr<BoolNode> node = std::make_shared<BoolNode>();
node->value = previous_token.type == Token::Type::KW_TRUE? true : false;
node->position = previous_token.position;
return node;
}
case Token::Type::KW_NIL:
{
std::shared_ptr<NilNode> node = std::make_shared<NilNode>();
node->position = previous_token.position;
return node;
}
default:
break;
}
return nullptr; // Unreachable
}
std::shared_ptr<ExpressionNode> Parser::parse_grouping()
{
FilePosition paren_pos = current_token.position;
push_newline_ignore(true);
advance();
FilePosition expr_position = current_token.position;
std::shared_ptr<ExpressionNode> expr = parse_expression();
pop_newline_ignore();
if(!expect_expression(expr_position, expr)) return nullptr;
if(current_token.type != Token::Type::PAREN_CLOSE)
{
errors.push_error(current_token.position,
format::format("Expected a closing ')' for the opening '(' at (ln: {0}, col: {1}).",
paren_pos.line, paren_pos.column));
return nullptr;
}
advance();
return expr;
}
std::shared_ptr<ExpressionNode> Parser::parse_lambda()
{
std::shared_ptr<LambdaNode> node = std::make_shared<LambdaNode>();
node->position = current_token.position;
advance();
std::string unused_name;
if(!parse_function_header(unused_name, node->return_type_annotation, node->parameters, true)) return nullptr;
node->statements = parse_statement_list();
if(!expect_ttype(Token::Type::KW_END, "Expected an 'end'.")) return nullptr;
return node;
}
std::shared_ptr<ExpressionNode> Parser::parse_cast(std::shared_ptr<ExpressionNode> prev)
{
std::shared_ptr<CastNode> node = std::make_shared<CastNode>();
node->position = current_token.position;
node->operand = prev;
advance();
if(!expect_type_no_void(node->cast_type_string)) return nullptr;
return node;
}
std::shared_ptr<ExpressionNode> Parser::parse_property_access(std::shared_ptr<ExpressionNode> prev)
{
std::shared_ptr<MemberAccessNode> node = std::make_shared<MemberAccessNode>();
node->position = current_token.position;
node->base = prev;
advance();
if(!expect_identifier()) return nullptr;
node->member_name = previous_token.value.value();
return node;
}
const Parser::ParseRule& Parser::get_rule(Token::Type ttype)
{
static std::unordered_map<Token::Type, ParseRule> rules = {
// Prefix Infix Precedence
{ Token::Type::STRING_LITERAL, { &Parser::parse_primary, nullptr, ExprPrecedence::PREC_NONE }},
{ Token::Type::INT_LITERAL, { &Parser::parse_primary, nullptr, ExprPrecedence::PREC_NONE }},
{ Token::Type::FLOAT_LITERAL, { &Parser::parse_primary, nullptr, ExprPrecedence::PREC_NONE }},
{ Token::Type::KW_FALSE, { &Parser::parse_primary, nullptr, ExprPrecedence::PREC_NONE }},
{ Token::Type::KW_TRUE, { &Parser::parse_primary, nullptr, ExprPrecedence::PREC_NONE }},
{ Token::Type::KW_NIL, { &Parser::parse_primary, nullptr, ExprPrecedence::PREC_NONE }},
{ Token::Type::IDENTIFIER, { &Parser::parse_primary, nullptr, ExprPrecedence::PREC_NONE }},
{ Token::Type::KW_FUNC, { &Parser::parse_lambda, nullptr, ExprPrecedence::PREC_NONE }},
{ Token::Type::PAREN_OPEN, { &Parser::parse_grouping, &Parser::parse_call, ExprPrecedence::PREC_CALL }},
{ Token::Type::KW_AS, { nullptr, &Parser::parse_cast, ExprPrecedence::PREC_CAST }},
{ Token::Type::DOT, { nullptr, &Parser::parse_property_access, ExprPrecedence::PREC_CALL }},
{ Token::Type::PLUS, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_ADD_EXPR }},
{ Token::Type::MINUS, { &Parser::parse_unary_op, &Parser::parse_binary_op, ExprPrecedence::PREC_ADD_EXPR }},
{ Token::Type::MUL, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_MUL_EXPR }},
{ Token::Type::DIV, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_MUL_EXPR }},
{ Token::Type::MOD, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_MUL_EXPR }},
{ Token::Type::ASSIGN, { nullptr, &Parser::parse_assignment, ExprPrecedence::PREC_ASSIGN }},
{ Token::Type::KW_NOT, { &Parser::parse_unary_op, nullptr, ExprPrecedence::PREC_NONE }},
{ Token::Type::KW_AND, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_AND_EXPR }},
{ Token::Type::KW_OR, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_OR_EXPR }},
{ Token::Type::EQ, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_COMP_EXPR }},
{ Token::Type::NEQ, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_COMP_EXPR }},
{ Token::Type::LT, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_COMP_EXPR }},
{ Token::Type::GT, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_COMP_EXPR }},
{ Token::Type::LTE, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_COMP_EXPR }},
{ Token::Type::GTE, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_COMP_EXPR }},
{ Token::Type::BIT_NOT, { &Parser::parse_unary_op, nullptr, ExprPrecedence::PREC_NONE }},
{ Token::Type::BIT_AND, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_BIT_AND }},
{ Token::Type::BIT_XOR, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_BIT_XOR }},
{ Token::Type::BIT_OR, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_BIT_OR }},
{ Token::Type::SHIFT_LEFT, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_BIT_SHIFT }},
{ Token::Type::SHIFT_RIGHT, { nullptr, &Parser::parse_binary_op, ExprPrecedence::PREC_BIT_SHIFT }},
};
return rules[ttype];
}
} // namespace wf
| 37.462443 | 143 | 0.539472 | Ornibyl |
fec60c1c51ff507952693ab094918b9d62e0aa09 | 4,506 | cpp | C++ | WildMagic4/LibFoundation/Distance/Wm4DistRay3Rectangle3.cpp | rms80/libgeometry | e60ec7d34968573a9cda3f3bf56d2d4717385dc9 | [
"BSL-1.0"
] | 23 | 2015-08-13T07:36:00.000Z | 2022-01-24T19:00:04.000Z | WildMagic4/LibFoundation/Distance/Wm4DistRay3Rectangle3.cpp | rms80/libgeometry | e60ec7d34968573a9cda3f3bf56d2d4717385dc9 | [
"BSL-1.0"
] | null | null | null | WildMagic4/LibFoundation/Distance/Wm4DistRay3Rectangle3.cpp | rms80/libgeometry | e60ec7d34968573a9cda3f3bf56d2d4717385dc9 | [
"BSL-1.0"
] | 6 | 2015-07-06T21:37:31.000Z | 2020-07-01T04:07:50.000Z | // Geometric Tools, LLC
// Copyright (c) 1998-2010
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 4.10.0 (2009/11/18)
#include "Wm4FoundationPCH.h"
#include "Wm4DistRay3Rectangle3.h"
#include "Wm4DistLine3Rectangle3.h"
#include "Wm4DistVector3Rectangle3.h"
namespace Wm4
{
//----------------------------------------------------------------------------
template <class Real>
DistRay3Rectangle3<Real>::DistRay3Rectangle3 (const Ray3<Real>& rkRay,
const Rectangle3<Real>& rkRectangle)
:
m_pkRay(&rkRay),
m_pkRectangle(&rkRectangle)
{
}
//----------------------------------------------------------------------------
template <class Real>
const Ray3<Real>& DistRay3Rectangle3<Real>::GetRay () const
{
return *m_pkRay;
}
//----------------------------------------------------------------------------
template <class Real>
const Rectangle3<Real>& DistRay3Rectangle3<Real>::GetRectangle () const
{
return *m_pkRectangle;
}
//----------------------------------------------------------------------------
template <class Real>
Real DistRay3Rectangle3<Real>::Get ()
{
Real fSqrDist = GetSquared();
return Math<Real>::Sqrt(fSqrDist);
}
//----------------------------------------------------------------------------
template <class Real>
Real DistRay3Rectangle3<Real>::GetSquared ()
{
DistLine3Rectangle3<Real> kLRDist(Line3<Real>(m_pkRay->Origin,
m_pkRay->Direction),*m_pkRectangle);
Real fSqrDist = kLRDist.GetSquared();
m_fRayParameter = kLRDist.GetLineParameter();
if (m_fRayParameter >= (Real)0.0)
{
m_kClosestPoint0 = kLRDist.GetClosestPoint0();
m_kClosestPoint1 = kLRDist.GetClosestPoint1();
m_afRectCoord[0] = kLRDist.GetRectangleCoordinate(0);
m_afRectCoord[1] = kLRDist.GetRectangleCoordinate(1);
}
else
{
m_kClosestPoint0 = m_pkRay->Origin;
DistVector3Rectangle3<Real> kVRDist(m_kClosestPoint0,*m_pkRectangle);
fSqrDist = kVRDist.GetSquared();
m_kClosestPoint1 = kVRDist.GetClosestPoint1();
m_fRayParameter = (Real)0.0;
m_afRectCoord[0] = kVRDist.GetRectangleCoordinate(0);
m_afRectCoord[1] = kVRDist.GetRectangleCoordinate(1);
}
return fSqrDist;
}
//----------------------------------------------------------------------------
template <class Real>
Real DistRay3Rectangle3<Real>::Get (Real fT,
const Vector3<Real>& rkVelocity0, const Vector3<Real>& rkVelocity1)
{
Vector3<Real> kMOrigin = m_pkRay->Origin + fT*rkVelocity0;
Vector3<Real> kMCenter = m_pkRectangle->Center + fT*rkVelocity1;
Ray3<Real> kMRay(kMOrigin,m_pkRay->Direction);
Rectangle3<Real> kMRectangle(kMCenter,m_pkRectangle->Axis,
m_pkRectangle->Extent);
return DistRay3Rectangle3<Real>(kMRay,kMRectangle).Get();
}
//----------------------------------------------------------------------------
template <class Real>
Real DistRay3Rectangle3<Real>::GetSquared (Real fT,
const Vector3<Real>& rkVelocity0, const Vector3<Real>& rkVelocity1)
{
Vector3<Real> kMOrigin = m_pkRay->Origin + fT*rkVelocity0;
Vector3<Real> kMCenter = m_pkRectangle->Center + fT*rkVelocity1;
Ray3<Real> kMRay(kMOrigin,m_pkRay->Direction);
Rectangle3<Real> kMRectangle(kMCenter,m_pkRectangle->Axis,
m_pkRectangle->Extent);
return DistRay3Rectangle3<Real>(kMRay,kMRectangle).GetSquared();
}
//----------------------------------------------------------------------------
template <class Real>
Real DistRay3Rectangle3<Real>::GetRayParameter () const
{
return m_fRayParameter;
}
//----------------------------------------------------------------------------
template <class Real>
Real DistRay3Rectangle3<Real>::GetRectangleCoordinate (int i) const
{
assert(0 <= i && i < 2);
return m_afRectCoord[i];
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
template WM4_FOUNDATION_ITEM
class DistRay3Rectangle3<float>;
template WM4_FOUNDATION_ITEM
class DistRay3Rectangle3<double>;
//----------------------------------------------------------------------------
}
| 36.934426 | 79 | 0.539725 | rms80 |
fec6a68842029b15ba5131daa40bf88c69cc60f1 | 3,837 | cpp | C++ | test/src/core/reactor_echo.cpp | chensoft/libxio | 17345e500cca5085641b5392ce8ef7dc65369d69 | [
"MIT"
] | 6 | 2018-07-28T08:03:24.000Z | 2022-03-31T08:56:57.000Z | test/src/core/reactor_echo.cpp | chensoft/libxio | 17345e500cca5085641b5392ce8ef7dc65369d69 | [
"MIT"
] | null | null | null | test/src/core/reactor_echo.cpp | chensoft/libxio | 17345e500cca5085641b5392ce8ef7dc65369d69 | [
"MIT"
] | 2 | 2019-05-21T02:26:36.000Z | 2020-04-13T16:46:20.000Z | /**
* Created by Jian Chen
* @since 2016.12.29
* @author Jian Chen <admin@chensoft.com>
* @link http://chensoft.com
*/
#include "socket/inet/inet_address.hpp"
#include "socket/base/basic_socket.hpp"
#include "socket/core/reactor.hpp"
#include "chen/mt/threadpool.hpp"
#include "gtest/gtest.h"
using chen::reactor;
using chen::ev_base;
using chen::inet_address;
using chen::basic_socket;
void server_thread(basic_socket &s);
void client_thread(inet_address a);
TEST(CoreReactorTest, Echo)
{
// server
basic_socket s(AF_INET, SOCK_STREAM);
EXPECT_TRUE(!s.bind(inet_address("127.0.0.1:0"))); // bind on a random port
EXPECT_TRUE(!s.listen());
std::thread t_server(std::bind(&server_thread, std::ref(s)));
// client
std::thread t_client(std::bind(&client_thread, s.sock<inet_address>()));
t_server.join();
t_client.join();
}
void server_thread(basic_socket &s)
{
using namespace std::placeholders;
std::vector<std::unique_ptr<basic_socket>> cache;
reactor r;
auto handler_connection = [&](basic_socket *conn, int type) {
// you should read the rest of the data even if you received the closed event
EXPECT_TRUE((type & ev_base::Readable) || (type & ev_base::Closed));
// read data from client
auto size = conn->available();
EXPECT_GE(size, 0u);
if (!size)
return; // connection closed
std::string text(size, '\0');
EXPECT_EQ((chen::ssize_t)size, conn->recv(&text[0], size));
// need stop the reactor?
if (text == "stop")
return r.stop();
// revert and send back
std::reverse(text.begin(), text.end());
EXPECT_EQ((chen::ssize_t)size, conn->send(text.data(), size));
};
auto handler_server = [&](int type) {
EXPECT_GT(type & ev_base::Readable, 0);
// accept new connection
std::unique_ptr<basic_socket> conn(new basic_socket);
EXPECT_TRUE(!s.accept(*conn));
conn->attach(std::bind(handler_connection, conn.get(), _1));
cache.emplace_back(std::move(conn)); // prevent connection released
// register event for conn
r.set(cache.back().get(), reactor::ModeRead, 0);
};
s.attach(handler_server);
r.set(&s, reactor::ModeRead, 0);
r.run();
}
void client_thread(inet_address a)
{
// send each message to server, server
// will invert the string and send back
std::vector<std::string> data = {
"You say that you love rain",
"but you open your umbrella when it rains",
"You say that you love the sun",
"but you find a shadow spot when the sun shines",
"You say that you love the wind",
"But you close your windows when wind blows",
"This is why I am afraid",
"You say that you love me too",
};
// spawn many clients to exchange data with server
std::unique_ptr<chen::threadpool> pool(new chen::threadpool);
for (std::size_t i = 0, l = data.size(); i < l; ++i)
{
pool->post([&data, a, i] () {
auto text = data[i % data.size()];
basic_socket c(AF_INET, SOCK_STREAM);
EXPECT_TRUE(!c.connect(a));
EXPECT_EQ((chen::ssize_t)text.size(), c.send(text.data(), text.size()));
std::string response(text.size(), '\0');
std::string reverse(text.rbegin(), text.rend());
EXPECT_EQ((chen::ssize_t)text.size(), c.recv(&response[0], text.size()));
EXPECT_EQ(reverse, response); // the server will inverts the string
});
}
// destroy the thread pool
pool.reset();
// tell the server to quit
basic_socket c(AF_INET, SOCK_STREAM);
EXPECT_TRUE(!c.connect(a));
EXPECT_EQ(4, c.send("stop", 4));
} | 28.849624 | 85 | 0.604639 | chensoft |
fec6faad68b85e3553fb0bc98ac8f15626f2bb91 | 4,847 | cpp | C++ | plugins/qm-dsp/dsp/chromagram/Chromagram.cpp | horstsoft0815/qlcplus | 249da9d165630b89fe9fbb0796d892c992645709 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | plugins/qm-dsp/dsp/chromagram/Chromagram.cpp | horstsoft0815/qlcplus | 249da9d165630b89fe9fbb0796d892c992645709 | [
"ECL-2.0",
"Apache-2.0"
] | 8 | 2021-11-14T16:31:59.000Z | 2021-12-11T19:53:10.000Z | plugins/qm-dsp/dsp/chromagram/Chromagram.cpp | horstsoft0815/qlcplus | 249da9d165630b89fe9fbb0796d892c992645709 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
/*
QM DSP Library
Centre for Digital Music, Queen Mary, University of London.
This file 2005-2006 Christian Landone.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version. See the file
COPYING included with this distribution for more information.
*/
#include <iostream>
#include <cmath>
#include "maths/MathUtilities.h"
#include "Chromagram.h"
//----------------------------------------------------------------------------
Chromagram::Chromagram( ChromaConfig Config ) :
m_skGenerated(false)
{
initialise( Config );
}
int Chromagram::initialise( ChromaConfig Config )
{
m_FMin = Config.min; // min freq
m_FMax = Config.max; // max freq
m_BPO = Config.BPO; // bins per octave
m_normalise = Config.normalise; // if frame normalisation is required
// Extend range to a full octave
double octaves = log(m_FMax / m_FMin) / log(2.0);
m_FMax = m_FMin * pow(2.0, ceil(octaves));
// Create array for chroma result
m_chromadata = new double[ m_BPO ];
// Create Config Structure for ConstantQ operator
CQConfig ConstantQConfig;
// Populate CQ config structure with parameters
// inherited from the Chroma config
ConstantQConfig.FS = Config.FS;
ConstantQConfig.min = m_FMin;
ConstantQConfig.max = m_FMax;
ConstantQConfig.BPO = m_BPO;
ConstantQConfig.CQThresh = Config.CQThresh;
// Initialise ConstantQ operator
m_ConstantQ = new ConstantQ( ConstantQConfig );
// No. of constant Q bins
m_uK = m_ConstantQ->getK();
// Initialise working arrays
m_frameSize = m_ConstantQ->getFFTLength();
m_hopSize = m_ConstantQ->getHop();
// Initialise FFT object
m_FFT = new FFTReal(m_frameSize);
m_FFTRe = new double[ m_frameSize ];
m_FFTIm = new double[ m_frameSize ];
m_CQRe = new double[ m_uK ];
m_CQIm = new double[ m_uK ];
m_window = 0;
m_windowbuf = 0;
return 1;
}
Chromagram::~Chromagram()
{
deInitialise();
}
int Chromagram::deInitialise()
{
delete[] m_windowbuf;
delete m_window;
delete [] m_chromadata;
delete m_FFT;
delete m_ConstantQ;
delete [] m_FFTRe;
delete [] m_FFTIm;
delete [] m_CQRe;
delete [] m_CQIm;
return 1;
}
//----------------------------------------------------------------------------------
// returns the absolute value of complex number xx + i*yy
double Chromagram::kabs(double xx, double yy)
{
double ab = sqrt(xx*xx + yy*yy);
return(ab);
}
//-----------------------------------------------------------------------------------
void Chromagram::unityNormalise(double *src)
{
double min, max;
double val = 0;
MathUtilities::getFrameMinMax( src, m_BPO, & min, &max );
for (int i = 0; i < m_BPO; i++) {
val = src[ i ] / max;
src[ i ] = val;
}
}
double *Chromagram::process(const double *data)
{
if (!m_skGenerated) {
// Generate CQ Kernel
m_ConstantQ->sparsekernel();
m_skGenerated = true;
}
if (!m_window) {
m_window = new Window<double>(HammingWindow, m_frameSize);
m_windowbuf = new double[m_frameSize];
}
for (int i = 0; i < m_frameSize; ++i) {
m_windowbuf[i] = data[i];
}
m_window->cut(m_windowbuf);
// The frequency-domain version expects pre-fftshifted input - so
// we must do the same here
for (int i = 0; i < m_frameSize/2; ++i) {
double tmp = m_windowbuf[i];
m_windowbuf[i] = m_windowbuf[i + m_frameSize/2];
m_windowbuf[i + m_frameSize/2] = tmp;
}
m_FFT->forward(m_windowbuf, m_FFTRe, m_FFTIm);
return process(m_FFTRe, m_FFTIm);
}
double *Chromagram::process(const double *real, const double *imag)
{
if (!m_skGenerated) {
// Generate CQ Kernel
m_ConstantQ->sparsekernel();
m_skGenerated = true;
}
// initialise chromadata to 0
for (int i = 0; i < m_BPO; i++) m_chromadata[i] = 0;
// Calculate ConstantQ frame
m_ConstantQ->process( real, imag, m_CQRe, m_CQIm );
// add each octave of cq data into Chromagram
const int octaves = m_uK / m_BPO;
for (int octave = 0; octave < octaves; octave++) {
int firstBin = octave*m_BPO;
for (int i = 0; i < m_BPO; i++) {
m_chromadata[i] += kabs( m_CQRe[ firstBin + i ],
m_CQIm[ firstBin + i ]);
}
}
MathUtilities::normalise(m_chromadata, m_BPO, m_normalise);
return m_chromadata;
}
| 26.2 | 85 | 0.590262 | horstsoft0815 |
fecaa3df6196c16688993c11106071a5d8446bd5 | 1,276 | cpp | C++ | apps/test_typeid_name.cpp | mxgrey/sandbox | 6f3c316702a47053499222dbf293efe6c1f43f0c | [
"BSD-3-Clause"
] | null | null | null | apps/test_typeid_name.cpp | mxgrey/sandbox | 6f3c316702a47053499222dbf293efe6c1f43f0c | [
"BSD-3-Clause"
] | null | null | null | apps/test_typeid_name.cpp | mxgrey/sandbox | 6f3c316702a47053499222dbf293efe6c1f43f0c | [
"BSD-3-Clause"
] | null | null | null |
#include <iostream>
#include <typeinfo>
#include <cxxabi.h>
namespace space {
template<typename T>
class SomeClass
{
};
namespace nam {
class Huff
{
};
inline namespace ill_one
{
class VersionedClass
{
};
} // inline namespace ill_one
inline namespace ill_two
{
class VersionedClass
{
};
} // inline namespace ill_two
} // namespace nam
} // namespace space
using namespace space;
using namespace nam;
template<typename T>
class Foo
{
};
class Bar
{
};
#define PRINT(x) \
std::cout << #x << ": " << typeid(x).name() << std::endl;
int main()
{
PRINT(Huff);
PRINT(SomeClass<Huff>);
PRINT(Foo<Huff>);
PRINT(SomeClass<Foo<Huff>>);
PRINT(Bar);
PRINT(SomeClass<Bar>);
PRINT(Foo<Bar>);
PRINT(SomeClass<Foo<SomeClass<SomeClass<SomeClass<Foo<Bar>>>>>>);
PRINT(int);
PRINT(SomeClass<int>);
PRINT(ill_one::VersionedClass);
// using LongName = SomeClass<Foo<SomeClass<SomeClass<SomeClass<Foo<Bar>>>>>>;
int status;
char* demangled_cstr = abi::__cxa_demangle(
// typeid(LongName).name(), nullptr, nullptr, &status);
typeid(ill_two::VersionedClass).name(), nullptr, nullptr, &status);
const std::string demangled(demangled_cstr);
free(demangled_cstr);
std::cout << "Demangled: " << demangled << std::endl;
}
| 13.869565 | 79 | 0.666928 | mxgrey |
fecab7843b5a5ce5e5286b991cc73b09d26f16b2 | 3,286 | cpp | C++ | TxtMiruFunc2/TxtFuncBookmarkSqlite3/PictRendererMgr.cpp | gearsns/TxtMiru2 | f829803721354e0639e791ba63962bd702aebfd1 | [
"MIT"
] | 5 | 2019-09-28T09:41:24.000Z | 2020-08-28T07:38:32.000Z | TxtMiruFunc2/TxtFuncBookmarkSqlite3/PictRendererMgr.cpp | gearsns/TxtMiru2 | f829803721354e0639e791ba63962bd702aebfd1 | [
"MIT"
] | null | null | null | TxtMiruFunc2/TxtFuncBookmarkSqlite3/PictRendererMgr.cpp | gearsns/TxtMiru2 | f829803721354e0639e791ba63962bd702aebfd1 | [
"MIT"
] | null | null | null | #pragma warning( disable : 4786 )
#include <windows.h>
#include <windowsx.h>
#include <commctrl.h>
#include "PictRendererMgr.h"
#include "stltchar.h"
#include "Image.h"
#include "TxtFunc.h"
#include "TxtFuncIParam.h"
#include "Shell.h"
CGrPictRendererMgr::CGrPictRendererMgr()
{
memset(m_pictRendererMap, 0x00, sizeof(m_pictRendererMap));
}
CGrPictRendererMgr::~CGrPictRendererMgr()
{
Clear();
}
void CGrPictRendererMgr::Clear()
{
auto *p = m_pictRendererMap;
for(int len=static_cast<int>(PictRenderType::MaxNum); len>0; --len, ++p){
if(*p){ delete *p; }
*p = nullptr;
}
m_curPictRenderer = nullptr;
m_filename = _T("");
}
void CGrPictRendererMgr::Initialize()
{
Clear();
auto &¶m = CGrTxtFunc::Param();
m_pictRendererMap[static_cast<int>(PictRenderType::Spi)] = new CGrPictSPIRenderer();
m_pictRendererMap[static_cast<int>(PictRenderType::Ole)] = new CGrPictOleRenderer();
m_pictRendererMap[static_cast<int>(PictRenderType::Emf)] = new CGrPictEmfRenderer();
TCHAR dir[_MAX_PATH] = {};
param.GetText(CGrTxtFuncIParam::TextType::SpiPluginFolder, dir, sizeof(dir)/sizeof(TCHAR));
m_pictRendererMap[static_cast<int>(PictRenderType::Spi)]->SetParam(_T("PluginDir"), dir);
auto *p = m_pictRendererMap;
for(int len= static_cast<int>(PictRenderType::MaxNum); len>0; --len, ++p){
if(*p){
(*p)->SetParam(_T("CurDir"), _T("."));
(*p)->SetParam(_T("DataDir"), CGrTxtFunc::GetDataPath());
}
}
}
CGrPictRenderer *CGrPictRendererMgr::getPictRenderer(LPCTSTR lpFileName)
{
if(m_curPictRenderer && m_filename == lpFileName){
return m_curPictRenderer;
}
if(!CGrShell::GetSearchDir(lpFileName)){
return nullptr;
}
auto *p = m_pictRendererMap;
for(int len=static_cast<int>(PictRenderType::MaxNum); len>0; --len, ++p){
if(!*p){ continue; }
(*p)->SetParam(_T("CurDir"), _T("."));
if((*p)->IsSupported(lpFileName)){
return *p;
}
}
return nullptr;
}
bool CGrPictRendererMgr::Draw(CGrBitmap &bmp, int x, int y, int w, int h, LPCTSTR lpFileName)
{
auto ppr = getPictRenderer(lpFileName);
if(ppr){
m_curPictRenderer = ppr;
m_filename = lpFileName;
ppr->Draw(bmp, x, y, w, h, lpFileName);
return true;
}
return false;
}
bool CGrPictRendererMgr::Draw(HDC hdc, int x, int y, int w, int h, LPCTSTR lpFileName)
{
CGrBitmap bmp;
if(Draw(bmp, 0, 0, w, h, lpFileName)){
auto hImageDC = CreateCompatibleDC(NULL);
auto hOldBitmap = SelectBitmap(hImageDC, bmp);
BitBlt(hdc, x, y, bmp.Width(), bmp.Height(), hImageDC, 0, 0, SRCCOPY);
SelectBitmap(hImageDC, hOldBitmap);
DeleteDC(hImageDC);
return true;
}
return false;
}
bool CGrPictRendererMgr::IsSupported(LPCTSTR lpFileName)
{
auto ppr = getPictRenderer(lpFileName);
return ppr != nullptr;
}
bool CGrPictRendererMgr::GetSupportedFile(std::tstring &out_filename, LPCTSTR lpFileName)
{
WIN32_FIND_DATA wfd = {0};
if(CGrShell::getFileInfo(lpFileName, wfd)){
if(IsSupported(lpFileName)){
out_filename = lpFileName;
return true;
}
return false;
}
const TCHAR *fileExt[] = {
_T("png"), _T("jpg"), _T("jpeg"), _T("emf"), _T("bmp"),
};
for(int i=0; i<sizeof(fileExt)/sizeof(TCHAR*); ++i){
TCHAR path[MAX_PATH];
_stprintf_s(path, _T("%s.%s"), lpFileName, fileExt[i]);
if(IsSupported(path)){
out_filename = path;
return true;
}
}
return false;
}
| 25.874016 | 93 | 0.696896 | gearsns |
fecfbf1f7da58342f5ce9d90c2cecfb9a6db145e | 761 | cpp | C++ | src/vsgXchange/ReaderWriter_all.cpp | andesengineering/vsgXchange | 88a3356cdb92792190e878fe8eb3a2436e7b3b67 | [
"MIT"
] | null | null | null | src/vsgXchange/ReaderWriter_all.cpp | andesengineering/vsgXchange | 88a3356cdb92792190e878fe8eb3a2436e7b3b67 | [
"MIT"
] | null | null | null | src/vsgXchange/ReaderWriter_all.cpp | andesengineering/vsgXchange | 88a3356cdb92792190e878fe8eb3a2436e7b3b67 | [
"MIT"
] | null | null | null | #include <vsgXchange/ReaderWriter_all.h>
#include <vsg/io/ReaderWriter_vsg.h>
#include "../glsl//ReaderWriter_glsl.h"
#include "../spirv/ReaderWriter_spirv.h"
#include "../cpp/ReaderWriter_cpp.h"
#ifdef USE_FREETYPE
#include "../freetype/FreeTypeFont.h"
#endif
#ifdef USE_OPENSCENEGRAPH
#include "../osg/ReaderWriter_osg.h"
#endif
using namespace vsgXchange;
ReaderWriter_all::ReaderWriter_all()
{
add(vsg::ReaderWriter_vsg::create());
add(vsgXchange::ReaderWriter_glsl::create());
add(vsgXchange::ReaderWriter_spirv::create());
add(vsgXchange::ReaderWriter_cpp::create());
#ifdef USE_FREETYPE
add(vsgXchange::ReaderWriter_freetype::create());
#endif
#ifdef USE_OPENSCENEGRAPH
add(vsgXchange::ReaderWriter_osg::create());
#endif
}
| 23.78125 | 53 | 0.751643 | andesengineering |
fed005b74434390094522fb83d56db923dbcabe5 | 2,536 | hpp | C++ | src/DataStructures/SliceTensorToVariables.hpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 117 | 2017-04-08T22:52:48.000Z | 2022-03-25T07:23:36.000Z | src/DataStructures/SliceTensorToVariables.hpp | GitHimanshuc/spectre | 4de4033ba36547113293fe4dbdd77591485a4aee | [
"MIT"
] | 3,177 | 2017-04-07T21:10:18.000Z | 2022-03-31T23:55:59.000Z | src/DataStructures/SliceTensorToVariables.hpp | geoffrey4444/spectre | 9350d61830b360e2d5b273fdd176dcc841dbefb0 | [
"MIT"
] | 85 | 2017-04-07T19:36:13.000Z | 2022-03-01T10:21:00.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <boost/range/combine.hpp>
#include <boost/tuple/tuple.hpp>
#include <cstddef>
#include "DataStructures/Index.hpp"
#include "DataStructures/SliceIterator.hpp"
#include "DataStructures/Tensor/Tensor.hpp"
#include "DataStructures/Variables.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/TMPL.hpp"
/// @{
/*!
* \ingroup DataStructuresGroup
* \brief Slices volume `Tensor`s into a `Variables`
*
* The slice has a constant logical coordinate in direction `sliced_dim`,
* slicing the volume at `fixed_index` in that dimension. For
* example, to get the lower boundary of `sliced_dim`, pass `0` for
* `fixed_index`; to get the upper boundary, pass
* `extents[sliced_dim] - 1`.
*/
template <typename... TagsToSlice, size_t VolumeDim>
void data_on_slice(
const gsl::not_null<Variables<tmpl::list<TagsToSlice...>>*> interface_vars,
const Index<VolumeDim>& element_extents, const size_t sliced_dim,
const size_t fixed_index, const typename TagsToSlice::type&... tensors) {
const size_t interface_grid_points =
element_extents.slice_away(sliced_dim).product();
if (interface_vars->number_of_grid_points() != interface_grid_points) {
*interface_vars =
Variables<tmpl::list<TagsToSlice...>>(interface_grid_points);
}
for (SliceIterator si(element_extents, sliced_dim, fixed_index); si; ++si) {
const auto lambda = [&si](auto& interface_tensor,
const auto& volume_tensor) {
for (decltype(auto) interface_and_volume_tensor_components :
boost::combine(interface_tensor, volume_tensor)) {
boost::get<0>(
interface_and_volume_tensor_components)[si.slice_offset()] =
boost::get<1>(
interface_and_volume_tensor_components)[si.volume_offset()];
}
return '0';
};
expand_pack(lambda(get<TagsToSlice>(*interface_vars), tensors)...);
}
}
template <typename... TagsToSlice, size_t VolumeDim>
Variables<tmpl::list<TagsToSlice...>> data_on_slice(
const Index<VolumeDim>& element_extents, const size_t sliced_dim,
const size_t fixed_index, const typename TagsToSlice::type&... tensors) {
Variables<tmpl::list<TagsToSlice...>> interface_vars(
element_extents.slice_away(sliced_dim).product());
data_on_slice<TagsToSlice...>(make_not_null(&interface_vars), element_extents,
sliced_dim, fixed_index, tensors...);
return interface_vars;
}
/// @}
| 38.424242 | 80 | 0.705442 | nilsvu |
fed12f12c79b07fbfad6deed35f232dbb6f2ead0 | 141 | hpp | C++ | src/controllers/ignores/IgnoreController.hpp | NilsIrl/chatterino2 | b7e86a8de66e53876d7a71376c43529597ee6c12 | [
"MIT"
] | 2 | 2018-12-26T15:41:08.000Z | 2021-04-30T11:41:39.000Z | src/controllers/ignores/IgnoreController.hpp | NilsIrl/chatterino2 | b7e86a8de66e53876d7a71376c43529597ee6c12 | [
"MIT"
] | 62 | 2021-02-27T15:09:31.000Z | 2022-03-31T03:09:56.000Z | src/controllers/ignores/IgnoreController.hpp | NilsIrl/chatterino2 | b7e86a8de66e53876d7a71376c43529597ee6c12 | [
"MIT"
] | null | null | null | #pragma once
namespace chatterino {
enum class ShowIgnoredUsersMessages { Never, IfModerator, IfBroadcaster };
} // namespace chatterino
| 17.625 | 74 | 0.780142 | NilsIrl |
fed4ff53d025f27d5a0c068698703bbc24107505 | 648 | cpp | C++ | test/snippet/alphabet/gap/gapped.cpp | marehr/nomchop | a88bfb6f5d4a291a71b6b3192eeac81fdc450d43 | [
"CC-BY-4.0",
"CC0-1.0"
] | 1 | 2021-03-01T11:12:56.000Z | 2021-03-01T11:12:56.000Z | test/snippet/alphabet/gap/gapped.cpp | simonsasse/seqan3 | 0ff2e117952743f081735df9956be4c512f4ccba | [
"CC0-1.0",
"CC-BY-4.0"
] | 2 | 2017-05-17T07:16:19.000Z | 2020-02-13T16:10:10.000Z | test/snippet/alphabet/gap/gapped.cpp | simonsasse/seqan3 | 0ff2e117952743f081735df9956be4c512f4ccba | [
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null | #include <seqan3/alphabet/gap/gapped.hpp>
#include <seqan3/alphabet/nucleotide/dna4.hpp>
int main()
{
using seqan3::operator""_dna4;
seqan3::gapped<seqan3::dna4> gapped_letter{};
seqan3::gapped<seqan3::dna4> converted_letter{'C'_dna4};
seqan3::gapped<seqan3::dna4> gap_letter{seqan3::gap{}};
seqan3::gapped<seqan3::dna4>{}.assign_char('C');
seqan3::gapped<seqan3::dna4>{}.assign_char('-'); // gap character
seqan3::gapped<seqan3::dna4>{}.assign_char('K'); // unknown characters map to the default/unknown
// character of the given alphabet type (i.e. A of dna4)
}
| 38.117647 | 109 | 0.638889 | marehr |
fed8c6d160b28d6ca61d7c00c636c2b271801584 | 8,974 | cc | C++ | libs/fssr/mesh_clean.cc | lemony-fresh/mve | d90cc2c813fef026f7732c5a26f6c15973a36042 | [
"BSD-3-Clause"
] | 1 | 2019-05-30T13:19:21.000Z | 2019-05-30T13:19:21.000Z | libs/fssr/mesh_clean.cc | MasterShockwave/mve | 7a96751db098bb6f5c0b4075921b0e8e43a69bb6 | [
"BSD-3-Clause"
] | null | null | null | libs/fssr/mesh_clean.cc | MasterShockwave/mve | 7a96751db098bb6f5c0b4075921b0e8e43a69bb6 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2015, Simon Fuhrmann
* TU Darmstadt - Graphics, Capture and Massively Parallel Computing
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the LICENSE.txt file for details.
*/
#include "math/defines.h"
#include "mve/mesh.h"
#include "mve/mesh_tools.h"
#include "mve/mesh_info.h"
#include "fssr/mesh_clean.h"
FSSR_NAMESPACE_BEGIN
bool
edge_collapse (mve::TriangleMesh::Ptr mesh, mve::MeshInfo& mesh_info,
std::size_t v1, std::size_t v2, math::Vec3f const& new_vert,
std::vector<std::size_t> const& afaces,
float acos_threshold = 0.95f)
{
mve::TriangleMesh::FaceList& faces = mesh->get_faces();
mve::TriangleMesh::VertexList& verts = mesh->get_vertices();
/* Test if the hypothetical vertex destroys geometry. */
mve::MeshInfo::VertexInfo& vinfo1 = mesh_info[v1];
for (std::size_t i = 0; i < vinfo1.verts.size(); ++i)
{
std::size_t ip1 = (i + 1) % vinfo1.verts.size();
if (vinfo1.verts[i] == v2 || vinfo1.verts[ip1] == v2)
continue;
math::Vec3f const& av1 = verts[vinfo1.verts[i]];
math::Vec3f const& av2 = verts[vinfo1.verts[ip1]];
math::Vec3f n1 = (av1 - verts[v1]).cross(av2 - verts[v1]).normalized();
math::Vec3f n2 = (av1 - new_vert).cross(av2 - new_vert).normalized();
float dot = n1.dot(n2);
if (MATH_ISNAN(dot) || dot < acos_threshold)
return false;
}
mve::MeshInfo::VertexInfo& vinfo2 = mesh_info[v2];
for (std::size_t i = 0; i < vinfo2.verts.size(); ++i)
{
std::size_t ip1 = (i + 1) % vinfo2.verts.size();
if (vinfo2.verts[i] == v1 || vinfo2.verts[ip1] == v1)
continue;
math::Vec3f const& av1 = verts[vinfo2.verts[i]];
math::Vec3f const& av2 = verts[vinfo2.verts[ip1]];
math::Vec3f n1 = (av1 - verts[v2]).cross(av2 - verts[v2]).normalized();
math::Vec3f n2 = (av1 - new_vert).cross(av2 - new_vert).normalized();
float dot = n1.dot(n2);
if (MATH_ISNAN(dot) || dot < acos_threshold)
return false;
}
/* Test succeeded. Assign new vertex position to v1. */
verts[v1] = new_vert;
/* Update faces adjacent to v2 replacing v2 with v1. */
for (std::size_t i = 0; i < vinfo2.faces.size(); ++i)
for (std::size_t j = 0; j < 3; ++j)
if (faces[vinfo2.faces[i] * 3 + j] == v2)
faces[vinfo2.faces[i] * 3 + j] = v1;
/* Delete the two faces adjacent to the collapsed edge. */
std::size_t v3 = 0, v4 = 0;
for (std::size_t i = 0; i < 3; ++i)
{
std::size_t fid1 = afaces[0] * 3 + i;
std::size_t fid2 = afaces[1] * 3 + i;
if (faces[fid1] != v1 && faces[fid1] != v2)
v3 = faces[fid1];
if (faces[fid2] != v1 && faces[fid2] != v2)
v4 = faces[fid2];
faces[fid1] = 0;
faces[fid2] = 0;
}
/* Update vertex info for vertices adjcent to v2, replacing v2 with v1. */
for (std::size_t i = 0; i < vinfo2.verts.size(); ++i)
{
std::size_t const vert_id = vinfo2.verts[i];
if (vert_id != v1 && vert_id != v3 && vert_id != v4)
mesh_info[vert_id].replace_adjacent_vertex(v2, v1);
}
/* Update vertex info for v3 and v4: remove v2, remove deleted faces. */
mve::MeshInfo::VertexInfo& vinfo3 = mesh_info[v3];
vinfo3.remove_adjacent_face(afaces[0]);
vinfo3.remove_adjacent_vertex(v2);
mve::MeshInfo::VertexInfo& vinfo4 = mesh_info[v4];
vinfo4.remove_adjacent_face(afaces[1]);
vinfo4.remove_adjacent_vertex(v2);
/* Update vinfo for v1: Remove v2, remove collapsed faces, add v2 faces. */
vinfo1.remove_adjacent_face(afaces[0]);
vinfo1.remove_adjacent_face(afaces[1]);
for (std::size_t i = 0; i < vinfo2.faces.size(); ++i)
if (vinfo2.faces[i] != afaces[0] && vinfo2.faces[i] != afaces[1])
vinfo1.faces.push_back(vinfo2.faces[i]);
mesh_info.update_vertex(*mesh, v1);
/* Update vertex info for v2. */
vinfo2.faces.clear();
vinfo2.verts.clear();
vinfo2.vclass = mve::MeshInfo::VERTEX_CLASS_UNREF;
return true;
}
/* ---------------------------------------------------------------- */
namespace
{
/*
* Returns the ratio of the smallest by the second smallest edge length.
*/
float
get_needle_ratio_squared (mve::TriangleMesh::VertexList const& verts,
unsigned int const* vid,
std::size_t* shortest_edge_v1, std::size_t* shortest_edge_v2)
{
typedef std::pair<float, int> Edge;
Edge edges[3];
for (int j = 0; j < 3; ++j)
{
int const jp1 = (j + 1) % 3;
edges[j].first = (verts[vid[j]] - verts[vid[jp1]]).square_norm();
edges[j].second = j;
}
math::algo::sort_values(edges + 0, edges + 1, edges + 2);
/* Test shortest to second-shortest edge ratio. */
float const square_ratio = edges[0].first / edges[1].first;
if (shortest_edge_v1 != nullptr && shortest_edge_v2 != nullptr)
{
*shortest_edge_v1 = vid[edges[0].second];
*shortest_edge_v2 = vid[(edges[0].second + 1) % 3];
}
return square_ratio;
}
}
std::size_t
clean_needles (mve::TriangleMesh::Ptr mesh, float needle_ratio_thres)
{
float const square_needle_ratio_thres = MATH_POW2(needle_ratio_thres);
mve::MeshInfo mesh_info(mesh);
/*
* Algorithm to remove slivers with a two long and a very short edge.
* The sliver is identified using the ratio of the shortest by the second
* shortest edge. An edge collapse of the short edge is performed if it
* does not modify the geometry in a negative way, e.g. flips triangles.
*/
mve::TriangleMesh::FaceList& faces = mesh->get_faces();
mve::TriangleMesh::VertexList& verts = mesh->get_vertices();
std::size_t num_collapses = 0;
for (std::size_t i = 0; i < faces.size(); i += 3)
{
/* Skip invalid faces. */
if (faces[i] == faces[i + 1] && faces[i] == faces[i + 2])
continue;
/* Skip faces that are no needles. */
std::size_t v1, v2;
float const needle_ratio_squared
= get_needle_ratio_squared(verts, &faces[i], &v1, &v2);
if (needle_ratio_squared > square_needle_ratio_thres)
continue;
/* Skip edges between non-simple vertices. */
if (mesh_info[v1].vclass != mve::MeshInfo::VERTEX_CLASS_SIMPLE
|| mesh_info[v2].vclass != mve::MeshInfo::VERTEX_CLASS_SIMPLE)
continue;
/* Find triangle adjacent to the edge, skip non-simple edges. */
std::vector<std::size_t> afaces;
mesh_info.get_faces_for_edge(v1, v2, &afaces);
if (afaces.size() != 2)
continue;
/* Collapse the edge. */
math::Vec3f new_v = (verts[v1] + verts[v2]) / 2.0f;
if (edge_collapse(mesh, mesh_info, v1, v2, new_v, afaces))
num_collapses += 1;
}
/* Cleanup invalid triangles and unreferenced vertices. */
mve::geom::mesh_delete_unreferenced(mesh);
return num_collapses;
}
/* ---------------------------------------------------------------- */
std::size_t
clean_caps (mve::TriangleMesh::Ptr mesh)
{
mve::MeshInfo mesh_info(mesh);
mve::TriangleMesh::VertexList& verts = mesh->get_vertices();
std::size_t num_collapses = 0;
for (std::size_t v1 = 0; v1 < verts.size(); ++v1)
{
mve::MeshInfo::VertexInfo& vinfo = mesh_info[v1];
if (vinfo.vclass != mve::MeshInfo::VERTEX_CLASS_SIMPLE)
continue;
if (vinfo.verts.size() != 3)
continue;
std::pair<float, std::size_t> edge_len[3];
for (std::size_t j = 0; j < vinfo.verts.size(); ++j)
edge_len[j] = std::make_pair(
(verts[vinfo.verts[j]] - verts[v1]).square_norm(),
vinfo.verts[j]);
math::algo::sort_values(edge_len + 0, edge_len + 1, edge_len + 2);
std::size_t v2 = edge_len[0].second;
std::vector<std::size_t> afaces;
mesh_info.get_faces_for_edge(v1, v2, &afaces);
if (afaces.size() != 2)
continue;
/* Edge collapse fails if (v2 - v1) is not coplanar to triangle. */
if (edge_collapse(mesh, mesh_info, v1, v2, verts[v2], afaces))
num_collapses += 1;
}
/* Cleanup invalid triangles and unreferenced vertices. */
mve::geom::mesh_delete_unreferenced(mesh);
return num_collapses;
}
/* ---------------------------------------------------------------- */
std::size_t
clean_mc_mesh (mve::TriangleMesh::Ptr mesh, float needle_ratio_thres)
{
std::size_t num_collapsed = 0;
num_collapsed += clean_needles(mesh, needle_ratio_thres);
num_collapsed += clean_caps(mesh);
num_collapsed += clean_needles(mesh, needle_ratio_thres);
return num_collapsed;
}
FSSR_NAMESPACE_END
| 35.192157 | 79 | 0.589035 | lemony-fresh |
fed97fe09ba054ce76bd1e780c74f5fc77250065 | 477 | cpp | C++ | src/UOJ_1061 - (2729840) Accepted.cpp | dreamtocode/URI | 1f402853e8ae43f3761fc3099e7694bff721d5bc | [
"MIT"
] | 1 | 2015-04-26T03:55:07.000Z | 2015-04-26T03:55:07.000Z | src/UOJ_1061 - (2729840) Accepted.cpp | dreamtocode/URI | 1f402853e8ae43f3761fc3099e7694bff721d5bc | [
"MIT"
] | null | null | null | src/UOJ_1061 - (2729840) Accepted.cpp | dreamtocode/URI | 1f402853e8ae43f3761fc3099e7694bff721d5bc | [
"MIT"
] | null | null | null | #include <iostream>
int main(){
int d, dt, h, ht, m, mt, s, st;
scanf("Dia %d", &d);
scanf("%d : %d : %d\n", &h, &m, &s);
scanf("Dia %d", &dt);
scanf("%d : %d : %d", &ht, &mt, &st);
s = st - s;
m = mt - m;
h = ht - h;
d = dt - d;
if (s < 0){
s += 60;
m--;
}
if (m < 0){
m += 60;
h--;
}
if (h < 0){
h += 24;
d--;
}
printf("%d dia(s)\n", d);
printf("%d hora(s)\n", h);
printf("%d minuto(s)\n", m);
printf("%d segundo(s)\n", s);
}
| 12.891892 | 38 | 0.385744 | dreamtocode |
fedf4a386527949071fb4d1e6c19f1b8841ed5a4 | 1,044 | cpp | C++ | 000/33.cpp | correipj/ProjectEuler | 0173d8ec7f309b4f0c243a94351772b1be55e8bf | [
"Unlicense"
] | null | null | null | 000/33.cpp | correipj/ProjectEuler | 0173d8ec7f309b4f0c243a94351772b1be55e8bf | [
"Unlicense"
] | null | null | null | 000/33.cpp | correipj/ProjectEuler | 0173d8ec7f309b4f0c243a94351772b1be55e8bf | [
"Unlicense"
] | null | null | null | // https://projecteuler.net/problem=33
// Digit cancelling fractions
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
int cancel(int a, int b) {
if (a == b)
return 0;
double frac = (double)a/b;
int da1 = (a/10)%10;
int da2 = a%10;
int db1 = (b/10)%10;
int db2 = b%10;
if (da2 == 0 || db2 == 0)
return 0;
if (da1 == db2 && frac == (double)da2/db1)
return 1;
if (da2 == db2 && frac == (double)da1/db1)
return 1;
if (da1 == db1 && frac == (double)da2/db2)
return 1;
if (da2 == db1 && frac == (double)da1/db2)
return 1;
return 0;
}
int main(int argc, char* argv[]) {
unsigned long pa = 1;
unsigned long pb = 1;
for (int a = 10; a < 100; a++)
for (int b = a; b < 100; b++) {
if(cancel(a, b)) {
pa *= a;
pb *= b;
printf("a = %d, b = %d\n", a, b);
}
}
// Cancel via inspection, find denominator = 100
printf("pa = %lu\n", pa);
printf("pb = %lu\n", pb);
getchar();
return 0;
}
| 18 | 50 | 0.522031 | correipj |
fedfc9cf2ceb4e46a7c1a2d8ec3a0bfca541bb42 | 2,734 | cpp | C++ | uint128_test_app/src/cpp/testing.cpp | cpsusie/cjm-numerics | 9719f4aa7ed0fa157f4705e3f20f069e28a5755f | [
"MIT"
] | 2 | 2021-04-18T07:35:56.000Z | 2021-04-23T07:37:58.000Z | uint128_test_app/src/cpp/testing.cpp | cpsusie/Int128 | 9719f4aa7ed0fa157f4705e3f20f069e28a5755f | [
"MIT"
] | 29 | 2020-12-18T00:50:36.000Z | 2021-03-22T21:35:18.000Z | uint128_test_app/src/cpp/testing.cpp | cpsusie/cjm-numerics | 9719f4aa7ed0fa157f4705e3f20f069e28a5755f | [
"MIT"
] | null | null | null | // Copyright © 2020-2021 CJM Screws, LLC
// 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.
//
// CJM Screws, LLC is a Maryland Limited Liability Company.
// No copyright claimed to unmodified original work of others.
// The original, unmodified work of others, to the extent included in this library,
// is licensed to you under the same terms under which it was licensed to CJM Screws, LLC.
// For information about copyright and licensing of the original work of others,
// see Notices file in cjm/ folder.
#include "testing.hpp"
#include <cassert>
#include <sstream>
void cjm::testing::cjm_deny(bool predicateExpression)
{
if (predicateExpression)
{
throw testing_failure("The specified condition is true.");
}
}
void cjm::testing::cjm_assert(bool predicateExpression)
{
if (!predicateExpression)
{
throw testing_failure("The specified condition was not met.");
}
}
void cjm::testing::cjm_assert_throws(const std::function<void()>& func)
{
if (!func)
{
throw testing_failure("The specified delegate is no good.");
}
bool itThrew;
try
{
func();
itThrew = false;
}
catch (const std::exception&)
{
itThrew = true;
}
catch (...)
{
itThrew = true;
}
if (!itThrew)
throw testing_failure("The specified routine did not throw.");
}
void cjm::testing::cjm_assert_nothrow(const std::function<void()>& func)
{
if (!func)
{
throw testing_failure("The specified delegate is no good.");
}
try
{
func();
}
catch (const std::exception& ex)
{
std::stringstream ss;
ss << "The specified delegate threw an exception with message: \"" << ex.what() << "\".";
throw testing_failure(ss.str());
}
catch (...)
{
throw testing_failure("The delegate threw a non-standard exception.");
}
}
| 31.068182 | 150 | 0.730797 | cpsusie |
fee09e59ebfbe5bae6fd193ae4d00a4a4fe7b528 | 552 | cpp | C++ | src/prof.cpp | mariokonrad/bitset | 8f95b8ab45a41e5bbe652979ec55427e6317a58a | [
"BSD-4-Clause"
] | null | null | null | src/prof.cpp | mariokonrad/bitset | 8f95b8ab45a41e5bbe652979ec55427e6317a58a | [
"BSD-4-Clause"
] | null | null | null | src/prof.cpp | mariokonrad/bitset | 8f95b8ab45a41e5bbe652979ec55427e6317a58a | [
"BSD-4-Clause"
] | 1 | 2021-10-31T10:13:44.000Z | 2021-10-31T10:13:44.000Z | #include "bitset.hpp"
using namespace mk;
static void create_and_append_uint32_t(uint64_t times)
{
static const uint32_t value = 0xaa55aa55;
for (uint64_t i = 0; i < times; ++i) {
bitset<uint8_t> b;
b.append(value);
}
}
static void set_bits_large_bitset(uint64_t times)
{
const int SIZE = 1024 * 1024;
for (uint64_t i = 0; i < times; ++i) {
bitset<uint8_t> b(SIZE + 128);
for (size_t j = 0; j < SIZE; ++j) {
b.set(1, j, 1);
}
}
}
int main(int, char **)
{
// create_and_append_uint32_t(1000000);
set_bits_large_bitset(100);
}
| 17.25 | 54 | 0.653986 | mariokonrad |
fee792d11a0c4f006c47c6a1e98de50276153be7 | 14,002 | hpp | C++ | include/System/UriSyntaxFlags.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/UriSyntaxFlags.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/System/UriSyntaxFlags.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Enum
#include "System/Enum.hpp"
// Completed includes
// Type namespace: System
namespace System {
// Forward declaring type: UriSyntaxFlags
struct UriSyntaxFlags;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(::System::UriSyntaxFlags, "System", "UriSyntaxFlags");
// Type namespace: System
namespace System {
// Size: 0x4
#pragma pack(push, 1)
// Autogenerated type: System.UriSyntaxFlags
// [TokenAttribute] Offset: FFFFFFFF
// [FlagsAttribute] Offset: FFFFFFFF
struct UriSyntaxFlags/*, public ::System::Enum*/ {
public:
public:
// public System.Int32 value__
// Size: 0x4
// Offset: 0x0
int value;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Creating value type constructor for type: UriSyntaxFlags
constexpr UriSyntaxFlags(int value_ = {}) noexcept : value{value_} {}
// Creating interface conversion operator: operator ::System::Enum
operator ::System::Enum() noexcept {
return *reinterpret_cast<::System::Enum*>(this);
}
// Creating conversion operator: operator int
constexpr operator int() const noexcept {
return value;
}
// static field const value: static public System.UriSyntaxFlags None
static constexpr const int None = 0;
// Get static field: static public System.UriSyntaxFlags None
static ::System::UriSyntaxFlags _get_None();
// Set static field: static public System.UriSyntaxFlags None
static void _set_None(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags MustHaveAuthority
static constexpr const int MustHaveAuthority = 1;
// Get static field: static public System.UriSyntaxFlags MustHaveAuthority
static ::System::UriSyntaxFlags _get_MustHaveAuthority();
// Set static field: static public System.UriSyntaxFlags MustHaveAuthority
static void _set_MustHaveAuthority(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags OptionalAuthority
static constexpr const int OptionalAuthority = 2;
// Get static field: static public System.UriSyntaxFlags OptionalAuthority
static ::System::UriSyntaxFlags _get_OptionalAuthority();
// Set static field: static public System.UriSyntaxFlags OptionalAuthority
static void _set_OptionalAuthority(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags MayHaveUserInfo
static constexpr const int MayHaveUserInfo = 4;
// Get static field: static public System.UriSyntaxFlags MayHaveUserInfo
static ::System::UriSyntaxFlags _get_MayHaveUserInfo();
// Set static field: static public System.UriSyntaxFlags MayHaveUserInfo
static void _set_MayHaveUserInfo(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags MayHavePort
static constexpr const int MayHavePort = 8;
// Get static field: static public System.UriSyntaxFlags MayHavePort
static ::System::UriSyntaxFlags _get_MayHavePort();
// Set static field: static public System.UriSyntaxFlags MayHavePort
static void _set_MayHavePort(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags MayHavePath
static constexpr const int MayHavePath = 16;
// Get static field: static public System.UriSyntaxFlags MayHavePath
static ::System::UriSyntaxFlags _get_MayHavePath();
// Set static field: static public System.UriSyntaxFlags MayHavePath
static void _set_MayHavePath(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags MayHaveQuery
static constexpr const int MayHaveQuery = 32;
// Get static field: static public System.UriSyntaxFlags MayHaveQuery
static ::System::UriSyntaxFlags _get_MayHaveQuery();
// Set static field: static public System.UriSyntaxFlags MayHaveQuery
static void _set_MayHaveQuery(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags MayHaveFragment
static constexpr const int MayHaveFragment = 64;
// Get static field: static public System.UriSyntaxFlags MayHaveFragment
static ::System::UriSyntaxFlags _get_MayHaveFragment();
// Set static field: static public System.UriSyntaxFlags MayHaveFragment
static void _set_MayHaveFragment(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags AllowEmptyHost
static constexpr const int AllowEmptyHost = 128;
// Get static field: static public System.UriSyntaxFlags AllowEmptyHost
static ::System::UriSyntaxFlags _get_AllowEmptyHost();
// Set static field: static public System.UriSyntaxFlags AllowEmptyHost
static void _set_AllowEmptyHost(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags AllowUncHost
static constexpr const int AllowUncHost = 256;
// Get static field: static public System.UriSyntaxFlags AllowUncHost
static ::System::UriSyntaxFlags _get_AllowUncHost();
// Set static field: static public System.UriSyntaxFlags AllowUncHost
static void _set_AllowUncHost(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags AllowDnsHost
static constexpr const int AllowDnsHost = 512;
// Get static field: static public System.UriSyntaxFlags AllowDnsHost
static ::System::UriSyntaxFlags _get_AllowDnsHost();
// Set static field: static public System.UriSyntaxFlags AllowDnsHost
static void _set_AllowDnsHost(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags AllowIPv4Host
static constexpr const int AllowIPv4Host = 1024;
// Get static field: static public System.UriSyntaxFlags AllowIPv4Host
static ::System::UriSyntaxFlags _get_AllowIPv4Host();
// Set static field: static public System.UriSyntaxFlags AllowIPv4Host
static void _set_AllowIPv4Host(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags AllowIPv6Host
static constexpr const int AllowIPv6Host = 2048;
// Get static field: static public System.UriSyntaxFlags AllowIPv6Host
static ::System::UriSyntaxFlags _get_AllowIPv6Host();
// Set static field: static public System.UriSyntaxFlags AllowIPv6Host
static void _set_AllowIPv6Host(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags AllowAnInternetHost
static constexpr const int AllowAnInternetHost = 3584;
// Get static field: static public System.UriSyntaxFlags AllowAnInternetHost
static ::System::UriSyntaxFlags _get_AllowAnInternetHost();
// Set static field: static public System.UriSyntaxFlags AllowAnInternetHost
static void _set_AllowAnInternetHost(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags AllowAnyOtherHost
static constexpr const int AllowAnyOtherHost = 4096;
// Get static field: static public System.UriSyntaxFlags AllowAnyOtherHost
static ::System::UriSyntaxFlags _get_AllowAnyOtherHost();
// Set static field: static public System.UriSyntaxFlags AllowAnyOtherHost
static void _set_AllowAnyOtherHost(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags FileLikeUri
static constexpr const int FileLikeUri = 8192;
// Get static field: static public System.UriSyntaxFlags FileLikeUri
static ::System::UriSyntaxFlags _get_FileLikeUri();
// Set static field: static public System.UriSyntaxFlags FileLikeUri
static void _set_FileLikeUri(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags MailToLikeUri
static constexpr const int MailToLikeUri = 16384;
// Get static field: static public System.UriSyntaxFlags MailToLikeUri
static ::System::UriSyntaxFlags _get_MailToLikeUri();
// Set static field: static public System.UriSyntaxFlags MailToLikeUri
static void _set_MailToLikeUri(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags V1_UnknownUri
static constexpr const int V1_UnknownUri = 65536;
// Get static field: static public System.UriSyntaxFlags V1_UnknownUri
static ::System::UriSyntaxFlags _get_V1_UnknownUri();
// Set static field: static public System.UriSyntaxFlags V1_UnknownUri
static void _set_V1_UnknownUri(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags SimpleUserSyntax
static constexpr const int SimpleUserSyntax = 131072;
// Get static field: static public System.UriSyntaxFlags SimpleUserSyntax
static ::System::UriSyntaxFlags _get_SimpleUserSyntax();
// Set static field: static public System.UriSyntaxFlags SimpleUserSyntax
static void _set_SimpleUserSyntax(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags BuiltInSyntax
static constexpr const int BuiltInSyntax = 262144;
// Get static field: static public System.UriSyntaxFlags BuiltInSyntax
static ::System::UriSyntaxFlags _get_BuiltInSyntax();
// Set static field: static public System.UriSyntaxFlags BuiltInSyntax
static void _set_BuiltInSyntax(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags ParserSchemeOnly
static constexpr const int ParserSchemeOnly = 524288;
// Get static field: static public System.UriSyntaxFlags ParserSchemeOnly
static ::System::UriSyntaxFlags _get_ParserSchemeOnly();
// Set static field: static public System.UriSyntaxFlags ParserSchemeOnly
static void _set_ParserSchemeOnly(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags AllowDOSPath
static constexpr const int AllowDOSPath = 1048576;
// Get static field: static public System.UriSyntaxFlags AllowDOSPath
static ::System::UriSyntaxFlags _get_AllowDOSPath();
// Set static field: static public System.UriSyntaxFlags AllowDOSPath
static void _set_AllowDOSPath(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags PathIsRooted
static constexpr const int PathIsRooted = 2097152;
// Get static field: static public System.UriSyntaxFlags PathIsRooted
static ::System::UriSyntaxFlags _get_PathIsRooted();
// Set static field: static public System.UriSyntaxFlags PathIsRooted
static void _set_PathIsRooted(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags ConvertPathSlashes
static constexpr const int ConvertPathSlashes = 4194304;
// Get static field: static public System.UriSyntaxFlags ConvertPathSlashes
static ::System::UriSyntaxFlags _get_ConvertPathSlashes();
// Set static field: static public System.UriSyntaxFlags ConvertPathSlashes
static void _set_ConvertPathSlashes(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags CompressPath
static constexpr const int CompressPath = 8388608;
// Get static field: static public System.UriSyntaxFlags CompressPath
static ::System::UriSyntaxFlags _get_CompressPath();
// Set static field: static public System.UriSyntaxFlags CompressPath
static void _set_CompressPath(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags CanonicalizeAsFilePath
static constexpr const int CanonicalizeAsFilePath = 16777216;
// Get static field: static public System.UriSyntaxFlags CanonicalizeAsFilePath
static ::System::UriSyntaxFlags _get_CanonicalizeAsFilePath();
// Set static field: static public System.UriSyntaxFlags CanonicalizeAsFilePath
static void _set_CanonicalizeAsFilePath(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags UnEscapeDotsAndSlashes
static constexpr const int UnEscapeDotsAndSlashes = 33554432;
// Get static field: static public System.UriSyntaxFlags UnEscapeDotsAndSlashes
static ::System::UriSyntaxFlags _get_UnEscapeDotsAndSlashes();
// Set static field: static public System.UriSyntaxFlags UnEscapeDotsAndSlashes
static void _set_UnEscapeDotsAndSlashes(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags AllowIdn
static constexpr const int AllowIdn = 67108864;
// Get static field: static public System.UriSyntaxFlags AllowIdn
static ::System::UriSyntaxFlags _get_AllowIdn();
// Set static field: static public System.UriSyntaxFlags AllowIdn
static void _set_AllowIdn(::System::UriSyntaxFlags value);
// static field const value: static public System.UriSyntaxFlags AllowIriParsing
static constexpr const int AllowIriParsing = 268435456;
// Get static field: static public System.UriSyntaxFlags AllowIriParsing
static ::System::UriSyntaxFlags _get_AllowIriParsing();
// Set static field: static public System.UriSyntaxFlags AllowIriParsing
static void _set_AllowIriParsing(::System::UriSyntaxFlags value);
// Get instance field reference: public System.Int32 value__
[[deprecated("Use field access instead!")]] int& dyn_value__();
}; // System.UriSyntaxFlags
#pragma pack(pop)
static check_size<sizeof(UriSyntaxFlags), 0 + sizeof(int)> __System_UriSyntaxFlagsSizeCheck;
static_assert(sizeof(UriSyntaxFlags) == 0x4);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
| 61.682819 | 94 | 0.769676 | v0idp |
fee95cf99701be023262d325c5c351925e15b1ab | 901 | cpp | C++ | avs/vis_avs/g_chanshift.cpp | semiessessi/vis_avs | e99a3803e9de9032e0e6759963b2c2798f3443ef | [
"BSD-3-Clause"
] | 18 | 2020-07-30T11:55:23.000Z | 2022-02-25T02:39:15.000Z | avs/vis_avs/g_chanshift.cpp | semiessessi/vis_avs | e99a3803e9de9032e0e6759963b2c2798f3443ef | [
"BSD-3-Clause"
] | 34 | 2021-01-13T02:02:12.000Z | 2022-03-23T12:09:55.000Z | avs/vis_avs/g_chanshift.cpp | semiessessi/vis_avs | e99a3803e9de9032e0e6759963b2c2798f3443ef | [
"BSD-3-Clause"
] | 3 | 2021-03-18T12:53:58.000Z | 2021-10-02T20:24:41.000Z | #include "g__lib.h"
#include "g__defs.h"
#include "c_chanshift.h"
#include "resource.h"
#include <windows.h>
int win32_dlgproc_chanshift(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM)
{
C_THISCLASS* g_ConfigThis = (C_THISCLASS*)g_current_render;
int ids[] = { IDC_RBG, IDC_BRG, IDC_BGR, IDC_GBR, IDC_GRB, IDC_RGB };
switch (uMsg)
{
case WM_COMMAND:
if (HIWORD(wParam) == BN_CLICKED) {
for (unsigned int i=0;i<sizeof(ids)/sizeof(ids[0]);i++)
if (IsDlgButtonChecked(hwndDlg, ids[i]))
g_ConfigThis->config.mode = ids[i];
g_ConfigThis->config.onbeat = IsDlgButtonChecked(hwndDlg, IDC_ONBEAT) ? 1 : 0;
}
return 1;
case WM_INITDIALOG:
CheckDlgButton(hwndDlg, g_ConfigThis->config.mode, 1);
if (g_ConfigThis->config.onbeat)
CheckDlgButton(hwndDlg, IDC_ONBEAT, 1);
return 1;
case WM_DESTROY:
KillTimer(hwndDlg, 1);
return 1;
}
return 0;
}
| 23.710526 | 82 | 0.689234 | semiessessi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.