blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
72f53847741a83369524e0fcb779cdc4fd51a31b
affbe202218f92bb908ea32bf0fdfde7528df065
/LeetCode 477 Total Hamming Distance.cpp
99df8a183bb8bc5f3f441310e84e1f23571931f1
[]
no_license
GengchenXU/LeetCode-2
fddc92f8d230da6f3e860dd103cf34e187832ec0
431f7f9cc6dac91b9cccf853906e91ba2f7892d4
refs/heads/master
2020-12-21T02:32:08.446814
2019-12-22T14:14:57
2019-12-22T14:14:57
236,279,461
1
0
null
2020-01-26T07:12:31
2020-01-26T07:12:30
null
UTF-8
C++
false
false
382
cpp
// LeetCode 477 Total Hamming Distance.cpp class Solution { public: int totalHammingDistance(vector<int>& nums) { int dist = 0; for (int i = 0; i < 8 * sizeof(int); i++) { int b1 = 0; for (int n : nums) { b1 += n >> i & 1; } dist += b1 * (nums.size() - b1); } return dist; } };
0cef37bf19eb288be95ea0a907dcc30ae3bb6b9a
e33dcca8fdd5ebda31443feddae99e58ed8bfa5a
/uva/UVA 884.cpp
d41088e613e8259d31896afcdf72dd525068ba14
[]
no_license
keyliin0/Competitive-Programming
5e6c4f7f3d4be0aa80f01bd623fef88e34a4eb74
bf93567ab73f7545883a3af43fb6dd8f5fe7ac51
refs/heads/master
2021-06-07T11:47:35.930727
2020-01-19T22:13:05
2020-01-19T22:13:05
140,153,796
0
0
null
null
null
null
UTF-8
C++
false
false
1,469
cpp
/* we must factorize each number as much as possible , that can be done using prime factorization going through all the numbers from 2 to 10^6 and counting the factors of each one will TL but since we are going in an increasing order we know number factors of an integer x = 1 + number of factors of x / i i is the first number such that x % i = 0 use prefix sum to answer each test case in o(1) */ #include <bits/stdc++.h> using namespace std; #define loop(i,b,e) for(int i=b;i<=e;i++) #define loop2(i,e,b) for(int i=e;i>=b;i--) #define io ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0) #define fi first #define se second #define X real() #define Y imag() #define cp(a,b) ( (conj(a)*(b)).imag() ) #define length(a) (hypot((a).imag(), (a).real())) typedef complex<double> point; typedef long long ll; typedef unsigned long long ull; double PI = 3.141592653589793; const double EPS = 1e-9; const int N = 1e6 + 5; const ll mod = 1e9 + 7; const int oo = 1e9; int dx[] = { 0, 0, 1, -1, 1, -1, 1, -1 }; int dy[] = { 1, -1, 0, 0, -1, 1, 1, -1 }; int n; int freq[N]; void getfactors(int x) { int sum = 0,a = x; for (int i = 2; i <= x / i; i++) { if (x % i == 0) { freq[a] = 1 + freq[x / i]; return; } } freq[a] = 1; } int main() { loop(i, 2, 1e6) getfactors(i); loop(i, 2, 1e6) freq[i] += freq[i - 1]; while (scanf("%d", &n) != EOF) { ll ans = freq[n]; printf("%lld\n",ans); } }
ffc644ae2d7cecb13e8e5de9aa4a6bd2c43faaec
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/llvm/lib/Target/Mips/MipsMachineFunction.cpp
a7299d73a82f61535695cefe95f2bf3a975f98c0
[ "MIT", "NCSA", "BSD-3-Clause", "NTP", "LicenseRef-scancode-unknown-license-reference" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
2,470
cpp
//===-- MipsMachineFunctionInfo.cpp - Private data used for Mips ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MipsMachineFunction.h" #include "MCTargetDesc/MipsBaseInfo.h" #include "MipsInstrInfo.h" #include "MipsSubtarget.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/IR/Function.h" #include "llvm/Support/CommandLine.h" using namespace llvm; static cl::opt<bool> FixGlobalBaseReg("mips-fix-global-base-reg", cl::Hidden, cl::init(true), cl::desc("Always use $gp as the global base register.")); bool MipsFunctionInfo::globalBaseRegSet() const { return GlobalBaseReg; } unsigned MipsFunctionInfo::getGlobalBaseReg() { // Return if it has already been initialized. if (GlobalBaseReg) return GlobalBaseReg; const MipsSubtarget &ST = MF.getTarget().getSubtarget<MipsSubtarget>(); const TargetRegisterClass *RC; if (ST.inMips16Mode()) RC=(const TargetRegisterClass*)&Mips::CPU16RegsRegClass; else RC = ST.isABI_N64() ? (const TargetRegisterClass*)&Mips::GPR64RegClass : (const TargetRegisterClass*)&Mips::GPR32RegClass; return GlobalBaseReg = MF.getRegInfo().createVirtualRegister(RC); } bool MipsFunctionInfo::mips16SPAliasRegSet() const { return Mips16SPAliasReg; } unsigned MipsFunctionInfo::getMips16SPAliasReg() { // Return if it has already been initialized. if (Mips16SPAliasReg) return Mips16SPAliasReg; const TargetRegisterClass *RC; RC=(const TargetRegisterClass*)&Mips::CPU16RegsRegClass; return Mips16SPAliasReg = MF.getRegInfo().createVirtualRegister(RC); } void MipsFunctionInfo::createEhDataRegsFI() { for (int I = 0; I < 4; ++I) { const MipsSubtarget &ST = MF.getTarget().getSubtarget<MipsSubtarget>(); const TargetRegisterClass *RC = ST.isABI_N64() ? &Mips::GPR64RegClass : &Mips::GPR32RegClass; EhDataRegFI[I] = MF.getFrameInfo()->CreateStackObject(RC->getSize(), RC->getAlignment(), false); } } bool MipsFunctionInfo::isEhDataRegFI(int FI) const { return CallsEhReturn && (FI == EhDataRegFI[0] || FI == EhDataRegFI[1] || FI == EhDataRegFI[2] || FI == EhDataRegFI[3]); } void MipsFunctionInfo::anchor() { }
9663e011ef35f28cb58bbc2a9613a21b6af5cfb8
4c0c57f9ddb87f46d58192e1ebfd2c40f6d2c315
/td/telegram/UpdatesManager.cpp
c796c3c8fd68e1a455b6e7e9a532eee5ac21a948
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
luckydonald-backup/td
9693cf868b3afdc5b5257e95e37af79380472d0b
71d03f39c364367a8a7c51f783a41099297de826
refs/heads/master
2021-09-02T08:08:18.834827
2018-12-31T19:04:05
2017-12-31T20:08:40
115,928,341
2
0
null
2018-01-01T15:37:21
2018-01-01T15:37:20
null
UTF-8
C++
false
false
70,913
cpp
// // Copyright Aliaksei Levin ([email protected]), Arseny Smirnov ([email protected]) 2014-2017 // // 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 "td/telegram/UpdatesManager.h" #include "td/telegram/telegram_api.hpp" #include "td/telegram/AnimationsManager.h" #include "td/telegram/AuthManager.h" #include "td/telegram/CallbackQueriesManager.h" #include "td/telegram/CallManager.h" #include "td/telegram/ChannelId.h" #include "td/telegram/ChatId.h" #include "td/telegram/ConfigManager.h" #include "td/telegram/ContactsManager.h" #include "td/telegram/DialogId.h" #include "td/telegram/Global.h" #include "td/telegram/InlineQueriesManager.h" #include "td/telegram/Location.h" #include "td/telegram/MessageId.h" #include "td/telegram/MessagesManager.h" #include "td/telegram/net/DcOptions.h" #include "td/telegram/net/NetQuery.h" #include "td/telegram/Payments.h" #include "td/telegram/PrivacyManager.h" #include "td/telegram/SecretChatId.h" #include "td/telegram/SecretChatsManager.h" #include "td/telegram/StateManager.h" #include "td/telegram/StickersManager.h" #include "td/telegram/Td.h" #include "td/telegram/WebPagesManager.h" #include "td/utils/buffer.h" #include "td/utils/format.h" #include "td/utils/logging.h" #include "td/utils/misc.h" #include "td/utils/Random.h" #include "td/utils/Slice.h" #include "td/utils/Status.h" #include "td/utils/StringBuilder.h" #include <limits> namespace td { class OnUpdate { UpdatesManager *manager_; tl_object_ptr<telegram_api::Update> &update_; bool force_apply_; public: OnUpdate(UpdatesManager *manager, tl_object_ptr<telegram_api::Update> &update, bool force_apply) : manager_(manager), update_(update), force_apply_(force_apply) { } template <class T> void operator()(T &obj) const { CHECK(&*update_ == &obj); manager_->on_update(move_tl_object_as<T>(update_), force_apply_); } }; class GetUpdatesStateQuery : public Td::ResultHandler { public: void send() { // TODO this call must be first after client is logged in, there must be no API calls before // it succeeds send_query(G()->net_query_creator().create(create_storer(telegram_api::updates_getState()))); } void on_result(uint64 id, BufferSlice packet) override { auto result_ptr = fetch_result<telegram_api::updates_getState>(packet); if (result_ptr.is_error()) { return on_error(id, result_ptr.move_as_error()); } auto state = result_ptr.move_as_ok(); CHECK(state->get_id() == telegram_api::updates_state::ID); td->updates_manager_->on_get_updates_state(std::move(state), "GetUpdatesStateQuery"); } void on_error(uint64 id, Status status) override { if (status.message() != CSlice("SESSION_REVOKED") && status.message() != CSlice("USER_DEACTIVATED")) { LOG(ERROR) << "updates.getState error: " << status; } status.ignore(); td->updates_manager_->on_get_updates_state(nullptr, "GetUpdatesStateQuery"); } }; class GetDifferenceQuery : public Td::ResultHandler { public: void send() { int32 pts = td->updates_manager_->get_pts(); int32 date = td->updates_manager_->get_date(); int32 qts = td->updates_manager_->get_qts(); if (pts < 0) { pts = 0; } LOG(INFO) << tag("pts", pts) << tag("qts", qts) << tag("date", date); send_query( G()->net_query_creator().create(create_storer(telegram_api::updates_getDifference(0, pts, 0, date, qts)))); } void on_result(uint64 id, BufferSlice packet) override { auto result_ptr = fetch_result<telegram_api::updates_getDifference>(packet); if (result_ptr.is_error()) { return on_error(id, result_ptr.move_as_error()); } td->updates_manager_->on_get_difference(result_ptr.move_as_ok()); } void on_error(uint64 id, Status status) override { if (status.message() != CSlice("SESSION_REVOKED") && status.message() != CSlice("USER_DEACTIVATED")) { LOG(ERROR) << "updates.getDifference error: " << status; } td->updates_manager_->on_get_difference(nullptr); if (status.message() == CSlice("PERSISTENT_TIMESTAMP_INVALID")) { td->updates_manager_->set_pts(std::numeric_limits<int32>::max(), "PERSISTENT_TIMESTAMP_INVALID") .set_value(Unit()); } status.ignore(); } }; const double UpdatesManager::MAX_UNFILLED_GAP_TIME = 1.0; UpdatesManager::UpdatesManager(Td *td, ActorShared<> parent) : td_(td), parent_(std::move(parent)) { pts_manager_.init(-1); } void UpdatesManager::tear_down() { parent_.reset(); } void UpdatesManager::fill_pts_gap(void *td) { fill_gap(td, "pts"); } void UpdatesManager::fill_seq_gap(void *td) { fill_gap(td, "seq"); } void UpdatesManager::fill_get_difference_gap(void *td) { fill_gap(td, "getDifference"); } void UpdatesManager::fill_gap(void *td, const char *source) { CHECK(td != nullptr); auto updates_manager = static_cast<Td *>(td)->updates_manager_.get(); LOG(WARNING) << "Filling gap in " << source << " by running getDifference. " << updates_manager->get_state(); updates_manager->get_difference("fill_gap"); } string UpdatesManager::get_state() const { char buff[1024]; StringBuilder sb({buff, sizeof(buff)}); sb << "UpdatesManager is in state "; switch (state_.type) { case State::Type::General: sb << "General"; break; case State::Type::RunningGetUpdatesState: sb << "RunningGetUpdatesState"; break; case State::Type::RunningGetDifference: sb << "RunningGetDifference"; break; case State::Type::ApplyingDifference: sb << "ApplyingDifference"; break; case State::Type::ApplyingDifferenceSlice: sb << "ApplyingDifferenceSlice"; break; case State::Type::ApplyingUpdates: sb << "ApplyingUpdates"; break; case State::Type::ApplyingSeqUpdates: sb << "ApplyingSeqUpdates"; break; default: UNREACHABLE(); } sb << " with pts = " << state_.pts << ", qts = " << state_.qts << " and date = " << state_.date; CHECK(!sb.is_error()); return sb.as_cslice().str(); } void UpdatesManager::set_state(State::Type type) { state_.type = type; state_.pts = get_pts(); state_.qts = qts_; state_.date = date_; } void UpdatesManager::get_difference(const char *source) { if (get_pts() == -1) { init_state(); return; } if (!td_->auth_manager_->is_authorized()) { return; } if (running_get_difference_) { LOG(INFO) << "Skip running getDifference from " << source << " because it is already running"; return; } running_get_difference_ = true; LOG(INFO) << "-----BEGIN GET DIFFERENCE----- from " << source; before_get_difference(); td_->create_handler<GetDifferenceQuery>()->send(); last_get_difference_pts_ = get_pts(); set_state(State::Type::RunningGetDifference); } void UpdatesManager::before_get_difference() { // may be called many times before after_get_difference is called send_closure(G()->state_manager(), &StateManager::on_synchronized, false); td_->messages_manager_->before_get_difference(); send_closure(td_->secret_chats_manager_, &SecretChatsManager::before_get_difference, get_qts()); } Promise<> UpdatesManager::add_pts(int32 pts) { auto id = pts_manager_.add_pts(pts); return PromiseCreator::event(self_closure(this, &UpdatesManager::on_pts_ack, id)); } void UpdatesManager::on_pts_ack(PtsManager::PtsId ack_token) { auto old_pts = pts_manager_.db_pts(); auto new_pts = pts_manager_.finish(ack_token); if (old_pts != new_pts) { save_pts(new_pts); } } void UpdatesManager::save_pts(int32 pts) { if (pts == std::numeric_limits<int32>::max()) { G()->td_db()->get_binlog_pmc()->erase("updates.pts"); } else { G()->td_db()->get_binlog_pmc()->set("updates.pts", to_string(pts)); } } Promise<> UpdatesManager::set_pts(int32 pts, const char *source) { if (pts == std::numeric_limits<int32>::max()) { LOG(WARNING) << "Update pts from " << get_pts() << " to -1 from " << source; G()->td_db()->get_binlog_pmc()->erase("updates.pts"); auto result = add_pts(std::numeric_limits<int32>::max()); init_state(); return result; } Promise<> result; if (pts > get_pts() || (0 < pts && pts < get_pts() - 999999)) { // pts can only go up or drop cardinally if (pts < get_pts() - 999999) { LOG(WARNING) << "Pts decreases from " << get_pts() << " to " << pts << " from " << source << ". " << get_state(); } else { LOG(INFO) << "Update pts from " << get_pts() << " to " << pts << " from " << source; } result = add_pts(pts); if (last_get_difference_pts_ + FORCED_GET_DIFFERENCE_PTS_DIFF < get_pts()) { last_get_difference_pts_ = get_pts(); schedule_get_difference("set_pts"); } } else if (pts < get_pts()) { LOG(ERROR) << "Receive wrong pts = " << pts << " from " << source << ". Current pts = " << get_pts() << ". " << get_state(); } return result; } void UpdatesManager::set_qts(int32 qts) { if (qts > qts_) { LOG(INFO) << "Update qts to " << qts; qts_ = qts; G()->td_db()->get_binlog_pmc()->set("updates.qts", to_string(qts)); } else if (qts < qts_) { LOG(ERROR) << "Receive wrong qts = " << qts << ". Current qts = " << qts_ << ". " << get_state(); } } void UpdatesManager::set_date(int32 date, bool from_update, string date_source) { if (date > date_) { LOG(INFO) << "Update date to " << date; if (from_update && false) { // date in updates is decreased by the server date--; if (date == date_) { return; } } date_ = date; date_source_ = std::move(date_source); G()->td_db()->get_binlog_pmc()->set("updates.date", to_string(date)); } else if (date < date_) { if (from_update) { date++; if (date == date_) { return; } } LOG(ERROR) << "Receive wrong by " << (date_ - date) << " date = " << date << " from " << date_source << ". Current date = " << date_ << " from " << date_source_ << ". " << get_state(); } } bool UpdatesManager::is_acceptable_message_entities( const vector<tl_object_ptr<telegram_api::MessageEntity>> &message_entities) const { for (auto &entity : message_entities) { if (entity->get_id() == telegram_api::messageEntityMentionName::ID) { auto entity_mention_name = static_cast<const telegram_api::messageEntityMentionName *>(entity.get()); UserId user_id(entity_mention_name->user_id_); if (!td_->contacts_manager_->have_user(user_id)) { return false; } } } return true; } bool UpdatesManager::is_acceptable_message(const telegram_api::Message *message_ptr) const { CHECK(message_ptr != nullptr); int32 constructor_id = message_ptr->get_id(); bool is_channel_post = false; DialogId dialog_id; UserId sender_user_id; switch (constructor_id) { case telegram_api::messageEmpty::ID: return true; case telegram_api::message::ID: { auto message = static_cast<const telegram_api::message *>(message_ptr); is_channel_post = (message->flags_ & MessagesManager::MESSAGE_FLAG_IS_POST) != 0; dialog_id = DialogId(message->to_id_); if (message->flags_ & MessagesManager::MESSAGE_FLAG_HAS_FROM_ID) { sender_user_id = UserId(message->from_id_); } if (message->flags_ & MessagesManager::MESSAGE_FLAG_IS_FORWARDED) { CHECK(message->fwd_from_ != nullptr); auto flags = message->fwd_from_->flags_; bool from_post = (flags & MessagesManager::MESSAGE_FORWARD_HEADER_FLAG_HAS_CHANNEL_ID) != 0; if (from_post && !td_->contacts_manager_->have_channel(ChannelId(message->fwd_from_->channel_id_))) { return false; } if (flags & MessagesManager::MESSAGE_FORWARD_HEADER_FLAG_HAS_AUTHOR_ID) { UserId user_id(message->fwd_from_->from_id_); if (from_post && !td_->contacts_manager_->have_min_user(user_id)) { return false; } if (!from_post && !td_->contacts_manager_->have_user(user_id)) { return false; } } } else { CHECK(message->fwd_from_ == nullptr); } if ((message->flags_ & MessagesManager::MESSAGE_FLAG_IS_SENT_VIA_BOT) && !td_->contacts_manager_->have_user(UserId(message->via_bot_id_))) { return false; } if (!is_acceptable_message_entities(message->entities_)) { return false; } if (message->flags_ & MessagesManager::MESSAGE_FLAG_HAS_MEDIA) { CHECK(message->media_ != nullptr); auto media_id = message->media_->get_id(); if (media_id == telegram_api::messageMediaContact::ID) { auto message_media_contact = static_cast<const telegram_api::messageMediaContact *>(message->media_.get()); UserId user_id(message_media_contact->user_id_); if (user_id != UserId() && !td_->contacts_manager_->have_user(user_id)) { return false; } } /* if (media_id == telegram_api::messageMediaWebPage::ID) { auto message_media_web_page = static_cast<const telegram_api::messageMediaWebPage *>(message->media_.get()); if (message_media_web_page->webpage_->get_id() == telegram_api::webPage::ID) { auto web_page = static_cast<const telegram_api::webPage *>(message_media_web_page->webpage_.get()); if (web_page->cached_page_ != nullptr) { const vector<tl_object_ptr<telegram_api::PageBlock>> *page_blocks = nullptr; downcast_call(*web_page->cached_page_, [&page_blocks](auto &page) { page_blocks = &page.blocks_; }); CHECK(page_blocks != nullptr); for (auto &page_block : *page_blocks) { if (page_block->get_id() == telegram_api::pageBlockChannel::ID) { auto page_block_channel = static_cast<const telegram_api::pageBlockChannel *>(page_block.get()); auto channel_id = ContactsManager::get_channel_id(page_block_channel->channel_); if (channel_id.is_valid()) { if (!td_->contacts_manager_->have_channel(channel_id)) { return false; } } else { LOG(ERROR) << "Receive wrong channel " << to_string(page_block_channel->channel_); } } } } } } */ } else { CHECK(message->media_ == nullptr); } break; } case telegram_api::messageService::ID: { auto message = static_cast<const telegram_api::messageService *>(message_ptr); is_channel_post = (message->flags_ & MessagesManager::MESSAGE_FLAG_IS_POST) != 0; dialog_id = DialogId(message->to_id_); if (message->flags_ & MessagesManager::MESSAGE_FLAG_HAS_FROM_ID) { sender_user_id = UserId(message->from_id_); } const telegram_api::MessageAction *action = message->action_.get(); CHECK(action != nullptr); switch (action->get_id()) { case telegram_api::messageActionEmpty::ID: case telegram_api::messageActionChatEditTitle::ID: case telegram_api::messageActionChatEditPhoto::ID: case telegram_api::messageActionChatDeletePhoto::ID: case telegram_api::messageActionCustomAction::ID: case telegram_api::messageActionHistoryClear::ID: case telegram_api::messageActionChannelCreate::ID: case telegram_api::messageActionPinMessage::ID: case telegram_api::messageActionGameScore::ID: case telegram_api::messageActionPhoneCall::ID: case telegram_api::messageActionPaymentSent::ID: case telegram_api::messageActionPaymentSentMe::ID: case telegram_api::messageActionScreenshotTaken::ID: break; case telegram_api::messageActionChatCreate::ID: { auto chat_create = static_cast<const telegram_api::messageActionChatCreate *>(action); for (auto &user : chat_create->users_) { if (!td_->contacts_manager_->have_user(UserId(user))) { return false; } } break; } case telegram_api::messageActionChatAddUser::ID: { auto chat_add_user = static_cast<const telegram_api::messageActionChatAddUser *>(action); for (auto &user : chat_add_user->users_) { if (!td_->contacts_manager_->have_user(UserId(user))) { return false; } } break; } case telegram_api::messageActionChatJoinedByLink::ID: { auto chat_joined_by_link = static_cast<const telegram_api::messageActionChatJoinedByLink *>(action); if (!td_->contacts_manager_->have_user(UserId(chat_joined_by_link->inviter_id_))) { return false; } break; } case telegram_api::messageActionChatDeleteUser::ID: { auto chat_delete_user = static_cast<const telegram_api::messageActionChatDeleteUser *>(action); if (!td_->contacts_manager_->have_user(UserId(chat_delete_user->user_id_))) { return false; } break; } case telegram_api::messageActionChatMigrateTo::ID: { auto chat_migrate_to = static_cast<const telegram_api::messageActionChatMigrateTo *>(action); if (!td_->contacts_manager_->have_channel(ChannelId(chat_migrate_to->channel_id_))) { return false; } break; } case telegram_api::messageActionChannelMigrateFrom::ID: { auto channel_migrate_from = static_cast<const telegram_api::messageActionChannelMigrateFrom *>(action); if (!td_->contacts_manager_->have_chat(ChatId(channel_migrate_from->chat_id_))) { return false; } break; } default: UNREACHABLE(); return false; } break; } default: UNREACHABLE(); return false; } switch (dialog_id.get_type()) { case DialogType::None: LOG(ERROR) << "Receive message in the invalid " << dialog_id; return false; case DialogType::User: { if (!td_->contacts_manager_->have_user(dialog_id.get_user_id())) { return false; } break; } case DialogType::Chat: { if (!td_->contacts_manager_->have_chat(dialog_id.get_chat_id())) { return false; } break; } case DialogType::Channel: { if (!td_->contacts_manager_->have_channel(dialog_id.get_channel_id())) { return false; } break; } case DialogType::SecretChat: default: UNREACHABLE(); return false; } if (sender_user_id != UserId()) { if (is_channel_post && !td_->contacts_manager_->have_min_user(sender_user_id)) { return false; } if (!is_channel_post && !td_->contacts_manager_->have_user(sender_user_id)) { return false; } } return true; } bool UpdatesManager::is_acceptable_update(const telegram_api::Update *update) const { if (update == nullptr) { return true; } int32 id = update->get_id(); const telegram_api::Message *message = nullptr; if (id == telegram_api::updateNewMessage::ID) { message = static_cast<const telegram_api::updateNewMessage *>(update)->message_.get(); } if (id == telegram_api::updateNewChannelMessage::ID) { message = static_cast<const telegram_api::updateNewChannelMessage *>(update)->message_.get(); } if (id == telegram_api::updateEditMessage::ID) { message = static_cast<const telegram_api::updateEditMessage *>(update)->message_.get(); } if (id == telegram_api::updateEditChannelMessage::ID) { message = static_cast<const telegram_api::updateEditChannelMessage *>(update)->message_.get(); } if (message != nullptr) { return is_acceptable_message(message); } if (id == telegram_api::updateDraftMessage::ID) { auto update_draft_message = static_cast<const telegram_api::updateDraftMessage *>(update); CHECK(update_draft_message->draft_ != nullptr); if (update_draft_message->draft_->get_id() == telegram_api::draftMessage::ID) { auto draft_message = static_cast<const telegram_api::draftMessage *>(update_draft_message->draft_.get()); return is_acceptable_message_entities(draft_message->entities_); } } return true; } void UpdatesManager::on_get_updates(tl_object_ptr<telegram_api::Updates> &&updates_ptr) { CHECK(updates_ptr != nullptr); auto updates_type = updates_ptr->get_id(); if (updates_type != telegram_api::updateShort::ID) { LOG(INFO) << "Receive " << to_string(updates_ptr); } if (!td_->auth_manager_->is_authorized()) { LOG(INFO) << "Ignore updates received before authorization or after logout"; return; } switch (updates_ptr->get_id()) { case telegram_api::updatesTooLong::ID: get_difference("updatesTooLong"); break; case telegram_api::updateShortMessage::ID: { auto update = move_tl_object_as<telegram_api::updateShortMessage>(updates_ptr); if (update->flags_ & MessagesManager::MESSAGE_FLAG_HAS_REPLY_MARKUP) { LOG(ERROR) << "Receive updateShortMessage with reply_markup"; update->flags_ ^= MessagesManager::MESSAGE_FLAG_HAS_REPLY_MARKUP; } if (update->flags_ & MessagesManager::MESSAGE_FLAG_HAS_MEDIA) { LOG(ERROR) << "Receive updateShortMessage with media"; update->flags_ ^= MessagesManager::MESSAGE_FLAG_HAS_MEDIA; } auto from_id = update->flags_ & MessagesManager::MESSAGE_FLAG_IS_OUT ? td_->contacts_manager_->get_my_id("on_get_updates").get() : update->user_id_; update->flags_ |= MessagesManager::MESSAGE_FLAG_HAS_FROM_ID; on_pending_update( make_tl_object<telegram_api::updateNewMessage>( make_tl_object<telegram_api::message>( update->flags_, false /*ignored*/, false /*ignored*/, false /*ignored*/, false /*ignored*/, false /*ignored*/, update->id_, from_id, make_tl_object<telegram_api::peerUser>(update->user_id_), std::move(update->fwd_from_), update->via_bot_id_, update->reply_to_msg_id_, update->date_, update->message_, nullptr, nullptr, std::move(update->entities_), 0, 0, "", 0), update->pts_, update->pts_count_), 0, "telegram_api::updatesShortMessage"); break; } case telegram_api::updateShortChatMessage::ID: { auto update = move_tl_object_as<telegram_api::updateShortChatMessage>(updates_ptr); if (update->flags_ & MessagesManager::MESSAGE_FLAG_HAS_REPLY_MARKUP) { LOG(ERROR) << "Receive updateShortChatMessage with reply_markup"; update->flags_ ^= MessagesManager::MESSAGE_FLAG_HAS_REPLY_MARKUP; } if (update->flags_ & MessagesManager::MESSAGE_FLAG_HAS_MEDIA) { LOG(ERROR) << "Receive updateShortChatMessage with media"; update->flags_ ^= MessagesManager::MESSAGE_FLAG_HAS_MEDIA; } update->flags_ |= MessagesManager::MESSAGE_FLAG_HAS_FROM_ID; on_pending_update(make_tl_object<telegram_api::updateNewMessage>( make_tl_object<telegram_api::message>( update->flags_, false /*ignored*/, false /*ignored*/, false /*ignored*/, false /*ignored*/, false /*ignored*/, update->id_, update->from_id_, make_tl_object<telegram_api::peerChat>(update->chat_id_), std::move(update->fwd_from_), update->via_bot_id_, update->reply_to_msg_id_, update->date_, update->message_, nullptr, nullptr, std::move(update->entities_), 0, 0, "", 0), update->pts_, update->pts_count_), 0, "telegram_api::updatesShortChatMessage"); break; } case telegram_api::updateShort::ID: { auto update = move_tl_object_as<telegram_api::updateShort>(updates_ptr); LOG(DEBUG) << "Receive " << to_string(update); if (!is_acceptable_update(update->update_.get())) { LOG(ERROR) << "Receive unacceptable short update: " << td::oneline(to_string(update)); return get_difference("unacceptable short update"); } if (!downcast_call(*update->update_, OnUpdate(this, update->update_, false))) { LOG(ERROR) << "Can't call on some update"; } break; } case telegram_api::updatesCombined::ID: { auto updates = move_tl_object_as<telegram_api::updatesCombined>(updates_ptr); td_->contacts_manager_->on_get_users(std::move(updates->users_)); td_->contacts_manager_->on_get_chats(std::move(updates->chats_)); on_pending_updates(std::move(updates->updates_), updates->seq_start_, updates->seq_, updates->date_, "telegram_api::updatesCombined"); break; } case telegram_api::updates::ID: { auto updates = move_tl_object_as<telegram_api::updates>(updates_ptr); td_->contacts_manager_->on_get_users(std::move(updates->users_)); td_->contacts_manager_->on_get_chats(std::move(updates->chats_)); on_pending_updates(std::move(updates->updates_), updates->seq_, updates->seq_, updates->date_, "telegram_api::updates"); break; } case telegram_api::updateShortSentMessage::ID: LOG(ERROR) << "Receive " << oneline(to_string(updates_ptr)); get_difference("updateShortSentMessage"); break; default: UNREACHABLE(); } } void UpdatesManager::on_failed_get_difference() { schedule_get_difference("on_failed_get_difference"); } void UpdatesManager::schedule_get_difference(const char *source) { LOG(INFO) << "Schedule getDifference from " << source; if (!retry_timeout_.has_timeout()) { retry_timeout_.set_callback(std::move(fill_get_difference_gap)); retry_timeout_.set_callback_data(static_cast<void *>(td_)); retry_timeout_.set_timeout_in(retry_time_); retry_time_ *= 2; if (retry_time_ > 60) { retry_time_ = Random::fast(60, 80); } } } void UpdatesManager::on_get_updates_state(tl_object_ptr<telegram_api::updates_state> &&state, const char *source) { if (state == nullptr) { running_get_difference_ = false; on_failed_get_difference(); return; } LOG(INFO) << "Receive " << oneline(to_string(state)) << " from " << source; // TODO use state->unread_count; if (get_pts() == std::numeric_limits<int32>::max()) { LOG(WARNING) << "Restore pts to " << state->pts_; // restoring right pts pts_manager_.init(state->pts_); last_get_difference_pts_ = get_pts(); } else { string full_source = "on_get_updates_state " + oneline(to_string(state)) + " from " + source; set_pts(state->pts_, full_source.c_str()).set_value(Unit()); set_date(state->date_, false, std::move(full_source)); // set_qts(state->qts_); seq_ = state->seq_; } if (running_get_difference_) { // called from getUpdatesState running_get_difference_ = false; after_get_difference(); } } std::unordered_set<int64> UpdatesManager::get_sent_messages_random_ids(const telegram_api::Updates *updates_ptr) { std::unordered_set<int64> random_ids; const vector<tl_object_ptr<telegram_api::Update>> *updates; switch (updates_ptr->get_id()) { case telegram_api::updatesTooLong::ID: case telegram_api::updateShortMessage::ID: case telegram_api::updateShortChatMessage::ID: case telegram_api::updateShort::ID: case telegram_api::updateShortSentMessage::ID: LOG(ERROR) << "Receive " << oneline(to_string(*updates_ptr)) << " instead of updates"; return random_ids; case telegram_api::updatesCombined::ID: { updates = &static_cast<const telegram_api::updatesCombined *>(updates_ptr)->updates_; break; } case telegram_api::updates::ID: { updates = &static_cast<const telegram_api::updates *>(updates_ptr)->updates_; break; } default: UNREACHABLE(); return random_ids; } for (auto &update : *updates) { if (update->get_id() == telegram_api::updateMessageID::ID) { int64 random_id = static_cast<const telegram_api::updateMessageID *>(update.get())->random_id_; if (!random_ids.insert(random_id).second) { LOG(ERROR) << "Receive twice updateMessageID for " << random_id; } } } return random_ids; } vector<const tl_object_ptr<telegram_api::Message> *> UpdatesManager::get_new_messages( const telegram_api::Updates *updates_ptr) { vector<const tl_object_ptr<telegram_api::Message> *> messages; const vector<tl_object_ptr<telegram_api::Update>> *updates; switch (updates_ptr->get_id()) { case telegram_api::updatesTooLong::ID: case telegram_api::updateShortMessage::ID: case telegram_api::updateShortChatMessage::ID: case telegram_api::updateShort::ID: case telegram_api::updateShortSentMessage::ID: LOG(ERROR) << "Receive " << oneline(to_string(*updates_ptr)) << " instead of updates"; return messages; case telegram_api::updatesCombined::ID: { updates = &static_cast<const telegram_api::updatesCombined *>(updates_ptr)->updates_; break; } case telegram_api::updates::ID: { updates = &static_cast<const telegram_api::updates *>(updates_ptr)->updates_; break; } default: UNREACHABLE(); return messages; } for (auto &update : *updates) { auto constructor_id = update->get_id(); if (constructor_id == telegram_api::updateNewMessage::ID) { messages.emplace_back(&static_cast<const telegram_api::updateNewMessage *>(update.get())->message_); } else if (constructor_id == telegram_api::updateNewChannelMessage::ID) { messages.emplace_back(&static_cast<const telegram_api::updateNewChannelMessage *>(update.get())->message_); } } return messages; } void UpdatesManager::init_state() { if (!td_->auth_manager_->is_authorized()) { return; } auto pmc = G()->td_db()->get_binlog_pmc(); string pts_str = pmc->get("updates.pts"); if (pts_str.empty()) { if (!running_get_difference_) { running_get_difference_ = true; send_closure(G()->state_manager(), &StateManager::on_synchronized, false); td_->create_handler<GetUpdatesStateQuery>()->send(); set_state(State::Type::RunningGetUpdatesState); } return; } pts_manager_.init(to_integer<int32>(pts_str)); last_get_difference_pts_ = get_pts(); qts_ = to_integer<int32>(pmc->get("updates.qts")); date_ = to_integer<int32>(pmc->get("updates.date")); date_source_ = "database"; LOG(DEBUG) << "Init: " << get_pts() << " " << qts_ << " " << date_; send_closure(td_->secret_chats_manager_, &SecretChatsManager::init_qts, qts_); get_difference("init_state"); } void UpdatesManager::process_get_difference_updates( vector<tl_object_ptr<telegram_api::Message>> &&new_messages, vector<tl_object_ptr<telegram_api::EncryptedMessage>> &&new_encrypted_messages, int32 qts, vector<tl_object_ptr<telegram_api::Update>> &&other_updates) { LOG(INFO) << "In get difference receive " << new_messages.size() << " messages, " << new_encrypted_messages.size() << " encrypted messages and " << other_updates.size() << " other updates"; for (auto &update : other_updates) { auto constructor_id = update->get_id(); if (constructor_id == telegram_api::updateMessageID::ID) { on_update(move_tl_object_as<telegram_api::updateMessageID>(update), true); CHECK(!running_get_difference_); } if (constructor_id == telegram_api::updateEncryption::ID) { on_update(move_tl_object_as<telegram_api::updateEncryption>(update), true); CHECK(!running_get_difference_); } /* // TODO can't apply it here, because dialog may not be created yet // process updateReadHistoryInbox before new messages if (constructor_id == telegram_api::updateReadHistoryInbox::ID) { on_update(move_tl_object_as<telegram_api::updateReadHistoryInbox>(update), true); CHECK(!running_get_difference_); } */ } for (auto &message : new_messages) { // channel messages must not be received in this vector td_->messages_manager_->on_get_message(std::move(message), true, false, true, true, "get difference"); CHECK(!running_get_difference_); } for (auto &encrypted_message : new_encrypted_messages) { on_update(make_tl_object<telegram_api::updateNewEncryptedMessage>(std::move(encrypted_message), 0), true); } send_closure(td_->secret_chats_manager_, &SecretChatsManager::update_qts, qts); process_updates(std::move(other_updates), true); } void UpdatesManager::on_get_difference(tl_object_ptr<telegram_api::updates_Difference> &&difference_ptr) { LOG(INFO) << "----- END GET DIFFERENCE-----"; running_get_difference_ = false; if (difference_ptr == nullptr) { on_failed_get_difference(); return; } LOG(DEBUG) << "Result of get difference: " << to_string(difference_ptr); switch (difference_ptr->get_id()) { case telegram_api::updates_differenceEmpty::ID: { auto difference = move_tl_object_as<telegram_api::updates_differenceEmpty>(difference_ptr); set_date(difference->date_, false, "on_get_difference_empty"); seq_ = difference->seq_; break; } case telegram_api::updates_difference::ID: { auto difference = move_tl_object_as<telegram_api::updates_difference>(difference_ptr); td_->contacts_manager_->on_get_users(std::move(difference->users_)); td_->contacts_manager_->on_get_chats(std::move(difference->chats_)); set_state(State::Type::ApplyingDifference); process_get_difference_updates(std::move(difference->new_messages_), std::move(difference->new_encrypted_messages_), difference->state_->qts_, std::move(difference->other_updates_)); if (running_get_difference_) { LOG(ERROR) << "Get difference has run while processing get difference updates"; break; } on_get_updates_state(std::move(difference->state_), "get difference"); break; } case telegram_api::updates_differenceSlice::ID: { auto difference = move_tl_object_as<telegram_api::updates_differenceSlice>(difference_ptr); td_->contacts_manager_->on_get_users(std::move(difference->users_)); td_->contacts_manager_->on_get_chats(std::move(difference->chats_)); set_state(State::Type::ApplyingDifferenceSlice); process_get_difference_updates(std::move(difference->new_messages_), std::move(difference->new_encrypted_messages_), difference->intermediate_state_->qts_, std::move(difference->other_updates_)); if (running_get_difference_) { LOG(ERROR) << "Get difference has run while processing get difference updates"; break; } on_get_updates_state(std::move(difference->intermediate_state_), "get difference slice"); get_difference("on updates_differenceSlice"); break; } case telegram_api::updates_differenceTooLong::ID: { LOG(ERROR) << "Receive differenceTooLong"; // TODO auto difference = move_tl_object_as<telegram_api::updates_differenceTooLong>(difference_ptr); set_pts(difference->pts_, "differenceTooLong").set_value(Unit()); get_difference("on updates_differenceTooLong"); break; } default: UNREACHABLE(); } if (!running_get_difference_) { after_get_difference(); } } void UpdatesManager::after_get_difference() { CHECK(!running_get_difference_); send_closure(td_->secret_chats_manager_, &SecretChatsManager::after_get_difference); auto saved_state = state_; retry_timeout_.cancel_timeout(); retry_time_ = 1; process_pending_seq_updates(); // cancels seq_gap_timeout_, may apply some updates coming before getDifference, but // not returned in getDifference if (running_get_difference_) { return; } if (postponed_updates_.size()) { LOG(INFO) << "Begin to apply postponed updates"; while (!postponed_updates_.empty()) { auto it = postponed_updates_.begin(); auto updates = std::move(it->second.updates); auto updates_seq_begin = it->second.seq_begin; auto updates_seq_end = it->second.seq_end; // ignore it->second.date, because it may be too old postponed_updates_.erase(it); on_pending_updates(std::move(updates), updates_seq_begin, updates_seq_end, 0, "postponed updates"); if (running_get_difference_) { LOG(INFO) << "Finish to apply postponed updates because forced to run getDifference"; return; } } LOG(INFO) << "Finish to apply postponed updates"; } state_ = saved_state; td_->inline_queries_manager_->after_get_difference(); td_->messages_manager_->after_get_difference(); send_closure(G()->state_manager(), &StateManager::on_synchronized, true); set_state(State::Type::General); } void UpdatesManager::on_pending_updates(vector<tl_object_ptr<telegram_api::Update>> &&updates, int32 seq_begin, int32 seq_end, int32 date, const char *source) { if (get_pts() == -1) { init_state(); } if (!td_->auth_manager_->is_authorized()) { LOG(INFO) << "Ignore updates received before authorization or after logout"; return; } // for (auto &update : updates) { // LOG(WARNING) << "Receive update " << to_string(update.get()); // } if (seq_begin < 0 || seq_end < 0 || date < 0 || seq_end < seq_begin) { LOG(ERROR) << "Wrong updates parameters seq_begin = " << seq_begin << ", seq_end = " << seq_end << ", date = " << date << " from " << source; get_difference("on wrong updates in on_pending_updates"); return; } if (running_get_difference_) { LOG(INFO) << "Postpone " << updates.size() << " updates [" << seq_begin << ", " << seq_end << "] with date = " << date << " from " << source; postponed_updates_.emplace(seq_begin, PendingUpdates(seq_begin, seq_end, date, std::move(updates))); return; } // TODO typings must be processed before NewMessage size_t processed_updates = 0; for (auto &update : updates) { if (!is_acceptable_update(update.get())) { CHECK(update != nullptr); int32 id = update->get_id(); const tl_object_ptr<telegram_api::Message> *message_ptr = nullptr; int32 pts = 0; if (id == telegram_api::updateNewChannelMessage::ID) { auto update_new_channel_message = static_cast<const telegram_api::updateNewChannelMessage *>(update.get()); message_ptr = &update_new_channel_message->message_; pts = update_new_channel_message->pts_; } if (id == telegram_api::updateEditChannelMessage::ID) { auto update_edit_channel_message = static_cast<const telegram_api::updateEditChannelMessage *>(update.get()); message_ptr = &update_edit_channel_message->message_; pts = update_edit_channel_message->pts_; } if (message_ptr != nullptr) { auto dialog_id = td_->messages_manager_->get_message_dialog_id(*message_ptr); if (dialog_id.get_type() == DialogType::Channel) { // for channels we can replace unacceptable update with updateChannelTooLong update = telegram_api::make_object<telegram_api::updateChannelTooLong>( telegram_api::updateChannelTooLong::PTS_MASK, dialog_id.get_channel_id().get(), pts); continue; } else { LOG(ERROR) << "Update is not from a channel: " << to_string(update); } } return get_difference("on unacceptable updates in on_pending_updates"); } } set_state(State::Type::ApplyingUpdates); for (auto &update : updates) { if (update != nullptr) { LOG(INFO) << "Receive from " << source << " pending " << to_string(update); int32 id = update->get_id(); if (id == telegram_api::updateMessageID::ID) { LOG(INFO) << "Receive from " << source << " " << to_string(update); auto sent_message_update = move_tl_object_as<telegram_api::updateMessageID>(update); if (!td_->messages_manager_->on_update_message_id( sent_message_update->random_id_, MessageId(ServerMessageId(sent_message_update->id_)), source)) { for (auto &debug_update : updates) { LOG(ERROR) << "Update: " << oneline(to_string(debug_update)); } } processed_updates++; update = nullptr; CHECK(!running_get_difference_); } } } for (auto &update : updates) { if (update != nullptr) { int32 id = update->get_id(); if (id == telegram_api::updateNewMessage::ID || id == telegram_api::updateReadMessagesContents::ID || id == telegram_api::updateEditMessage::ID || id == telegram_api::updateDeleteMessages::ID || id == telegram_api::updateReadHistoryInbox::ID || id == telegram_api::updateReadHistoryOutbox::ID || id == telegram_api::updateWebPage::ID) { if (!downcast_call(*update, OnUpdate(this, update, false))) { LOG(ERROR) << "Can't call on some update received from " << source; } processed_updates++; update = nullptr; } } } if (running_get_difference_) { LOG(INFO) << "Postpone " << updates.size() << " updates [" << seq_begin << ", " << seq_end << "] with date = " << date << " from " << source; postponed_updates_.emplace(seq_begin, PendingUpdates(seq_begin, seq_end, date, std::move(updates))); return; } set_state(State::Type::General); if (processed_updates == updates.size()) { if (seq_begin || seq_end) { LOG(ERROR) << "All updates from " << source << " was processed but seq = " << seq_ << ", seq_begin = " << seq_begin << ", seq_end = " << seq_end; } else { LOG(INFO) << "All updates was processed"; } return; } if (seq_begin == 0 || seq_begin == seq_ + 1) { LOG(INFO) << "Process " << updates.size() << " updates [" << seq_begin << ", " << seq_end << "] with date = " << date << " from " << source; process_seq_updates(seq_end, date, std::move(updates)); process_pending_seq_updates(); return; } if (seq_begin <= seq_) { if (seq_end > seq_) { LOG(ERROR) << "Strange updates from " << source << " coming with seq_begin = " << seq_begin << ", seq_end = " << seq_end << ", but seq = " << seq_; } else { LOG(INFO) << "Old updates from " << source << " coming with seq_begin = " << seq_begin << ", seq_end = " << seq_end << ", but seq = " << seq_; } return; } LOG(INFO) << "Gap in seq has found. Receive " << updates.size() << " updates [" << seq_begin << ", " << seq_end << "] from " << source << ", but seq = " << seq_; LOG_IF(WARNING, pending_seq_updates_.find(seq_begin) != pending_seq_updates_.end()) << "Already have pending updates with seq = " << seq_begin << ", but receive it again from " << source; pending_seq_updates_.emplace(seq_begin, PendingUpdates(seq_begin, seq_end, date, std::move(updates))); set_seq_gap_timeout(MAX_UNFILLED_GAP_TIME); } void UpdatesManager::process_updates(vector<tl_object_ptr<telegram_api::Update>> &&updates, bool force_apply) { tl_object_ptr<telegram_api::updatePtsChanged> update_pts_changed; /* for (auto &update : updates) { if (update != nullptr) { // TODO can't apply it here, because dialog may not be created yet // process updateReadChannelInbox before updateNewChannelMessage auto constructor_id = update->get_id(); if (constructor_id == telegram_api::updateReadChannelInbox::ID) { on_update(move_tl_object_as<telegram_api::updateReadChannelInbox>(update), force_apply); } } } */ for (auto &update : updates) { if (update != nullptr) { // process updateNewChannelMessage first auto constructor_id = update->get_id(); if (constructor_id == telegram_api::updateNewChannelMessage::ID) { on_update(move_tl_object_as<telegram_api::updateNewChannelMessage>(update), force_apply); } // updatePtsChanged forces get difference, so process it last if (constructor_id == telegram_api::updatePtsChanged::ID) { update_pts_changed = move_tl_object_as<telegram_api::updatePtsChanged>(update); } } } for (auto &update : updates) { if (update != nullptr) { LOG(INFO) << "Process update " << to_string(update); if (!downcast_call(*update, OnUpdate(this, update, force_apply))) { LOG(ERROR) << "Can't call on some update"; } CHECK(!running_get_difference_); } } if (update_pts_changed != nullptr) { on_update(std::move(update_pts_changed), force_apply); } } void UpdatesManager::process_seq_updates(int32 seq_end, int32 date, vector<tl_object_ptr<telegram_api::Update>> &&updates) { set_state(State::Type::ApplyingSeqUpdates); string serialized_updates = PSTRING() << "process_seq_updates [seq_ = " << seq_ << ", seq_end = " << seq_end << "]: "; // TODO remove after bugs will be fixed for (auto &update : updates) { if (update != nullptr) { serialized_updates += oneline(to_string(update)); } } process_updates(std::move(updates), false); if (seq_end) { seq_ = seq_end; } if (date && seq_end) { set_date(date, true, std::move(serialized_updates)); } if (!running_get_difference_) { set_state(State::Type::General); } } void UpdatesManager::process_pending_seq_updates() { while (!pending_seq_updates_.empty() && !running_get_difference_) { auto update_it = pending_seq_updates_.begin(); auto seq_begin = update_it->second.seq_begin; if (seq_begin > seq_ + 1) { break; } if (seq_begin == seq_ + 1) { process_seq_updates(update_it->second.seq_end, update_it->second.date, std::move(update_it->second.updates)); } else { // old update CHECK(seq_begin != 0); LOG_IF(ERROR, update_it->second.seq_end > seq_) << "Strange updates coming with seq_begin = " << seq_begin << ", seq_end = " << update_it->second.seq_end << ", but seq = " << seq_; } pending_seq_updates_.erase(update_it); } if (pending_seq_updates_.empty()) { seq_gap_timeout_.cancel_timeout(); } } void UpdatesManager::set_seq_gap_timeout(double timeout) { if (!seq_gap_timeout_.has_timeout()) { seq_gap_timeout_.set_callback(std::move(fill_seq_gap)); seq_gap_timeout_.set_callback_data(static_cast<void *>(td_)); seq_gap_timeout_.set_timeout_in(timeout); } } void UpdatesManager::on_pending_update(tl_object_ptr<telegram_api::Update> update, int32 seq, const char *source) { vector<tl_object_ptr<telegram_api::Update>> v; v.push_back(std::move(update)); on_pending_updates(std::move(v), seq, seq, 0, source); // TODO can be optimized } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateNewMessage> update, bool force_apply) { CHECK(update != nullptr); int new_pts = update->pts_; int pts_count = update->pts_count_; td_->messages_manager_->add_pending_update(std::move(update), new_pts, pts_count, force_apply, "on_updateNewMessage"); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateNewChannelMessage> update, bool /*force_apply*/) { CHECK(update != nullptr); td_->messages_manager_->on_update_new_channel_message(std::move(update)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateMessageID> update, bool force_apply) { CHECK(update != nullptr); if (!force_apply) { LOG(ERROR) << "Receive updateMessageID not in getDifference"; return; } LOG(INFO) << "Receive update about sent message " << to_string(update); td_->messages_manager_->on_update_message_id(update->random_id_, MessageId(ServerMessageId(update->id_)), "getDifference"); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateReadMessagesContents> update, bool force_apply) { CHECK(update != nullptr); int new_pts = update->pts_; int pts_count = update->pts_count_; td_->messages_manager_->add_pending_update(std::move(update), new_pts, pts_count, force_apply, "on_updateReadMessagesContents"); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateEditMessage> update, bool force_apply) { CHECK(update != nullptr); int new_pts = update->pts_; int pts_count = update->pts_count_; td_->messages_manager_->add_pending_update(std::move(update), new_pts, pts_count, force_apply, "on_updateEditMessage"); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateDeleteMessages> update, bool force_apply) { CHECK(update != nullptr); int new_pts = update->pts_; int pts_count = update->pts_count_; if (update->messages_.empty()) { td_->messages_manager_->add_pending_update(make_tl_object<dummyUpdate>(), new_pts, pts_count, force_apply, "on_updateDeleteMessages"); } else { td_->messages_manager_->add_pending_update(std::move(update), new_pts, pts_count, force_apply, "on_updateDeleteMessages"); } } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateReadHistoryInbox> update, bool force_apply) { CHECK(update != nullptr); int new_pts = update->pts_; int pts_count = update->pts_count_; td_->messages_manager_->add_pending_update(std::move(update), new_pts, pts_count, force_apply, "on_updateReadHistoryInbox"); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateReadHistoryOutbox> update, bool force_apply) { CHECK(update != nullptr); int new_pts = update->pts_; int pts_count = update->pts_count_; td_->messages_manager_->add_pending_update(std::move(update), new_pts, pts_count, force_apply, "on_updateReadHistoryOutbox"); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateServiceNotification> update, bool /*force_apply*/) { CHECK(update != nullptr); td_->messages_manager_->on_update_service_notification(std::move(update)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateContactRegistered> update, bool /*force_apply*/) { CHECK(update != nullptr); td_->messages_manager_->on_update_contact_registered(std::move(update)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateReadChannelInbox> update, bool /*force_apply*/) { CHECK(update != nullptr); td_->messages_manager_->on_update_read_channel_inbox(std::move(update)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateReadChannelOutbox> update, bool /*force_apply*/) { CHECK(update != nullptr); td_->messages_manager_->on_update_read_channel_outbox(std::move(update)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateChannelReadMessagesContents> update, bool /*force_apply*/) { td_->messages_manager_->on_update_read_channel_messages_contents(std::move(update)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateChannelTooLong> update, bool force_apply) { td_->messages_manager_->on_update_channel_too_long(std::move(update), force_apply); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateChannel> update, bool /*force_apply*/) { // nothing to do } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateEditChannelMessage> update, bool /*force_apply*/) { td_->messages_manager_->on_update_edit_channel_message(std::move(update)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateDeleteChannelMessages> update, bool /*force_apply*/) { ChannelId channel_id(update->channel_id_); if (!channel_id.is_valid()) { LOG(ERROR) << "Receive invalid " << channel_id; return; } DialogId dialog_id(channel_id); int new_pts = update->pts_; int pts_count = update->pts_count_; td_->messages_manager_->add_pending_channel_update(dialog_id, std::move(update), new_pts, pts_count, "on_updateDeleteChannelMessages"); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateChannelMessageViews> update, bool /*force_apply*/) { ChannelId channel_id(update->channel_id_); if (!channel_id.is_valid()) { LOG(ERROR) << "Receive invalid " << channel_id; return; } DialogId dialog_id(channel_id); td_->messages_manager_->on_update_message_views({dialog_id, MessageId(ServerMessageId(update->id_))}, update->views_); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateChannelPinnedMessage> update, bool /*force_apply*/) { td_->contacts_manager_->on_update_channel_pinned_message(ChannelId(update->channel_id_), MessageId(ServerMessageId(update->id_))); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateChannelAvailableMessages> update, bool /*force_apply*/) { td_->messages_manager_->on_update_channel_max_unavailable_message_id( ChannelId(update->channel_id_), MessageId(ServerMessageId(update->available_min_id_))); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateNotifySettings> update, bool /*force_apply*/) { CHECK(update != nullptr); td_->messages_manager_->on_update_notify_settings( td_->messages_manager_->get_notification_settings_scope(std::move(update->peer_)), std::move(update->notify_settings_)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateWebPage> update, bool force_apply) { CHECK(update != nullptr); td_->web_pages_manager_->on_get_web_page(std::move(update->webpage_), DialogId()); td_->messages_manager_->add_pending_update(make_tl_object<dummyUpdate>(), update->pts_, update->pts_count_, force_apply, "on_updateWebPage"); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateChannelWebPage> update, bool /*force_apply*/) { CHECK(update != nullptr); td_->web_pages_manager_->on_get_web_page(std::move(update->webpage_), DialogId()); ChannelId channel_id(update->channel_id_); if (!channel_id.is_valid()) { LOG(ERROR) << "Receive invalid " << channel_id; return; } DialogId dialog_id(channel_id); td_->messages_manager_->add_pending_channel_update(dialog_id, make_tl_object<dummyUpdate>(), update->pts_, update->pts_count_, "on_updateChannelWebPage"); } tl_object_ptr<td_api::ChatAction> UpdatesManager::convertSendMessageAction( tl_object_ptr<telegram_api::SendMessageAction> action) { auto fix_progress = [](int32 progress) { return progress <= 0 || progress > 100 ? 0 : progress; }; switch (action->get_id()) { case telegram_api::sendMessageCancelAction::ID: return make_tl_object<td_api::chatActionCancel>(); case telegram_api::sendMessageTypingAction::ID: return make_tl_object<td_api::chatActionTyping>(); case telegram_api::sendMessageRecordVideoAction::ID: return make_tl_object<td_api::chatActionRecordingVideo>(); case telegram_api::sendMessageUploadVideoAction::ID: { auto upload_video_action = move_tl_object_as<telegram_api::sendMessageUploadVideoAction>(action); return make_tl_object<td_api::chatActionUploadingVideo>(fix_progress(upload_video_action->progress_)); } case telegram_api::sendMessageRecordAudioAction::ID: return make_tl_object<td_api::chatActionRecordingVoiceNote>(); case telegram_api::sendMessageUploadAudioAction::ID: { auto upload_audio_action = move_tl_object_as<telegram_api::sendMessageUploadAudioAction>(action); return make_tl_object<td_api::chatActionUploadingVoiceNote>(fix_progress(upload_audio_action->progress_)); } case telegram_api::sendMessageUploadPhotoAction::ID: { auto upload_photo_action = move_tl_object_as<telegram_api::sendMessageUploadPhotoAction>(action); return make_tl_object<td_api::chatActionUploadingPhoto>(fix_progress(upload_photo_action->progress_)); } case telegram_api::sendMessageUploadDocumentAction::ID: { auto upload_document_action = move_tl_object_as<telegram_api::sendMessageUploadDocumentAction>(action); return make_tl_object<td_api::chatActionUploadingDocument>(fix_progress(upload_document_action->progress_)); } case telegram_api::sendMessageGeoLocationAction::ID: return make_tl_object<td_api::chatActionChoosingLocation>(); case telegram_api::sendMessageChooseContactAction::ID: return make_tl_object<td_api::chatActionChoosingContact>(); case telegram_api::sendMessageGamePlayAction::ID: return make_tl_object<td_api::chatActionStartPlayingGame>(); case telegram_api::sendMessageRecordRoundAction::ID: return make_tl_object<td_api::chatActionRecordingVideoNote>(); case telegram_api::sendMessageUploadRoundAction::ID: { auto upload_round_action = move_tl_object_as<telegram_api::sendMessageUploadRoundAction>(action); return make_tl_object<td_api::chatActionUploadingVideoNote>(fix_progress(upload_round_action->progress_)); } default: UNREACHABLE(); } } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateUserTyping> update, bool /*force_apply*/) { UserId user_id(update->user_id_); if (!td_->contacts_manager_->have_min_user(user_id)) { LOG(DEBUG) << "Ignore user typing of unknown " << user_id; return; } DialogId dialog_id(user_id); if (!td_->messages_manager_->have_dialog(dialog_id)) { LOG(DEBUG) << "Ignore user typing in unknown " << dialog_id; return; } send_closure(G()->td(), &Td::send_update, make_tl_object<td_api::updateUserChatAction>(dialog_id.get(), user_id.get(), convertSendMessageAction(std::move(update->action_)))); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateChatUserTyping> update, bool /*force_apply*/) { UserId user_id(update->user_id_); if (!td_->contacts_manager_->have_min_user(user_id)) { LOG(DEBUG) << "Ignore user chat typing of unknown " << user_id; return; } ChatId chat_id(update->chat_id_); DialogId dialog_id(chat_id); if (!td_->messages_manager_->have_dialog(dialog_id)) { ChannelId channel_id(update->chat_id_); dialog_id = DialogId(channel_id); if (!td_->messages_manager_->have_dialog(dialog_id)) { LOG(DEBUG) << "Ignore user chat typing in unknown " << dialog_id; return; } } send_closure(G()->td(), &Td::send_update, make_tl_object<td_api::updateUserChatAction>(dialog_id.get(), user_id.get(), convertSendMessageAction(std::move(update->action_)))); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateEncryptedChatTyping> update, bool /*force_apply*/) { SecretChatId secret_chat_id(update->chat_id_); DialogId dialog_id(secret_chat_id); if (!td_->messages_manager_->have_dialog(dialog_id)) { LOG(DEBUG) << "Ignore secret chat typing in unknown " << dialog_id; return; } UserId user_id = td_->contacts_manager_->get_secret_chat_user_id(secret_chat_id); if (!user_id.is_valid()) { LOG(DEBUG) << "Ignore secret chat typing of unknown " << user_id; return; } send_closure(G()->td(), &Td::send_update, make_tl_object<td_api::updateUserChatAction>(dialog_id.get(), user_id.get(), make_tl_object<td_api::chatActionTyping>())); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateUserStatus> update, bool /*force_apply*/) { td_->contacts_manager_->on_update_user_online(UserId(update->user_id_), std::move(update->status_)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateUserName> update, bool /*force_apply*/) { td_->contacts_manager_->on_update_user_name(UserId(update->user_id_), std::move(update->first_name_), std::move(update->last_name_), std::move(update->username_)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateUserPhone> update, bool /*force_apply*/) { td_->contacts_manager_->on_update_user_phone_number(UserId(update->user_id_), std::move(update->phone_)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateUserPhoto> update, bool /*force_apply*/) { // TODO update->previous_, update->date_ td_->contacts_manager_->on_update_user_photo(UserId(update->user_id_), std::move(update->photo_)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateUserBlocked> update, bool /*force_apply*/) { td_->contacts_manager_->on_update_user_blocked(UserId(update->user_id_), update->blocked_); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateContactLink> update, bool /*force_apply*/) { td_->contacts_manager_->on_update_user_links(UserId(update->user_id_), std::move(update->my_link_), std::move(update->foreign_link_)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateChatParticipants> update, bool /*force_apply*/) { td_->contacts_manager_->on_get_chat_participants(std::move(update->participants_)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateChatParticipantAdd> update, bool /*force_apply*/) { td_->contacts_manager_->on_update_chat_add_user(ChatId(update->chat_id_), UserId(update->inviter_id_), UserId(update->user_id_), update->date_, update->version_); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateChatParticipantAdmin> update, bool /*force_apply*/) { td_->contacts_manager_->on_update_chat_edit_administrator(ChatId(update->chat_id_), UserId(update->user_id_), update->is_admin_, update->version_); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateChatParticipantDelete> update, bool /*force_apply*/) { td_->contacts_manager_->on_update_chat_delete_user(ChatId(update->chat_id_), UserId(update->user_id_), update->version_); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateChatAdmins> update, bool /*force_apply*/) { td_->contacts_manager_->on_update_chat_everyone_is_administrator(ChatId(update->chat_id_), !update->enabled_, update->version_); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateDraftMessage> update, bool /*force_apply*/) { td_->messages_manager_->on_update_dialog_draft_message(DialogId(update->peer_), std::move(update->draft_)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateDialogPinned> update, bool /*force_apply*/) { td_->messages_manager_->on_update_dialog_pinned( DialogId(update->peer_), (update->flags_ & telegram_api::updateDialogPinned::PINNED_MASK) != 0); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updatePinnedDialogs> update, bool /*force_apply*/) { td_->messages_manager_->on_update_pinned_dialogs(); // TODO use update->order_ } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateDcOptions> update, bool /*force_apply*/) { send_closure(G()->config_manager(), &ConfigManager::on_dc_options_update, DcOptions(update->dc_options_)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateBotInlineQuery> update, bool /*force_apply*/) { td_->inline_queries_manager_->on_new_query(update->query_id_, UserId(update->user_id_), Location(update->geo_), update->query_, update->offset_); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateBotInlineSend> update, bool /*force_apply*/) { td_->inline_queries_manager_->on_chosen_result(UserId(update->user_id_), Location(update->geo_), update->query_, update->id_, std::move(update->msg_id_)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateBotCallbackQuery> update, bool /*force_apply*/) { td_->callback_queries_manager_->on_new_query(update->flags_, update->query_id_, UserId(update->user_id_), DialogId(update->peer_), MessageId(ServerMessageId(update->msg_id_)), std::move(update->data_), update->chat_instance_, std::move(update->game_short_name_)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateInlineBotCallbackQuery> update, bool /*force_apply*/) { td_->callback_queries_manager_->on_new_inline_query(update->flags_, update->query_id_, UserId(update->user_id_), std::move(update->msg_id_), std::move(update->data_), update->chat_instance_, std::move(update->game_short_name_)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateFavedStickers> update, bool /*force_apply*/) { td_->stickers_manager_->reload_favorite_stickers(true); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateSavedGifs> update, bool /*force_apply*/) { td_->animations_manager_->reload_saved_animations(true); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateConfig> update, bool /*force_apply*/) { send_closure(td_->config_manager_, &ConfigManager::request_config); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updatePtsChanged> update, bool /*force_apply*/) { set_pts(std::numeric_limits<int32>::max(), "updatePtsChanged").set_value(Unit()); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateEncryption> update, bool /*force_apply*/) { send_closure(td_->secret_chats_manager_, &SecretChatsManager::on_update_chat, std::move(update)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateNewEncryptedMessage> update, bool force_apply) { send_closure(td_->secret_chats_manager_, &SecretChatsManager::on_update_message, std::move(update), force_apply); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateEncryptedMessagesRead> update, bool /*force_apply*/) { td_->messages_manager_->read_secret_chat_outbox(SecretChatId(update->chat_id_), update->max_date_, update->date_); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updatePrivacy> update, bool /*force_apply*/) { send_closure(td_->privacy_manager_, &PrivacyManager::update_privacy, std::move(update)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateNewStickerSet> update, bool /*force_apply*/) { td_->stickers_manager_->on_get_messages_sticker_set(0, std::move(update->stickerset_), true); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateStickerSets> update, bool /*force_apply*/) { td_->stickers_manager_->on_update_sticker_sets(); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateStickerSetsOrder> update, bool /*force_apply*/) { bool is_masks = (update->flags_ & telegram_api::updateStickerSetsOrder::MASKS_MASK) != 0; td_->stickers_manager_->on_update_sticker_sets_order(is_masks, update->order_); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateReadFeaturedStickers> update, bool /*force_apply*/) { td_->stickers_manager_->reload_featured_sticker_sets(true); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateRecentStickers> update, bool /*force_apply*/) { td_->stickers_manager_->reload_recent_stickers(false, true); td_->stickers_manager_->reload_recent_stickers(true, true); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateBotShippingQuery> update, bool /*force_apply*/) { UserId user_id(update->user_id_); if (!user_id.is_valid()) { LOG(ERROR) << "Receive shipping query from invalid " << user_id; return; } CHECK(update->shipping_address_ != nullptr); send_closure(G()->td(), &Td::send_update, make_tl_object<td_api::updateNewShippingQuery>( update->query_id_, user_id.get(), update->payload_.as_slice().str(), get_shipping_address_object(get_shipping_address( std::move(update->shipping_address_))))); // TODO use convert_shipping_address } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateBotPrecheckoutQuery> update, bool /*force_apply*/) { UserId user_id(update->user_id_); if (!user_id.is_valid()) { LOG(ERROR) << "Receive pre-checkout query from invalid " << user_id; return; } send_closure( G()->td(), &Td::send_update, make_tl_object<td_api::updateNewPreCheckoutQuery>( update->query_id_, user_id.get(), update->currency_, update->total_amount_, update->payload_.as_slice().str(), update->shipping_option_id_, get_order_info_object(get_order_info(std::move(update->info_))))); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateBotWebhookJSON> update, bool /*force_apply*/) { send_closure(G()->td(), &Td::send_update, make_tl_object<td_api::updateNewCustomEvent>(update->data_->data_)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateBotWebhookJSONQuery> update, bool /*force_apply*/) { send_closure(G()->td(), &Td::send_update, make_tl_object<td_api::updateNewCustomQuery>(update->query_id_, update->data_->data_, update->timeout_)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updatePhoneCall> update, bool /*force_apply*/) { send_closure(G()->call_manager(), &CallManager::update_call, std::move(update)); } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateContactsReset> update, bool /*force_apply*/) { td_->contacts_manager_->on_update_contacts_reset(); } // unsupported updates void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateLangPackTooLong> update, bool /*force_apply*/) { } void UpdatesManager::on_update(tl_object_ptr<telegram_api::updateLangPack> update, bool /*force_apply*/) { } } // namespace td
2ae818cb648154e8589fcdea2f83452ac345bdb9
193f6b964b1a030d1e819ca4932fb2b829e2e41c
/Framework/Render/ConstBuffer.h
6293733dac6bb5acc38dc8d1b2c8148774d47e36
[]
no_license
fkem79/DX11_Team_HomeSweetHome
cef13f869bee16fb2bbfe401364a2d4293925b2f
27b5b45ddcaaa407eb7e385f0ac63bdbd75c46e2
refs/heads/master
2021-05-18T20:34:29.754175
2020-05-10T16:37:20
2020-05-10T16:37:20
251,392,881
1
0
null
2020-05-08T12:57:25
2020-03-30T18:25:32
C++
UTF-8
C++
false
false
323
h
#pragma once class ConstBuffer { private: ID3D11Buffer* buffer; void* data; UINT dataSize; protected: ConstBuffer(void* data, UINT dataSize); virtual ~ConstBuffer(); void MapData(); public: void SetVSBuffer(UINT slot); void SetPSBuffer(UINT slot); void SetGSBuffer(UINT slot); void SetCSBuffer(UINT slot); };
d680eba4b9e0c12d82ee185c89abc4ec1b6ab983
745f4ab36df82211cdda98cf3240116f99d72648
/ArrayProgram.cpp
3af5b952b9ef4be5ad674703b270449a0d67a309
[]
no_license
GhulamMustafaGM/ILoveProgramming
c270ac73c42d0e72384043d2769cc4960681a391
516fd9cc113d0edadc6fda0e0d545fa08e34e209
refs/heads/master
2023-01-02T01:32:47.158055
2020-10-26T14:30:18
2020-10-26T14:30:18
216,835,476
0
0
null
null
null
null
UTF-8
C++
false
false
243
cpp
#include <iostream> #include <string> using namespace std; int main() { string cars[5] = {"Scania", "Toyota", "Suzuki", "BMW", "Volvo" }; for (int i = 0; i < 5; i++) { cout << cars[i] << endl; } return 0; }
b18a8add7284ae921c80bb52be194ba308920c90
6673340e0102ef4205019c8e262377fd2d244e0c
/Training/Chapter 5/5.5/hidden.cpp
6fc9c1ea991001a224c717be917741b0ff45b4a0
[]
no_license
arponr/usaco
3b71c23fac7a03c993b0a4344a4eeb3e7ae53046
f558a5f640dcb96867fd7235b778d07e9c6746a0
refs/heads/master
2021-01-02T23:12:46.215677
2014-12-16T18:49:44
2014-12-16T18:49:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
678
cpp
/* ID: arpon.r1 PROG: hidden LANG: C++ */ #include <cstdio> #include <cstring> using namespace std; FILE *in = fopen ("hidden.in", "r"), *out = fopen ("hidden.out", "w"); const int MAXL = 2 * 100005, LINE = 72; char pass [MAXL]; int L, ind = 0; int main () { fscanf (in, "%d\n", &L); for (int i = 0; i < L; i += LINE) fscanf (in, "%s", pass + i); memcpy (pass + L, pass, L); for (int i = 1; i < L; i++) { char *p = pass + i, *q = pass + ind; int j; for (j = 0; j < L && *p == *q; j++, p++, q++) ; if (*p < *q) ind = i; if (j > 1) i += j - 1; } fprintf (out, "%d\n", ind); return 0; }
1a5a564e6ef1adf5fd1187c7bc02d73888e96d55
04cdc91f88a137e2f7d470b0ef713d72f79f9d47
/Vitis_Platform_Creation/Feature_Tutorials/03_Vitis_Export_To_Vivado/aie/graph.cpp
b7904f228a33f31608913f6e3d7c77c706bfc087
[ "MIT" ]
permissive
Xilinx/Vitis-Tutorials
80b6945c88406d0669326bb13b222b5a44fcc0c7
ab39b8482dcbd2264ccb9462910609e714f1d10d
refs/heads/2023.1
2023-09-05T11:59:43.272473
2023-08-21T16:43:31
2023-08-21T16:43:31
211,912,254
926
611
MIT
2023-08-03T03:20:33
2019-09-30T17:08:51
C
UTF-8
C++
false
false
340
cpp
/* Copyright (C) 2023, Advanced Micro Devices, Inc. All rights reserved. SPDX-License-Identifier: MIT */ #include "graph.h" clipped clipgraph; int main(int argc, char ** argv) { clipgraph.init(); clipgraph.run(4); // Note: The number of iterations can be changed if needed based on the input clipgraph.end(); return 0; }
c7dde553a2b873e3156f2849fe844ab5b4c37b83
68cf9307614aefa396f7333fc57f786c3b6c0e39
/source/project/engine/rhid3d11/renderwnd.cpp
66e3f7f9a3593530a9add09ea7de77f6b0a15d22
[ "MIT" ]
permissive
lfyjnui/game
3ba195313115de9459f7217b91084e9bd30cf019
f79787ff1ae81f39fd790a589d6e5e0e8925af2b
refs/heads/master
2020-04-25T15:37:21.616119
2019-03-12T07:29:52
2019-03-12T07:29:52
172,882,546
0
0
null
null
null
null
UTF-8
C++
false
false
4,443
cpp
#include "device.h" #include "renderwnd.h" #include <d3d11.h> #include <windows.h> #include <DirectXMath.h> template<typename T> void SafeRelease(T*& p) { if (p) { p->Release(); p = nullptr; } } namespace d3d11 { RenderWindow g_RenderWindow; RenderWindow * GetRenderWnd() { return &g_RenderWindow; } bool RenderWindow::Create(void * hWnd) { m_hWnd = hWnd; HRESULT hr = S_OK; RECT rc; GetClientRect((HWND)m_hWnd, &rc); UINT width = rc.right - rc.left; UINT height = rc.bottom - rc.top; DXGI_SWAP_CHAIN_DESC sd = {}; sd.BufferCount = 2; sd.BufferDesc.Width = width; sd.BufferDesc.Height = height; sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; sd.BufferDesc.RefreshRate.Numerator = 60; sd.BufferDesc.RefreshRate.Denominator = 1; sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; sd.OutputWindow = (HWND)hWnd; sd.SampleDesc.Count = 1; sd.SampleDesc.Quality = 0; sd.Windowed = TRUE; ID3D11Device* pD3dDevice = GetD3dDevice(); IDXGIFactory1* dxgiFactory = nullptr; { IDXGIDevice* dxgiDevice = nullptr; hr = pD3dDevice->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgiDevice)); if (SUCCEEDED(hr)) { IDXGIAdapter* adapter = nullptr; hr = dxgiDevice->GetAdapter(&adapter); if (SUCCEEDED(hr)) { hr = adapter->GetParent(__uuidof(IDXGIFactory1), reinterpret_cast<void**>(&dxgiFactory)); adapter->Release(); } dxgiDevice->Release(); } } if (FAILED(hr)) return false; hr = dxgiFactory->CreateSwapChain(GetD3dDevice(), &sd, m_pSwapChain.GetAddressOf()); dxgiFactory->MakeWindowAssociation((HWND)m_hWnd, DXGI_MWA_NO_ALT_ENTER); SafeRelease(dxgiFactory); m_vp.Width = (FLOAT)width; m_vp.Height = (FLOAT)height; m_vp.MinDepth = 0.0f; m_vp.MaxDepth = 1.0f; m_vp.TopLeftX = 0; m_vp.TopLeftY = 0; Build(); return true; } void RenderWindow::Build() { HRESULT hr = S_OK; ID3D11Device* pD3dDevice = GetD3dDevice(); ID3D11Texture2D* pBackBuffer = nullptr; hr = m_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&pBackBuffer)); if (FAILED(hr)) return; hr = pD3dDevice->CreateRenderTargetView(pBackBuffer, nullptr, m_pRenderTargetView.GetAddressOf()); if (FAILED(hr)) return; D3D11_TEXTURE2D_DESC backbuffer_desc; pBackBuffer->GetDesc(&backbuffer_desc); SafeRelease(pBackBuffer); D3D11_TEXTURE2D_DESC descDepth = {}; descDepth.Width = backbuffer_desc.Width; descDepth.Height = backbuffer_desc.Height; descDepth.MipLevels = 1; descDepth.ArraySize = 1; descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; descDepth.SampleDesc.Count = 1; descDepth.SampleDesc.Quality = 0; descDepth.Usage = D3D11_USAGE_DEFAULT; descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL; descDepth.CPUAccessFlags = 0; descDepth.MiscFlags = 0; hr = pD3dDevice->CreateTexture2D(&descDepth, nullptr, m_pDepthStencilTex.ReleaseAndGetAddressOf()); if (FAILED(hr)) return; // Create the depth stencil view D3D11_DEPTH_STENCIL_VIEW_DESC descDSV = {}; descDSV.Format = descDepth.Format; descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; descDSV.Texture2D.MipSlice = 0; m_pDepthStencilView = nullptr; hr = pD3dDevice->CreateDepthStencilView(m_pDepthStencilTex.Get(), &descDSV, m_pDepthStencilView.ReleaseAndGetAddressOf()); if (FAILED(hr)) return; } void RenderWindow::Resize(uint32_t width, uint32_t height) { m_pRenderTargetView.Reset(); m_pDepthStencilView.Reset(); m_pDepthStencilTex.Reset(); HRESULT hr = m_pSwapChain->ResizeBuffers(1, width, height, DXGI_FORMAT_R8G8B8A8_UNORM, 0); Build(); m_vp.Width = (FLOAT)width; m_vp.Height = (FLOAT)height; m_vp.MinDepth = 0.0f; m_vp.MaxDepth = 1.0f; m_vp.TopLeftX = 0; m_vp.TopLeftY = 0; } bool RenderWindow::Begin() { ID3D11DeviceContext* pImmediateContext = GetImmediateContext(); pImmediateContext->OMSetRenderTargets(1, m_pRenderTargetView.GetAddressOf(), m_pDepthStencilView.Get()); pImmediateContext->RSSetViewports(1, &m_vp); DirectX::XMVECTORF32 color = { 0.45f, 0.55f, 0.60f, 1.00f }; pImmediateContext->ClearRenderTargetView(m_pRenderTargetView.Get(), color); pImmediateContext->ClearDepthStencilView(m_pDepthStencilView.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0); return true; } bool RenderWindow::End(bool bVsync) { HRESULT hr = m_pSwapChain->Present(bVsync ? 1 : 0, 0); return SUCCEEDED(hr); } }
d92061e297914f77201a1230cdbb9a728dec5873
04b1803adb6653ecb7cb827c4f4aa616afacf629
/chrome/browser/vr/testapp/vr_test_context.h
0c62e85835b28c747c06a313f2bd481be45b3ca2
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
3,995
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_VR_TESTAPP_VR_TEST_CONTEXT_H_ #define CHROME_BROWSER_VR_TESTAPP_VR_TEST_CONTEXT_H_ #include <memory> #include <queue> #include "base/macros.h" #include "base/time/time.h" #include "chrome/browser/vr/content_input_delegate.h" #include "chrome/browser/vr/model/controller_model.h" #include "chrome/browser/vr/ui_browser_interface.h" #include "chrome/browser/vr/ui_interface.h" #include "third_party/skia/include/core/SkColor.h" #include "ui/gfx/transform.h" namespace ui { class Event; } namespace vr { class GraphicsDelegate; class TestKeyboardDelegate; class Ui; struct Model; // This class provides a home for the VR UI in a testapp context, and // manipulates the UI according to user input. class VrTestContext : public vr::UiBrowserInterface { public: explicit VrTestContext(GraphicsDelegate* compositor_delgate); ~VrTestContext() override; // TODO(crbug/895313): Make use of BrowserRenderer. void DrawFrame(); void HandleInput(ui::Event* event); // vr::UiBrowserInterface implementation (UI calling to VrShell). void ExitPresent() override; void ExitFullscreen() override; void NavigateBack() override; void NavigateForward() override; void ReloadTab() override; void OpenNewTab(bool incognito) override; void OpenBookmarks() override; void OpenRecentTabs() override; void OpenHistory() override; void OpenDownloads() override; void OpenShare() override; void OpenSettings() override; void CloseAllIncognitoTabs() override; void OpenFeedback() override; void CloseHostedDialog() override; void OnUnsupportedMode(vr::UiUnsupportedMode mode) override; void OnExitVrPromptResult(vr::ExitVrPromptChoice choice, vr::UiUnsupportedMode reason) override; void OnContentScreenBoundsChanged(const gfx::SizeF& bounds) override; void SetVoiceSearchActive(bool active) override; void StartAutocomplete(const AutocompleteRequest& request) override; void StopAutocomplete() override; void ShowPageInfo() override; void Navigate(GURL gurl, NavigationMethod method) override; void set_window_size(const gfx::Size& size) { window_size_ = size; } private: void InitializeGl(); unsigned int CreateTexture(SkColor color); void CreateFakeVoiceSearchResult(); void CycleWebVrModes(); void ToggleSplashScreen(); void CycleOrigin(); void CycleIndicators(); RenderInfo GetRenderInfo() const; gfx::Transform ProjectionMatrix() const; gfx::Transform ViewProjectionMatrix() const; ControllerModel UpdateController(const RenderInfo& render_info, base::TimeTicks current_time); gfx::Point3F LaserOrigin() const; void LoadAssets(); std::unique_ptr<Ui> ui_instance_; UiInterface* ui_; gfx::Size window_size_; gfx::Transform head_pose_; float head_angle_x_degrees_ = 0; float head_angle_y_degrees_ = 0; int last_drag_x_pixels_ = 0; int last_drag_y_pixels_ = 0; gfx::Point last_mouse_point_; bool touchpad_pressed_ = false; gfx::PointF touchpad_touch_position_; float view_scale_factor_ = 1.f; // This avoids storing a duplicate of the model state here. Model* model_; bool web_vr_mode_ = false; bool webvr_frames_received_ = false; bool fullscreen_ = false; bool incognito_ = false; bool show_web_vr_splash_screen_ = false; bool voice_search_enabled_ = false; bool touching_touchpad_ = false; bool recentered_ = false; base::TimeTicks page_load_start_; bool hosted_ui_enabled_ = false; GraphicsDelegate* graphics_delegate_; TestKeyboardDelegate* keyboard_delegate_; ControllerModel::Handedness handedness_ = ControllerModel::kRightHanded; std::queue<InputEventList> input_event_lists_; DISALLOW_COPY_AND_ASSIGN(VrTestContext); }; } // namespace vr #endif // CHROME_BROWSER_VR_TESTAPP_VR_TEST_CONTEXT_H_
b3fe07660b6c845d9685cebfc8ceac1333852f2f
243af6f697c16c54af3613988ddaef62a2b29212
/firmware/uvc_controller/mbed-os/TESTS/mbed_hal/qspi/qspi_test_utils.h
8e41aa89519228138e29faf0843a69d42bdf6b4d
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
davewhiiite/uvc
0020fcc99d279a70878baf7cdc5c02c19b08499a
fd45223097eed5a824294db975b3c74aa5f5cc8f
refs/heads/main
2023-05-29T10:18:08.520756
2021-06-12T13:06:40
2021-06-12T13:06:40
376,287,264
1
0
null
null
null
null
UTF-8
C++
false
false
6,172
h
/* mbed Microcontroller Library * Copyright (c) 2018-2018 ARM Limited * SPDX-License-Identifier: Apache-2.0 * * 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 MBED_QSPI_TEST_UTILS_H #define MBED_QSPI_TEST_UTILS_H #include "flash_configs/flash_configs.h" #include "unity/unity.h" #define QSPI_NONE (-1) enum QspiStatus { sOK, sError, sTimeout, sUnknown }; class QspiCommand { public: void configure(qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width, qspi_bus_width_t alt_width, qspi_address_size_t addr_size, qspi_alt_size_t alt_size, int dummy_cycles = 0); void set_dummy_cycles(int dummy_cycles); void build(int instruction, int address = QSPI_NONE, int alt = QSPI_NONE); qspi_command_t *get(); private: qspi_command_t _cmd; }; struct Qspi { qspi_t handle; QspiCommand cmd; }; // MODE_Command_Address_Data_Alt #define MODE_1_1_1 QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_SINGLE #define MODE_1_1_2 QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_DUAL, QSPI_CFG_BUS_DUAL #define MODE_1_2_2 QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_DUAL, QSPI_CFG_BUS_DUAL, QSPI_CFG_BUS_DUAL #define MODE_2_2_2 QSPI_CFG_BUS_DUAL, QSPI_CFG_BUS_DUAL, QSPI_CFG_BUS_DUAL, QSPI_CFG_BUS_DUAL #define MODE_1_1_4 QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_QUAD, QSPI_CFG_BUS_QUAD #define MODE_1_4_4 QSPI_CFG_BUS_SINGLE, QSPI_CFG_BUS_QUAD, QSPI_CFG_BUS_QUAD, QSPI_CFG_BUS_QUAD #define MODE_4_4_4 QSPI_CFG_BUS_QUAD, QSPI_CFG_BUS_QUAD, QSPI_CFG_BUS_QUAD, QSPI_CFG_BUS_QUAD #define WRITE_1_1_1 MODE_1_1_1, QSPI_CMD_WRITE_1IO #ifdef QSPI_CMD_WRITE_2IO #define WRITE_1_2_2 MODE_1_2_2, QSPI_CMD_WRITE_2IO #endif #ifdef QSPI_CMD_WRITE_1I4O // Quad page program - command: 0x32 #define WRITE_1_1_4 MODE_1_1_4, QSPI_CMD_WRITE_1I4O #endif #ifdef QSPI_CMD_WRITE_4IO #define WRITE_1_4_4 MODE_1_4_4, QSPI_CMD_WRITE_4IO #endif #ifdef QSPI_CMD_WRITE_DPI #define WRITE_2_2_2 MODE_2_2_2, QSPI_CMD_WRITE_DPI #endif #ifdef QSPI_CMD_WRITE_QPI #define WRITE_4_4_4 MODE_4_4_4, QSPI_CMD_WRITE_QPI #endif #define READ_1_1_1 MODE_1_1_1, QSPI_CMD_READ_1IO, QSPI_READ_1IO_DUMMY_CYCLE #ifdef QSPI_CMD_READ_1I2O #define READ_1_1_2 MODE_1_1_2, QSPI_CMD_READ_1I2O, QSPI_READ_1I2O_DUMMY_CYCLE #endif #ifdef QSPI_CMD_READ_2IO #define READ_1_2_2 MODE_1_2_2, QSPI_CMD_READ_2IO, QSPI_READ_2IO_DUMMY_CYCLE #endif #ifdef QSPI_CMD_READ_1I4O #define READ_1_1_4 MODE_1_1_4, QSPI_CMD_READ_1I4O, QSPI_READ_1I4O_DUMMY_CYCLE #endif #ifdef QSPI_CMD_READ_4IO #define READ_1_4_4 MODE_1_4_4, QSPI_CMD_READ_4IO, QSPI_READ_4IO_DUMMY_CYCLE #endif #ifdef QSPI_CMD_READ_DPI #define READ_2_2_2 MODE_2_2_2, QSPI_CMD_READ_DPI, QSPI_READ_2IO_DUMMY_CYCLE #endif #ifdef QSPI_CMD_READ_QPI #define READ_4_4_4 MODE_4_4_4, QSPI_CMD_READ_QPI, QSPI_READ_4IO_DUMMY_CYCLE #endif #define ADDR_SIZE_8 QSPI_CFG_ADDR_SIZE_8 #define ADDR_SIZE_16 QSPI_CFG_ADDR_SIZE_16 #define ADDR_SIZE_24 QSPI_CFG_ADDR_SIZE_24 #define ADDR_SIZE_32 QSPI_CFG_ADDR_SIZE_32 #define ALT_SIZE_8 QSPI_CFG_ALT_SIZE_8 #define ALT_SIZE_16 QSPI_CFG_ALT_SIZE_16 #define ALT_SIZE_24 QSPI_CFG_ALT_SIZE_24 #define ALT_SIZE_32 QSPI_CFG_ALT_SIZE_32 #define STATUS_REG QSPI_CMD_RDSR #define CONFIG_REG0 QSPI_CMD_RDCR0 #ifdef QSPI_CMD_RDCR1 #define CONFIG_REG1 QSPI_CMD_RDCR1 #endif #ifdef QSPI_CMD_RDCR2 #define CONFIG_REG2 QSPI_CMD_RDCR2 #endif #define SECURITY_REG QSPI_CMD_RDSCUR #ifndef QSPI_CONFIG_REG_1_SIZE #define QSPI_CONFIG_REG_1_SIZE 0 #endif #ifndef QSPI_CONFIG_REG_2_SIZE #define QSPI_CONFIG_REG_2_SIZE 0 #endif #define SECTOR_ERASE QSPI_CMD_ERASE_SECTOR #define BLOCK_ERASE QSPI_CMD_ERASE_BLOCK_64 #define SECTOR_ERASE_MAX_TIME QSPI_ERASE_SECTOR_MAX_TIME #define BLOCK32_ERASE_MAX_TIME QSPI_ERASE_BLOCK_32_MAX_TIME #define BLOCK64_ERASE_MAX_TIME QSPI_ERASE_BLOCK_64_MAX_TIME #define PAGE_PROG_MAX_TIME QSPI_PAGE_PROG_MAX_TIME #define WRSR_MAX_TIME QSPI_WRSR_MAX_TIME #define WAIT_MAX_TIME QSPI_WAIT_MAX_TIME qspi_status_t read_register(uint32_t cmd, uint8_t *buf, uint32_t size, Qspi &q); qspi_status_t write_register(uint32_t cmd, uint8_t *buf, uint32_t size, Qspi &q); QspiStatus flash_wait_for(uint32_t time_us, Qspi &qspi); void flash_init(Qspi &qspi); qspi_status_t write_enable(Qspi &qspi); qspi_status_t write_disable(Qspi &qspi); void log_register(uint32_t cmd, uint32_t reg_size, Qspi &qspi, const char *str = NULL); qspi_status_t mode_enable(Qspi &qspi, qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width); qspi_status_t mode_disable(Qspi &qspi, qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width); qspi_status_t fast_mode_enable(Qspi &qspi); qspi_status_t fast_mode_disable(Qspi &qspi); qspi_status_t erase(uint32_t erase_cmd, uint32_t flash_addr, Qspi &qspi); bool is_extended_mode(qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width); bool is_dual_mode(qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width); bool is_quad_mode(qspi_bus_width_t inst_width, qspi_bus_width_t addr_width, qspi_bus_width_t data_width); #define WAIT_FOR(timeout, q) TEST_ASSERT_EQUAL_MESSAGE(sOK, flash_wait_for(timeout, q), "flash_wait_for failed!!!") #endif // MBED_QSPI_TEST_UTILS_H
a3a8b7c84750691e5aa16df3c3deedb637da7108
092ab7e8f4e198cd3e10f1f66d5d671d2ea25d99
/Sort List.cpp
1f131fb494f26fca356ae91fb7acbd3028c456ab
[]
no_license
ThreeMonkey/LeetCode
5b5f24ed71222c50257b2578d5a0a21821fd2e55
8f3d63737fe91aa71d4f66c3ae9f6b634567c954
refs/heads/master
2016-09-07T18:58:49.625910
2014-08-09T07:48:31
2014-08-09T07:48:31
23,688,384
2
0
null
null
null
null
GB18030
C++
false
false
1,597
cpp
/*  Sort a linked list in O(n log n) time using constant space complexity. 解题思路:   复杂度为O(n* logn) 的排序算法有:快速排序、堆排序、归并排序。对于链表这种数据结构,使用归并排序比较靠谱。 */ #include <iostream> using namespace std; /** * Definition for singly-linked list. */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *sortList(ListNode *head) { if (head == NULL || head->next == NULL) { return head; } /*找到链表中间的元素*/ ListNode* p_middle = head; ListNode* p_last = head->next; while (p_last != NULL && p_last->next != NULL){ p_middle = p_middle->next; p_last = p_last->next->next; } /*划分为左右两部分*/ ListNode* p_left = head; ListNode* p_right = p_middle->next; p_middle->next = NULL; /*对左右两部分分别进行排序*/ p_left = sortList(p_left); p_right = sortList(p_right); /*合并*/ ListNode* p_head = NULL; if (p_left->val < p_right->val){ p_head = p_left; p_left = p_left->next; } else{ p_head = p_right; p_right = p_right->next; } ListNode* p_current = p_head; while (p_left != NULL && p_right != NULL) { if (p_left->val < p_right->val){ p_current->next = p_left; p_left = p_left->next; } else { p_current->next = p_right; p_right = p_right->next; } p_current = p_current->next; } if (p_left != NULL) p_current->next = p_left; if (p_right != NULL) p_current->next = p_right; return p_head; } };
1c8b5fdc9edb3b77e38690079ba580127e6159a6
11ef4bbb8086ba3b9678a2037d0c28baaf8c010e
/Source Code/server/binaries/chromium/gen/components/sync/protocol/managed_user_shared_setting_specifics.pb.h
c0172494fd618d2fa8dbda41ded8003c6eb443ce
[]
no_license
lineCode/wasmview.github.io
8f845ec6ba8a1ec85272d734efc80d2416a6e15b
eac4c69ea1cf0e9af9da5a500219236470541f9b
refs/heads/master
2020-09-22T21:05:53.766548
2019-08-24T05:34:04
2019-08-24T05:34:04
null
0
0
null
null
null
null
UTF-8
C++
false
true
18,906
h
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: managed_user_shared_setting_specifics.proto #ifndef PROTOBUF_INCLUDED_managed_5fuser_5fshared_5fsetting_5fspecifics_2eproto #define PROTOBUF_INCLUDED_managed_5fuser_5fshared_5fsetting_5fspecifics_2eproto #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 3005000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3005001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/inlined_string_field.h> #include <google/protobuf/metadata_lite.h> #include <google/protobuf/message_lite.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export // @@protoc_insertion_point(includes) #define PROTOBUF_INTERNAL_EXPORT_protobuf_managed_5fuser_5fshared_5fsetting_5fspecifics_2eproto namespace protobuf_managed_5fuser_5fshared_5fsetting_5fspecifics_2eproto { // Internal implementation detail -- do not use these members. struct TableStruct { static const ::google::protobuf::internal::ParseTableField entries[]; static const ::google::protobuf::internal::AuxillaryParseTableField aux[]; static const ::google::protobuf::internal::ParseTable schema[1]; static const ::google::protobuf::internal::FieldMetadata field_metadata[]; static const ::google::protobuf::internal::SerializationTable serialization_table[]; static const ::google::protobuf::uint32 offsets[]; }; } // namespace protobuf_managed_5fuser_5fshared_5fsetting_5fspecifics_2eproto namespace sync_pb { class ManagedUserSharedSettingSpecifics; class ManagedUserSharedSettingSpecificsDefaultTypeInternal; extern ManagedUserSharedSettingSpecificsDefaultTypeInternal _ManagedUserSharedSettingSpecifics_default_instance_; } // namespace sync_pb namespace google { namespace protobuf { template<> ::sync_pb::ManagedUserSharedSettingSpecifics* Arena::CreateMaybeMessage<::sync_pb::ManagedUserSharedSettingSpecifics>(Arena*); } // namespace protobuf } // namespace google namespace sync_pb { // =================================================================== class ManagedUserSharedSettingSpecifics : public ::google::protobuf::MessageLite /* @@protoc_insertion_point(class_definition:sync_pb.ManagedUserSharedSettingSpecifics) */ { public: ManagedUserSharedSettingSpecifics(); virtual ~ManagedUserSharedSettingSpecifics(); ManagedUserSharedSettingSpecifics(const ManagedUserSharedSettingSpecifics& from); inline ManagedUserSharedSettingSpecifics& operator=(const ManagedUserSharedSettingSpecifics& from) { CopyFrom(from); return *this; } #if LANG_CXX11 ManagedUserSharedSettingSpecifics(ManagedUserSharedSettingSpecifics&& from) noexcept : ManagedUserSharedSettingSpecifics() { *this = ::std::move(from); } inline ManagedUserSharedSettingSpecifics& operator=(ManagedUserSharedSettingSpecifics&& from) noexcept { if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } #endif inline const ::std::string& unknown_fields() const { return _internal_metadata_.unknown_fields(); } inline ::std::string* mutable_unknown_fields() { return _internal_metadata_.mutable_unknown_fields(); } static const ManagedUserSharedSettingSpecifics& default_instance(); static void InitAsDefaultInstance(); // FOR INTERNAL USE ONLY static inline const ManagedUserSharedSettingSpecifics* internal_default_instance() { return reinterpret_cast<const ManagedUserSharedSettingSpecifics*>( &_ManagedUserSharedSettingSpecifics_default_instance_); } static constexpr int kIndexInFileMessages = 0; GOOGLE_ATTRIBUTE_NOINLINE void Swap(ManagedUserSharedSettingSpecifics* other); friend void swap(ManagedUserSharedSettingSpecifics& a, ManagedUserSharedSettingSpecifics& b) { a.Swap(&b); } // implements Message ---------------------------------------------- inline ManagedUserSharedSettingSpecifics* New() const final { return CreateMaybeMessage<ManagedUserSharedSettingSpecifics>(NULL); } ManagedUserSharedSettingSpecifics* New(::google::protobuf::Arena* arena) const final { return CreateMaybeMessage<ManagedUserSharedSettingSpecifics>(arena); } void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from) final; void CopyFrom(const ManagedUserSharedSettingSpecifics& from); void MergeFrom(const ManagedUserSharedSettingSpecifics& from); void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) final; void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const final; void DiscardUnknownFields(); int GetCachedSize() const final { return _cached_size_.Get(); } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; void InternalSwap(ManagedUserSharedSettingSpecifics* other); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return NULL; } inline void* MaybeArenaPtr() const { return NULL; } public: ::std::string GetTypeName() const final; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional string mu_id = 1; bool has_mu_id() const; void clear_mu_id(); static const int kMuIdFieldNumber = 1; const ::std::string& mu_id() const; void set_mu_id(const ::std::string& value); #if LANG_CXX11 void set_mu_id(::std::string&& value); #endif void set_mu_id(const char* value); void set_mu_id(const char* value, size_t size); ::std::string* mutable_mu_id(); ::std::string* release_mu_id(); void set_allocated_mu_id(::std::string* mu_id); // optional string key = 2; bool has_key() const; void clear_key(); static const int kKeyFieldNumber = 2; const ::std::string& key() const; void set_key(const ::std::string& value); #if LANG_CXX11 void set_key(::std::string&& value); #endif void set_key(const char* value); void set_key(const char* value, size_t size); ::std::string* mutable_key(); ::std::string* release_key(); void set_allocated_key(::std::string* key); // optional string value = 3; bool has_value() const; void clear_value(); static const int kValueFieldNumber = 3; const ::std::string& value() const; void set_value(const ::std::string& value); #if LANG_CXX11 void set_value(::std::string&& value); #endif void set_value(const char* value); void set_value(const char* value, size_t size); ::std::string* mutable_value(); ::std::string* release_value(); void set_allocated_value(::std::string* value); // optional bool acknowledged = 4 [default = false]; bool has_acknowledged() const; void clear_acknowledged(); static const int kAcknowledgedFieldNumber = 4; bool acknowledged() const; void set_acknowledged(bool value); // @@protoc_insertion_point(class_scope:sync_pb.ManagedUserSharedSettingSpecifics) private: void set_has_mu_id(); void clear_has_mu_id(); void set_has_key(); void clear_has_key(); void set_has_value(); void clear_has_value(); void set_has_acknowledged(); void clear_has_acknowledged(); ::google::protobuf::internal::InternalMetadataWithArenaLite _internal_metadata_; ::google::protobuf::internal::HasBits<1> _has_bits_; mutable ::google::protobuf::internal::CachedSize _cached_size_; ::google::protobuf::internal::ArenaStringPtr mu_id_; ::google::protobuf::internal::ArenaStringPtr key_; ::google::protobuf::internal::ArenaStringPtr value_; bool acknowledged_; friend struct ::protobuf_managed_5fuser_5fshared_5fsetting_5fspecifics_2eproto::TableStruct; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // ManagedUserSharedSettingSpecifics // optional string mu_id = 1; inline bool ManagedUserSharedSettingSpecifics::has_mu_id() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void ManagedUserSharedSettingSpecifics::set_has_mu_id() { _has_bits_[0] |= 0x00000001u; } inline void ManagedUserSharedSettingSpecifics::clear_has_mu_id() { _has_bits_[0] &= ~0x00000001u; } inline void ManagedUserSharedSettingSpecifics::clear_mu_id() { mu_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); clear_has_mu_id(); } inline const ::std::string& ManagedUserSharedSettingSpecifics::mu_id() const { // @@protoc_insertion_point(field_get:sync_pb.ManagedUserSharedSettingSpecifics.mu_id) return mu_id_.GetNoArena(); } inline void ManagedUserSharedSettingSpecifics::set_mu_id(const ::std::string& value) { set_has_mu_id(); mu_id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:sync_pb.ManagedUserSharedSettingSpecifics.mu_id) } #if LANG_CXX11 inline void ManagedUserSharedSettingSpecifics::set_mu_id(::std::string&& value) { set_has_mu_id(); mu_id_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:sync_pb.ManagedUserSharedSettingSpecifics.mu_id) } #endif inline void ManagedUserSharedSettingSpecifics::set_mu_id(const char* value) { GOOGLE_DCHECK(value != NULL); set_has_mu_id(); mu_id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:sync_pb.ManagedUserSharedSettingSpecifics.mu_id) } inline void ManagedUserSharedSettingSpecifics::set_mu_id(const char* value, size_t size) { set_has_mu_id(); mu_id_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:sync_pb.ManagedUserSharedSettingSpecifics.mu_id) } inline ::std::string* ManagedUserSharedSettingSpecifics::mutable_mu_id() { set_has_mu_id(); // @@protoc_insertion_point(field_mutable:sync_pb.ManagedUserSharedSettingSpecifics.mu_id) return mu_id_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* ManagedUserSharedSettingSpecifics::release_mu_id() { // @@protoc_insertion_point(field_release:sync_pb.ManagedUserSharedSettingSpecifics.mu_id) if (!has_mu_id()) { return NULL; } clear_has_mu_id(); return mu_id_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void ManagedUserSharedSettingSpecifics::set_allocated_mu_id(::std::string* mu_id) { if (mu_id != NULL) { set_has_mu_id(); } else { clear_has_mu_id(); } mu_id_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), mu_id); // @@protoc_insertion_point(field_set_allocated:sync_pb.ManagedUserSharedSettingSpecifics.mu_id) } // optional string key = 2; inline bool ManagedUserSharedSettingSpecifics::has_key() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void ManagedUserSharedSettingSpecifics::set_has_key() { _has_bits_[0] |= 0x00000002u; } inline void ManagedUserSharedSettingSpecifics::clear_has_key() { _has_bits_[0] &= ~0x00000002u; } inline void ManagedUserSharedSettingSpecifics::clear_key() { key_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); clear_has_key(); } inline const ::std::string& ManagedUserSharedSettingSpecifics::key() const { // @@protoc_insertion_point(field_get:sync_pb.ManagedUserSharedSettingSpecifics.key) return key_.GetNoArena(); } inline void ManagedUserSharedSettingSpecifics::set_key(const ::std::string& value) { set_has_key(); key_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:sync_pb.ManagedUserSharedSettingSpecifics.key) } #if LANG_CXX11 inline void ManagedUserSharedSettingSpecifics::set_key(::std::string&& value) { set_has_key(); key_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:sync_pb.ManagedUserSharedSettingSpecifics.key) } #endif inline void ManagedUserSharedSettingSpecifics::set_key(const char* value) { GOOGLE_DCHECK(value != NULL); set_has_key(); key_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:sync_pb.ManagedUserSharedSettingSpecifics.key) } inline void ManagedUserSharedSettingSpecifics::set_key(const char* value, size_t size) { set_has_key(); key_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:sync_pb.ManagedUserSharedSettingSpecifics.key) } inline ::std::string* ManagedUserSharedSettingSpecifics::mutable_key() { set_has_key(); // @@protoc_insertion_point(field_mutable:sync_pb.ManagedUserSharedSettingSpecifics.key) return key_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* ManagedUserSharedSettingSpecifics::release_key() { // @@protoc_insertion_point(field_release:sync_pb.ManagedUserSharedSettingSpecifics.key) if (!has_key()) { return NULL; } clear_has_key(); return key_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void ManagedUserSharedSettingSpecifics::set_allocated_key(::std::string* key) { if (key != NULL) { set_has_key(); } else { clear_has_key(); } key_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), key); // @@protoc_insertion_point(field_set_allocated:sync_pb.ManagedUserSharedSettingSpecifics.key) } // optional string value = 3; inline bool ManagedUserSharedSettingSpecifics::has_value() const { return (_has_bits_[0] & 0x00000004u) != 0; } inline void ManagedUserSharedSettingSpecifics::set_has_value() { _has_bits_[0] |= 0x00000004u; } inline void ManagedUserSharedSettingSpecifics::clear_has_value() { _has_bits_[0] &= ~0x00000004u; } inline void ManagedUserSharedSettingSpecifics::clear_value() { value_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); clear_has_value(); } inline const ::std::string& ManagedUserSharedSettingSpecifics::value() const { // @@protoc_insertion_point(field_get:sync_pb.ManagedUserSharedSettingSpecifics.value) return value_.GetNoArena(); } inline void ManagedUserSharedSettingSpecifics::set_value(const ::std::string& value) { set_has_value(); value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:sync_pb.ManagedUserSharedSettingSpecifics.value) } #if LANG_CXX11 inline void ManagedUserSharedSettingSpecifics::set_value(::std::string&& value) { set_has_value(); value_.SetNoArena( &::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value)); // @@protoc_insertion_point(field_set_rvalue:sync_pb.ManagedUserSharedSettingSpecifics.value) } #endif inline void ManagedUserSharedSettingSpecifics::set_value(const char* value) { GOOGLE_DCHECK(value != NULL); set_has_value(); value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:sync_pb.ManagedUserSharedSettingSpecifics.value) } inline void ManagedUserSharedSettingSpecifics::set_value(const char* value, size_t size) { set_has_value(); value_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:sync_pb.ManagedUserSharedSettingSpecifics.value) } inline ::std::string* ManagedUserSharedSettingSpecifics::mutable_value() { set_has_value(); // @@protoc_insertion_point(field_mutable:sync_pb.ManagedUserSharedSettingSpecifics.value) return value_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline ::std::string* ManagedUserSharedSettingSpecifics::release_value() { // @@protoc_insertion_point(field_release:sync_pb.ManagedUserSharedSettingSpecifics.value) if (!has_value()) { return NULL; } clear_has_value(); return value_.ReleaseNonDefaultNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } inline void ManagedUserSharedSettingSpecifics::set_allocated_value(::std::string* value) { if (value != NULL) { set_has_value(); } else { clear_has_value(); } value_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set_allocated:sync_pb.ManagedUserSharedSettingSpecifics.value) } // optional bool acknowledged = 4 [default = false]; inline bool ManagedUserSharedSettingSpecifics::has_acknowledged() const { return (_has_bits_[0] & 0x00000008u) != 0; } inline void ManagedUserSharedSettingSpecifics::set_has_acknowledged() { _has_bits_[0] |= 0x00000008u; } inline void ManagedUserSharedSettingSpecifics::clear_has_acknowledged() { _has_bits_[0] &= ~0x00000008u; } inline void ManagedUserSharedSettingSpecifics::clear_acknowledged() { acknowledged_ = false; clear_has_acknowledged(); } inline bool ManagedUserSharedSettingSpecifics::acknowledged() const { // @@protoc_insertion_point(field_get:sync_pb.ManagedUserSharedSettingSpecifics.acknowledged) return acknowledged_; } inline void ManagedUserSharedSettingSpecifics::set_acknowledged(bool value) { set_has_acknowledged(); acknowledged_ = value; // @@protoc_insertion_point(field_set:sync_pb.ManagedUserSharedSettingSpecifics.acknowledged) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // @@protoc_insertion_point(namespace_scope) } // namespace sync_pb // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_INCLUDED_managed_5fuser_5fshared_5fsetting_5fspecifics_2eproto
980a71749df054cdb4536116e57de2c5b5c0c884
9963483dc14eee86b2a057df24b6876172644e4b
/OscTests/JuceLibraryCode/JuceHeader.h
547badb8e61ae2d73762507a04b8e2163b012743
[]
no_license
kasparia/audio-foolery
b7d5bed86861f5b17131ecd4595f24683dadf79f
912963b8e32f817ff0e79800e0f2fc0344673cb9
refs/heads/main
2023-03-27T05:23:42.499721
2021-03-30T21:10:07
2021-03-30T21:10:07
340,762,813
0
0
null
null
null
null
UTF-8
C++
false
false
1,979
h
/* IMPORTANT! This file is auto-generated each time you save your project - if you alter its contents, your changes may be overwritten! This is the header file that your files should include in order to get all the JUCE library headers. You should avoid including the JUCE headers directly in your own source files, because that wouldn't pick up the correct configuration options for your app. */ #pragma once #include <juce_audio_basics/juce_audio_basics.h> #include <juce_audio_devices/juce_audio_devices.h> #include <juce_audio_formats/juce_audio_formats.h> #include <juce_audio_plugin_client/juce_audio_plugin_client.h> #include <juce_audio_processors/juce_audio_processors.h> #include <juce_audio_utils/juce_audio_utils.h> #include <juce_core/juce_core.h> #include <juce_data_structures/juce_data_structures.h> #include <juce_dsp/juce_dsp.h> #include <juce_events/juce_events.h> #include <juce_graphics/juce_graphics.h> #include <juce_gui_basics/juce_gui_basics.h> #include <juce_gui_extra/juce_gui_extra.h> #if defined (JUCE_PROJUCER_VERSION) && JUCE_PROJUCER_VERSION < JUCE_VERSION /** If you've hit this error then the version of the Projucer that was used to generate this project is older than the version of the JUCE modules being included. To fix this error, re-save your project using the latest version of the Projucer or, if you aren't using the Projucer to manage your project, remove the JUCE_PROJUCER_VERSION define from the AppConfig.h file. */ #error "This project was last saved using an outdated version of the Projucer! Re-save this project with the latest version to fix this error." #endif #if ! JUCE_DONT_DECLARE_PROJECTINFO namespace ProjectInfo { const char* const projectName = "OscTests"; const char* const companyName = ""; const char* const versionString = "1.0.0"; const int versionNumber = 0x10000; } #endif
13fd7f86eb48bdbf2f6fe2ec7fcf2d4cb46ac404
30dee1c42022fb8bd5383fe431b8a55a6015ffe5
/tests/include/aquila/dde/MockInstance.h
b693c1517d2c1f1f08bf2159c0235e754c9e47f0
[]
no_license
robot-aquila/wquik
b0ad7fe51e2f8cb84d5a7de7eda66da18e700af9
e8ce4c4359dc2bbd9963f2d082b97b821be248b7
refs/heads/master
2020-05-17T02:01:38.424268
2015-12-13T06:27:51
2015-12-13T06:27:51
21,413,837
1
0
null
null
null
null
UTF-8
C++
false
false
968
h
/** * ============================================================================ * 2011/07/18 * $Id: MockInstance.h 96 2011-08-11 17:36:58Z whirlwind $ * Juno * ============================================================================ */ #pragma once #include <gtest/gtest.h> #include <gmock/gmock.h> #include "aquila/dde/IInstance.h" #include <string> namespace aquila { namespace dde { class MockInstance : public IInstance { public: virtual ~MockInstance() { } MOCK_METHOD1(createString, IString*(std::string str)); MOCK_METHOD1(wrapString, IString*(HSZ hsz)); MOCK_METHOD1(wrapData, IData*(HDDEDATA hData)); MOCK_METHOD1(wrapConversation, IConversation*(HCONV hConv)); MOCK_METHOD0(getLastError, int()); MOCK_METHOD2(nameService, void(IString* name, UINT afCmd)); MOCK_METHOD0(getId, DWORD()); MOCK_METHOD0(getCodePage, int()); }; } // end namespace dde } // end namespace aquila
54ae203ded9e62a6fef727bb9cbf8aa5f52ccca0
3f7d619cafd38afb9a76fbb8c2c5914ab7257ca6
/NewGine/ModuleWindow.h
080d23c3d3a3810ac3650b336142514233bb3a03
[ "MIT" ]
permissive
miquelgiru/NewGine
1afa9585f408a80f6093c4b511ca5943bbc04601
11e1d2e835182c5fd008f51ce2c044a028898f96
refs/heads/master
2020-03-27T16:32:47.477166
2018-11-18T16:48:53
2018-11-18T16:48:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
881
h
#ifndef __ModuleWindow_H__ #define __ModuleWindow_H__ #include "Module.h" #include "SDL/include/SDL.h" class Application; enum WINDOW_MODE { RESIZABLE, FULL_DESKTOP, FULLSCREEN }; class ModuleWindow : public Module { public: ModuleWindow(Application* app, bool start_enabled = true); // Destructor virtual ~ModuleWindow(); bool Init(); bool CleanUp(); void SetTitle(const char* title); int GetWindowMode(); void SetWindowMode(int type); int GetWidth(); void SetWidth(int width); int GetHeight(); void SetHeight(int height); bool LoadConfig(JSON_Object* data); bool SaveConfig(JSON_Object* data)const; public: //The window we'll be rendering to SDL_Window* window; //The surface contained by the window SDL_Surface* screen_surface; private: int width; int height; WINDOW_MODE win_mode; const char* title = TITLE; }; #endif // __ModuleWindow_H__
27f11375d56fa0a2be70472c5caf983fa225a9de
571996358761ee432816fbeedbe932480a9e12ad
/src/board/Board.cpp
99d7ca5f8aaf00da8b3e1bb81dab8f3f8228a31e
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
char-lotl/knights-tour
14d2f6f2c2123ecd4031dfa20571d6cb6cfe79b5
db9ae785768b3143279dfad64e4408105c309a80
refs/heads/master
2023-05-04T10:29:10.439290
2021-05-14T02:42:00
2021-05-14T02:42:00
367,228,438
0
0
null
null
null
null
UTF-8
C++
false
false
3,858
cpp
#include "Board.h" #include "Tile.h" #include <iostream> void add_neighbor_if_in_bounds(int r, int c, int h, int w, STPV2& con, SmartTilePointer& t); bool is_in_bounds(int r, int c, int h, int w); int count_digits(int num); Board::Board(int h, int w) : height{h}, width{w}, area{h * w}, used_tiles{0}, contents{static_cast<unsigned long>(h), STPV{}} { for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { contents[i].push_back(std::make_shared<Tile>()); } } establish_adjacencies(); initialize_statistics(); } const std::vector<std::vector<int> > KNIGHTS_MOVES = { {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1} }; void Board::establish_adjacencies() { for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { for (int k = 0; k < 8; ++k) { add_neighbor_if_in_bounds(i - KNIGHTS_MOVES[k][0], j + KNIGHTS_MOVES[k][1], height, width, contents, contents[i][j]); } } } } STPV& Board::operator[](int row) { return contents[row]; } void Board::add_tile_to_route(SmartTilePointer& stp, STPV& r) { ++used_tiles; r.push_back(stp); stp->path_index = r.size(); stp->used = true; --adjacency_stats[stp->num_unused_neighbors]; for (SmartTilePointer s : stp->neighbors) { if (!(s->used)) { --adjacency_stats[s->num_unused_neighbors]; --(s->num_unused_neighbors); ++adjacency_stats[s->num_unused_neighbors]; } } } void Board::remove_tile_from_route(STPV& r) { SmartTilePointer& stp = r.back(); stp->reset_direction(); for (SmartTilePointer s : stp->neighbors) { if (!(s->used)) { --adjacency_stats[s->num_unused_neighbors]; ++(s->num_unused_neighbors); ++adjacency_stats[s->num_unused_neighbors]; } } ++adjacency_stats[stp->num_unused_neighbors]; stp->used = false; stp->path_index = 0; r.pop_back(); --used_tiles; } int Board::get_used_tiles() { return used_tiles; } void add_neighbor_if_in_bounds(int r, int c, int h, int w, STPV2& contents, SmartTilePointer& t) { bool in_bounds = is_in_bounds(r, c, h, w); if (in_bounds) t->add_neighbor(contents[r][c]); } bool is_in_bounds(int r, int c, int h, int w) { return (r >= 0) && (r < h) && (c >= 0) && (c < w); } void Board::initialize_statistics() { std::vector<int> temp_stats(9, 0); for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { ++temp_stats[contents[i][j]->num_unused_neighbors]; } } adjacency_stats = temp_stats; } int Board::geth() { return height; } int Board::getw() { return width; } int Board::get_area() { return area; } bool Board::unsolvable(SmartTilePointer& t) { bool singleton_dead_end = (adjacency_stats[0] > 0) && (used_tiles + 1 < area); // detects an isolated node that isn't the final node // a node with only one unused neighbor that is not // adjacent to the active node must be a terminal node, // and there can only be one terminal node. // if there are two, the current path is not part of a solution. // however, checking for adjacency requires an inner loop we'd rather skip. if (singleton_dead_end || (adjacency_stats[1] > 2)) return true; // early return to avoid the has_singleton_neighbor loop where possible bool doubleton_dead_end = (adjacency_stats[1] > 1) && !(t->has_singleton_neighbor()); // after checking for the simpler dead-ends, we use the slightly longer // (but still O(1)) check return doubleton_dead_end; } void Board::print_path() { int max_digits = count_digits(area); int col_width = max_digits + 1; for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { int p_i = contents[i][j]->path_index; int left_spacing = col_width - count_digits(p_i); std::cout << std::string(left_spacing, ' ') << p_i; } std::cout << '\n'; } } int count_digits(int num) { int num_digits = 0; while (num > 0) { ++num_digits; num /= 10; } return num_digits; }
f7924755fdb2e245dd252d8d16018b4b9a7a6d1d
b4eb01e9533f0461272034ade8b199b3324e4475
/staticLibs/GameLib/CommandList.h
199bd096285de85a42a828d95caa995f86b6dbd4
[ "MIT" ]
permissive
Mynsu/Sirtet_SFML
2a8db9d1b9528b28ed41c16ffa1e4993569c020a
ad1b64597868959d96d27fcb73fd272f41b21e16
refs/heads/develop
2022-02-25T06:17:42.935175
2022-02-17T16:50:00
2022-02-17T16:50:00
180,202,622
1
1
null
2022-02-17T16:57:14
2019-04-08T17:47:47
C++
UTF-8
C++
false
false
966
h
//// // Commonly used in exes/Engine, dlls/Game. //// #pragma once #include "../Lib/Hash.h" // e.g. "chto 1" // Changes the current scene to another scene immediately. // Intro 0, Main Menu 1, Singleplay 2, Online Battle 3. // Countdown Skipped 21, Game Over 22, All Levels Cleared 23 constexpr HashedKey CMD_CHANGE_SCENE = ::util::hash::Digest( "chto" ); constexpr HashedKey CMD_SET_VOLUME = ::util::hash::Digest( "vol" ); // e.g. "refresh" // Refreshes the current scene, or reloads its script and resources. constexpr HashedKey CMD_RELOAD = ::util::hash::Digest( "refresh" ); constexpr HashedKey CMD_RELOAD_CONSOLE = ::util::hash::Digest( "refreshcon" ); constexpr HashedKey CMD_CREATE_ROOM = ::util::hash::Digest( "croom" ); constexpr HashedKey CMD_START_GAME = ::util::hash::Digest( "start" ); constexpr HashedKey CMD_LEAVE_ROOM = ::util::hash::Digest( "leave" ); // e.g. "join nickname1" constexpr HashedKey CMD_JOIN_ROOM = ::util::hash::Digest( "join" );
be012113e2ff902d5ea17a38de77b1bcb62e7871
5d201972ebf01a252a46188d1cbd148d9395c6f3
/libtiny816/board_horn.cpp
b8b49197420787a3eae0b86ceabc5093810926a9
[]
no_license
TeddyHut/SEM2019
498a3a17e7b1bc1aa39508617bd333f172fd9623
1aeca4773292056a021ebc5aab9a1580cae42f30
refs/heads/master
2020-04-09T02:17:23.175714
2020-01-07T10:12:05
2020-01-07T10:12:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,486
cpp
/* * board_horn.cpp * * Created: 16/01/2019 1:12:28 AM * Author: teddy */ #include "board_horn.h" PORT_t &libtiny816::hw::PINPORT::LED_RED = PORTA; PORT_t &libtiny816::hw::PINPORT::LED_GREEN = PORTA; PORT_t &libtiny816::hw::PINPORT::BUTTON_TEST = PORTA; PORT_t &libtiny816::hw::PINPORT::BUTTON_HORN = PORTB; PORT_t &libtiny816::hw::PINPORT::BUTTON_WHEEL = PORTB; PORT_t &libtiny816::hw::PINPORT::SW_MODE = PORTA; PORT_t &libtiny816::hw::PINPORT::OUT_HORN = PORTB; void libmodule::hw::panic() { PORTA.DIRSET = libtiny816::hw::PINMASK::LED_RED | libtiny816::hw::PINMASK::LED_GREEN; PORTA.OUTSET = libtiny816::hw::PINMASK::LED_RED | libtiny816::hw::PINMASK::LED_GREEN; asm("BREAK"); while(true); } bool libtiny816::Button::get() const { return pm_hwport.IN & 1 << pm_hwpin; } libtiny816::Button::Button(PORT_t &port, uint8_t pin, bool const onlevel /*= false*/, bool const pullup /*= true*/) : pm_hwport(port), pm_hwpin(pin) { pm_hwport.DIRCLR = 1 << pm_hwpin; uint8_t pinctrlmask = 0; //Invert input if the button is active low if(!onlevel) pinctrlmask = PORT_INVEN_bm; //Enable pullup if necessary if(pullup) pinctrlmask |= PORT_PULLUPEN_bm; *(&pm_hwport.PIN0CTRL + pm_hwpin) = pinctrlmask; } void libtiny816::LED::set(bool const state) { if(state) pm_hwport.OUTSET = 1 << pm_hwpin; else pm_hwport.OUTCLR = 1 << pm_hwpin; } libtiny816::LED::LED(PORT_t &port, uint8_t const pin) : pm_hwport(port), pm_hwpin(pin) { pm_hwport.DIRSET = 1 << pm_hwpin; }
1a7a8c97f50c35bd9f033e405a34b866a107ce39
b9f3333160e8e75ce67af3e205879c832c3e1f30
/PhoneBook/Person.cpp
06c9698c293c9bf71cd1a21c972366259cc4a878
[]
no_license
dinci11/PhoneBook
12c8992a8f0d71bd04e08c1b2bd271c61f44d263
6323e08399cb923cd6791bf7fc5a226b7b8799bc
refs/heads/master
2020-05-20T08:03:15.365634
2019-05-11T11:24:22
2019-05-11T11:24:22
185,465,324
0
0
null
null
null
null
UTF-8
C++
false
false
3,653
cpp
#include "pch.h" #include "Person.h" #define PRINT_METHOD false /* Default Constructor for Person */ Person::Person() { #if PRINT_METHOD true std::cout << "Person DefCTOR\n"; #endif // PRINT_METHOD true firstName = new char(); lastName = new char(); nickName = new char(); address = new char(); workPhone = new char(); privatePhone = new char(); } /* Constructor with paramters for set fields */ Person::Person(const char* pFirstName, const char* pLastName, const char* pNickName, const char* pAddress, const char* pWorkPhone, const char* pPrivatePhone) { #if PRINT_METHOD true std::cout << "Person ParamCTOR\n"; #endif // PRINT_METHOD true firstName = new char[strlen(pFirstName) + 1]; lastName = new char[strlen(pLastName) + 1]; nickName = new char[strlen(pNickName) + 1]; address = new char[strlen(pAddress) + 1]; workPhone = new char[strlen(pWorkPhone) + 1]; privatePhone = new char[strlen(pPrivatePhone) + 1]; strcpy_s(firstName, strlen(pFirstName) + 1, pFirstName); strcpy_s(lastName, strlen(pLastName) + 1, pLastName); strcpy_s(nickName, strlen(pNickName) + 1, pNickName); strcpy_s(address, strlen(pAddress) + 1, pAddress); strcpy_s(workPhone, strlen(pWorkPhone) + 1, pWorkPhone); strcpy_s(privatePhone, strlen(pPrivatePhone) + 1, pPrivatePhone); } /* Copy constructor */ Person::Person(const Person & p) { #if PRINT_METHOD ture std::cout << "Person CCTOR\n"; #endif // PRINT_METHOD ture firstName = new char[strlen(p.firstName) + 1]; lastName = new char[strlen(p.lastName) + 1]; nickName = new char[strlen(p.nickName) + 1]; address = new char[strlen(p.address) + 1]; workPhone = new char[strlen(p.workPhone) + 1]; privatePhone = new char[strlen(p.privatePhone) + 1]; strcpy_s(firstName, strlen(p.firstName) + 1, p.firstName); strcpy_s(lastName, strlen(p.lastName) + 1, p.lastName); strcpy_s(nickName, strlen(p.nickName) + 1, p.nickName); strcpy_s(address, strlen(p.address) + 1, p.address); strcpy_s(workPhone, strlen(p.workPhone) + 1, p.workPhone); strcpy_s(privatePhone, strlen(p.privatePhone) + 1, p.privatePhone); } /* Destructor Delete all the allocated memory for fields */ Person::~Person() { #if PRINT_METHOD true std::cout << "Person DCTOR\n"; #endif // PRINT_METHOD true delete[] firstName; delete[] lastName; delete[] nickName; delete[] address; delete[] workPhone; delete[] privatePhone; } /* Override operator= */ Person& Person::operator=(const Person p) { #if PRINT_METHOD true std::cout << "Person operator= \n"; #endif // PRINT_METHOD true if (this != &p) { firstName = new char[strlen(p.firstName) + 1]; lastName = new char[strlen(p.lastName) + 1]; nickName = new char[strlen(p.nickName) + 1]; address = new char[strlen(p.address) + 1]; workPhone = new char[strlen(p.workPhone) + 1]; privatePhone = new char[strlen(p.privatePhone) + 1]; strcpy_s(firstName, strlen(p.firstName) + 1, p.firstName); strcpy_s(lastName, strlen(p.lastName) + 1, p.lastName); strcpy_s(nickName, strlen(p.nickName) + 1, p.nickName); strcpy_s(address, strlen(p.address) + 1, p.address); strcpy_s(workPhone, strlen(p.workPhone) + 1, p.workPhone); strcpy_s(privatePhone, strlen(p.privatePhone) + 1, p.privatePhone); } return *this; } /* Override operator== Two Person are equal if their firstname are equals and theri lastname are quals and their nickname are equals */ bool Person::operator==(const Person & p) { #if PRINT_METHOD true std::cout << "Person operator== \n"; #endif // PRINT_METHOD true if (strcmp(firstName, p.firstName) == 0 && strcmp(lastName, p.lastName) == 0 && strcmp(nickName, p.nickName) == 0) { return true; } else { return false; } }
9cdb7b57a41453731559df4d6dc9d4d2ac05af92
bc01d89e3b77b9b60afd6f5f8fcad5675b813f8e
/multimediacommscontroller/tsrc/TestConsoles/McpConsole/Src/Testconsole.cpp
d7762185cced43bca2a075725a025b4d4a28c2c5
[]
no_license
SymbianSource/oss.FCL.sf.mw.ipappsrv
fce862742655303fcfa05b9e77788734aa66724e
65c20a5a6e85f048aa40eb91066941f2f508a4d2
refs/heads/master
2021-01-12T15:40:59.380107
2010-09-17T05:32:38
2010-09-17T05:32:38
71,849,396
1
0
null
null
null
null
UTF-8
C++
false
false
65,583
cpp
/* * Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Part of TestConsole application. ** Methods for the class CTestAppConsole ** */ #include <e32std.h> #include <e32svr.h> #include <e32base.h> #include <AudioPreference.h> #include "TestConsole.h" #include "MccInternalCodecs.h" #include "MmccEvents.h" #include "MccDef.h" #include "MmccCodecAMR.h" _LIT( KTxtMainInstructions, "Please select one option:\n" L"1. Session & Q. Stream creation\n" L"2. Prepare & W. Start Stream\n" L"3. Pause Stream\n" L"4. Resume Stream\n" L"5. Stop & d. Delete Stream\n" L"6. Close Session\n" L"7. Set volume & gain\n" L"8. Get gain & maxgain & codec & volume\n" L"\n" L"c. Codec menu\n" L"m. DTMF menu\n" L"n. Network settings\n" L"r. Send non-RTCP data\n" L"t. Toggle inactivity timer on/off\n" L"9. Quit\n" ); _LIT( KTxtCodecInstructions, "Select option:\n" L"1. Supported Codecs\n" L"2. Change codec\n" L"3. Set Codec Settings\n" L"4. Toggle VAD/FW\n" L"5. Set Codec\n" L"6. Set FTMP attribute\n" L"9. Return main menu\n" ); _LIT( KTxtDTMFInstructions, "Select option:\n " L"1. Start DTMF Tone\n" L"2. Stop DTMF Tone\n" L"3. Send DTMF Tones\n" L"4. Continue sending\n" L"9. Return main menu\n" ); //******************************************************************************* // Method : CTestAppConsole::NewL() // Purpose : // Parameters : // Return Value: //******************************************************************************* CTestAppConsole* CTestAppConsole::NewL() { CTestAppConsole* self = new( ELeave ) CTestAppConsole(); CleanupStack::PushL( self ); self->ConstructL(); CleanupStack::Pop(); return self; } //******************************************************************************* // Method : CTestAppConsole::CTestAppConsole() // Purpose : Constructor // Parameters : // Return Value: //******************************************************************************* CTestAppConsole::CTestAppConsole() : CActive( EPriorityStandard ), iDTMFSessionID( KNullId ), iDTMFStreamID( 0 ), iInactivityTimerActive( EFalse ), iIapId( -1 ), iNetSettingsDone( EFalse ), iCurMenu( EMainMenu ), iDtmfMode( EFalse ), iSdesReported( EFalse ), iSrReported( EFalse ), iRrReported( EFalse ), iNumOfNonRtcpDataSent( 0 ) { CActiveScheduler::Add( this ); } //******************************************************************************* // Method : CTestAppConsole::ConstructL() // Purpose : // Parameters : // Return Value: //******************************************************************************* void CTestAppConsole::ConstructL() { _LIT( KTxtTitle, " Mcc Test " ); iConsole = Console::NewL( KTxtTitle, TSize( KConsFullScreen, KConsFullScreen ) ); DisplayConsoleMenu( KTxtMainInstructions ); //__KHEAP_MARK; iMccInterface = CMccInterface::NewL( *this ); iCodecArray.Reset(); iMccInterface->GetCapabilities( iCodecArray/*iCodecInformation*/ ); // RPointerArray<TFourCC>& aCodecs RunTestCodecFactory(); } //******************************************************************************* // Method : CTestAppConsole::~CTestAppConsole() // Purpose : Destructor // Parameters : // Return Value: //******************************************************************************* CTestAppConsole::~CTestAppConsole() { Cancel(); // any outstanding request if ( iConsole ) { delete iConsole; } delete iInstruct; iCodecInformation.ResetAndDestroy(); iCodecInformation.Close(); iCodecArray.ResetAndDestroy(); iCodecArray.Close(); iMccInterface->Close(); delete iMccInterface; //__KHEAP_MARKEND; } //******************************************************************************* // Method : CTestAppConsole::StartTesting() // Purpose : start this AO // Parameters : // Return Value: //******************************************************************************* void CTestAppConsole::StartTesting() { DoRead(); } //******************************************************************************* // Method : CTestAppConsole::DoRead() // Purpose : get the user's option and send request to scheduler // Parameters : // Return Value: //******************************************************************************* void CTestAppConsole::DoRead() { //PrintOptions(); iConsole->Read( iStatus ); SetActive(); } //******************************************************************************* // Method : CTestAppConsole::RunL() // Purpose : // Parameters : // Return Value: //******************************************************************************* void CTestAppConsole::RunL() { // According to current test case and direct the user's command // to proper command handler. switch ( iCurMenu ) { case EMainMenu: DisplayConsoleMenu( KTxtMainInstructions ); ProcessMainInput(); break; case EDTMFTestMenu: DisplayConsoleMenu( KTxtDTMFInstructions ); ProcessDTMFInput(); break; case ECodecTestMenu: DisplayConsoleMenu( KTxtCodecInstructions ); ProcessCodecInput(); break; default: break; } //ProcessKey( TChar( iConsole->KeyCode() ) ); //DoRead(); } //******************************************************************************* // Method : CTestAppConsole::DoCancel() // Purpose : // Parameters : // Return Value: //******************************************************************************* void CTestAppConsole::DoCancel() { iConsole->ReadCancel(); } //******************************************************************************* // Method : CTestAppConsole::DisplayConsoleMenu() // Purpose : Display main or sub console menus for different test cases // Parameters : TDesc &aInstructions // Return Value: void //******************************************************************************* void CTestAppConsole::DisplayConsoleMenu( const TDesC &aInstructions ) { if ( iInstruct ) { delete iInstruct; iInstruct = NULL; } iInstruct = aInstructions.AllocL(); iConsole->ClearScreen(); iConsole->Write( *iInstruct ); } //******************************************************************************* // Method : CTestAppConsole::ProcessMainInput() // Purpose : Obtain user's option and decide which test case to run next. // Parameters : // Return Value: //******************************************************************************* void CTestAppConsole::ProcessMainInput() { TBuf<20> line; GetStringFromConsole( line ); if ( line.Length() > 0 ) { TChar inputChar = line.Ptr()[0]; switch( inputChar ) { case '1': RunTestCreateSession(); break; case 'q': RunTestCreateStreams(); break; case 'z': RunTest1c(); break; case '2': RunTestPrepareStreams(); break; case 'p': RunTest2p(); break; case 'w': RunTestStartStream(); break; case '3': RunTestPauseStreams(); break; case '4': RunTestResumeStreams(); break; case '5': RunTestStopStream(); break; case 'd': RunTestDeleteStreams(); break; case '6': RunTestCloseSession(); break; case '7': RunTest7(); break; case '8': RunTestGetCodecAndAudioSettings(); break; case 'l': SetRemoteAddr(); break; case 'n': SetNetSettings(); break; case 'r': SendNonRtcpData(); break; case 't': ToggleInactivityTimer(); break; // Menus case 'c': iCurMenu = ECodecTestMenu; DisplayConsoleMenu( KTxtCodecInstructions ); break; case 'm': iCurMenu = EDTMFTestMenu; DisplayConsoleMenu( KTxtDTMFInstructions ); break; case '9': iMccInterface->Close(); CActiveScheduler::Stop(); break; default: _LIT( KTxtWrongOption, "Wrong Option! Try Again." ); DisplayMsg( KTxtWrongOption ); break; } } // Ready to get next input option. DoRead(); } //******************************************************************************* // Method : CTestAppConsole::DisplayMsg() // Purpose : Display testing message on screen // Parameters : TDesC & // Return Value: //******************************************************************************* void CTestAppConsole::DisplayMsg( const TDesC &aMsg ) { iConsole->ClearScreen(); iConsole->Write( *iInstruct ); iConsole->Printf( KTxtLineBreak ); iConsole->Printf( aMsg ); iConsole->Printf( KTxtLineBreak ); } //******************************************************************************* // Method : CTestAppConsole::GetAddrFromConsole() // Purpose : // Parameters : // Return Value: //******************************************************************************* TKeyCode CTestAppConsole::GetStringFromConsole( TDes &aAddr ) { // Get a line from console TKeyCode input = EKeyNull; const TInt start_pos = iConsole->WhereX(); aAddr.Zero(); // loop until descriptor full or EKeyEnter or EKeyEscape entered do { // get one character input = iConsole->Getch(); // process it if( input == EKeyBackspace || input == EKeyDelete ) { // backspace or delete if( iConsole->WhereX() > start_pos ) { iConsole->SetPos( iConsole->WhereX() - 1 ); iConsole->ClearToEndOfLine(); if( aAddr.Length() > 0 ) { aAddr.SetLength( aAddr.Length() - 1 ); } } } else { // other than backspace or delete TChar ch( input ); if( ch.IsPrint() ) { aAddr.Append( ch ); iConsole->Printf( _L( "%c" ), input ); } } } while( aAddr.Length() < aAddr.MaxLength() && input != EKeyEnter && input != EKeyEscape ); DisplayMsg( KTxtLineBreak ); return input; } // --------------------------------------------------------------------------- // CTestAppConsole::SetNetSettings // // --------------------------------------------------------------------------- // void CTestAppConsole::SetNetSettings() { TBuf<20> line; TUint port; TUint rport; TUint iapid; iConsole->Printf( _L( "\nEnter Iap Id: " ) ); GetIntegerFromConsole( iapid ); iNetSettings.iIapId = iapid; iNetSettings.iMediaQosValue = 46; iConsole->Printf( _L( "\nEnter the Remote IP address " ) ); GetStringFromConsole( line ); iRemoteAddr.Input( line ); iConsole->Printf( _L( "\nEnter the Remote port: " ) ); GetIntegerFromConsole( rport ); RDebug::Print( _L("RemotePort: %d"), rport ); iRemoteAddr.SetPort( rport ); iConsole->Printf( _L( "\nEnter the Local port: " ) ); GetIntegerFromConsole( port ); RDebug::Print( _L( "LocalPort: %d" ), port ); iConsole->Printf( _L( "Addr: %d\n"), iRemoteAddr.Address() ); RDebug::Print( _L( "RemoteAddr: %d"), iRemoteAddr.Address() ); iNetSettings.iRemoteAddress.SetAddress( iRemoteAddr.Address() ); iNetSettings.iRemoteAddress.SetPort( rport ); iNetSettings.iLocalPort = port; DisplayMsg( _L( "Create DTMF session <y/n>: " ) ); GetStringFromConsole( line ); TChar inputChar = line.Ptr()[0]; if ( inputChar == 'y' ) { iDtmfMode = ETrue; } // RTCP is not available in DTMF sessions if ( !iDtmfMode ) { iConsole->Printf( _L( "\nEnable RTCP? <y/n>: " ) ); GetStringFromConsole( line ); TChar inputChar = line.Ptr()[0]; if ( inputChar == 'y' ) { iNetSettings.iMediaSignalling = ESignalRtcp; iConsole->Printf( _L( "\nRTCP enabled\n" ) ); } } iNetSettingsDone = ETrue; } // --------------------------------------------------------------------------- // CTestAppConsole::RunTestCreateSession // // --------------------------------------------------------------------------- // void CTestAppConsole::RunTestCreateSession() { TBuf<20> line; if ( !iNetSettingsDone ) { SetNetSettings(); } if ( iDtmfMode ) { DisplayMsg( _L( "Enable inband DTMF <y/n>: " ) ); GetStringFromConsole( line ); TChar inputChar = line.Ptr()[0]; if ( inputChar == 'y' ) { iNetSettings.iMediaSignalling = TMCCMediaSignalingType( iNetSettings.iMediaSignalling | KSignalInbandDtmf ); DisplayMsg( _L( "Inband DTMF enabled" ) ); } DisplayMsg( _L( "Enable outband DTMF <y/n>: " ) ); GetStringFromConsole( line ); inputChar = line.Ptr()[0]; if ( inputChar == 'y' ) { iNetSettings.iMediaSignalling = TMCCMediaSignalingType( iNetSettings.iMediaSignalling | KSignalOutbandDtmf ); DisplayMsg( _L( "Outband DTMF enabled" ) ); } TInt err = iMccInterface->CreateSession( iDTMFSessionID ); if ( err == KErrNone ) { iConsole->Printf( _L( "DTMF Session created, id: %d\n" ), iSessionId ); } else { iConsole->Printf( _L( "Could not create DTMF session, error %d\n" ), err ); } err = iMccInterface->CreateLink( iDTMFSessionID, KMccLinkGeneral, iDtmfLinkID, iNetSettings ); if ( err == KErrNone ) { iConsole->Printf( _L( "DTMF link created, id: %d\n" ), iDtmfLinkID ); } else { iConsole->Printf( _L( "Could not create DTMF session, error %d\n" ), err ); } } else { // Create session TInt err = iMccInterface->CreateSession( iSessionId ); if ( err == KErrNone ) { iConsole->Printf( _L( "Session created, id: %d\n" ), iSessionId ); } else { iConsole->Printf( _L( "Could not create session, error %d\n" ), err ); } } TVersion version = iMccInterface->Version(); iConsole->Printf( _L( "Version %d.%d.%d\n" ), version.iMajor, version.iMinor, version.iBuild ); }; // --------------------------------------------------------------------------- // CTestAppConsole::RunTestCreateStreams // // --------------------------------------------------------------------------- // void CTestAppConsole::RunTestCreateStreams() { TInt err( KErrNone ); if ( KMccFourCCIdDTMF == iCodecArray[iCodecSelected]->FourCC() ) { // Create DTMF stream err = iMccInterface->CreateStream( iDTMFSessionID, iDtmfLinkID, iDTMFStreamID, EMccAudioUplinkStream, iCodecArray[iCodecSelected] ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not create DTMF stream" ) ); return; } iConsole->Printf( _L( "\nEnter the Remote port: " ) ); TInt rport; GetIntegerFromConsole( rport ); iRemoteAddr.SetPort( rport ); iMccInterface->SetRemoteAddress( iDTMFSessionID, iDtmfLinkID, iRemoteAddr ); iConsole->Printf( _L( "Stream created. ID: DTMF %d, pt: %d\n" ), iDTMFStreamID, iCodecArray[iCodecSelected]->PayloadType() ); } else { // Create uplink iConsole->Printf( _L( "Creating uplink...\n" ) ); err = iMccInterface->CreateLink( iSessionId, KMccLinkGeneral, iUplinkId, iNetSettings ); if ( err == KErrNone ) { iConsole->Printf( _L( "Uplink created, id: %d, port: %d\n" ), iUplinkId, iNetSettings.iLocalPort ); } else { iConsole->Printf( _L( "Could not create uplink, error %d\n" ), err ); return; } // Create upstream // Make the AMR codec compatible with the RTP sender program if ( iCodecSelected == 0 ) { iCodecArray[iCodecSelected]->SetBitrate( KAmrNbBitrate122 ); iCodecArray[iCodecSelected]->SetCodecMode( EOctetAligned ); iCodecArray[iCodecSelected]->SetPayloadType( 96 ); iCodecArray[iCodecSelected]->SetPTime( 20 ); iCodecArray[iCodecSelected]->SetMaxPTime( 200 ); } err = iMccInterface->CreateStream( iSessionId, iUplinkId, iUpStreamId, EMccAudioUplinkStream, iCodecArray[iCodecSelected] ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not create upstream, error %d" ), err ); return; } iConsole->Printf( _L( "Upstream created. Sess %d, link %d, stream %d, pt: %d\n" ), iSessionId, iUplinkId, iUpStreamId, iCodecArray[iCodecSelected]->PayloadType() ); // Create downlink iConsole->Printf( _L( "Creating downlink...\n" ) ); err = iMccInterface->CreateLink( iSessionId, KMccLinkGeneral, iDownlinkId, iNetSettings ); if ( err == KErrNone ) { iConsole->Printf( _L( "Downlink created, id: %d, port: %d\n" ), iDownlinkId, iNetSettings.iLocalPort ); } else { iConsole->Printf( _L( "Could not create downlink, error %d\n" ), err ); } // Create downstream err = iMccInterface->CreateStream( iSessionId, iDownlinkId, iDownStreamId, EMccAudioDownlinkStream, iCodecArray[iCodecSelected] ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not create downstream, error %d" ), err ); return; } iConsole->Printf( _L( "Downstream created. Sess %d, link %d, stream %d, pt: %d\n" ), iSessionId, iDownlinkId, iDownStreamId, iCodecArray[iCodecSelected]->PayloadType() ); iMccInterface->SetRemoteAddress( iSessionId, iUplinkId, iRemoteAddr ); iMccInterface->SetRemoteAddress( iSessionId, iDownlinkId, iRemoteAddr ); iConsole->Printf( _L( "\nRemote addresses set" ) ); } } // --------------------------------------------------------------------------- // CTestAppConsole::RunTest1c // // --------------------------------------------------------------------------- // void CTestAppConsole::RunTest1c() { TInt err( KErrNone ); if ( KMccFourCCIdDTMF == iCodecArray[iCodecSelected]->FourCC() ) { err = iMccInterface->CreateStream( iDTMFSessionID, iDtmfLinkID, iDTMFStreamID, EMccAudioUplinkStream, iCodecArray[iCodecSelected] ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not create DTMF stream" ) ); return; } iConsole->Printf( _L( "\nEnter the Remote port: " ) ); TInt rport; GetIntegerFromConsole( rport ); iRemoteAddr.SetPort( rport ); iMccInterface->SetRemoteAddress( iDTMFSessionID, iDtmfLinkID, iRemoteAddr ); iConsole->Printf( _L( "Stream created. ID: DTMF %d, pt: %d\n" ), iDTMFStreamID, iCodecArray[iCodecSelected]->PayloadType() ); } else { iConsole->Printf( _L( "\nCreate Uplink or Downlink <u/d>: " ) ); TBuf<20> line; GetStringFromConsole( line ); TChar inputChar = line.Ptr()[0]; if ( inputChar == 'u' ) { err = iMccInterface->CreateStream( iSessionId, iUplinkId, iUpStreamId, EMccAudioUplinkStream, iCodecArray[iCodecSelected] ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not create uplink stream" ) ); return; } } else if ( inputChar == 'd' ) { err = iMccInterface->CreateStream( iSessionId, iDownlinkId, iDownStreamId, EMccAudioDownlinkStream, iCodecArray[iCodecSelected] ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not create downlink stream" ) ); return; } } else { iConsole->Printf( _L( "\nInvalid input" ) ); return; } iConsole->Printf( _L( "\nEnter the Remote port: " ) ); TUint rport; GetStringFromConsole( line ); TLex lex( line ); lex.Val( rport,EDecimal ); iRemoteAddr.SetPort( rport ); if ( inputChar == 'u' ) { err = iMccInterface->SetRemoteAddress( iSessionId, iUplinkId, iRemoteAddr ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not set remote address ( up )" ) ); return; } } else if ( inputChar == 'd' ) { err = iMccInterface->SetRemoteAddress( iSessionId, iDownlinkId, iRemoteAddr ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not set remote address ( down )" ) ); return; } } iConsole->Printf( _L( "Stream created. ID: UL: %d, DL: %d, pt: %d\n" ), iUpStreamId, iDownStreamId, iCodecArray[iCodecSelected]->PayloadType() ); } } // --------------------------------------------------------------------------- // CTestAppConsole::RunTestPrepareStreams // // --------------------------------------------------------------------------- // void CTestAppConsole::RunTestPrepareStreams() { TInt err( KErrNone ); if ( KMccFourCCIdDTMF == iCodecArray[iCodecSelected]->FourCC() ) { if ( KNullId != iDTMFStreamID ) { iMccInterface->SetPriority( iDTMFSessionID, iDtmfLinkID, iDTMFStreamID, KAudioPriorityPhoneCall /*EMdaPriorityNormal*/ ); err = iMccInterface->PrepareStream( iDTMFSessionID, iDtmfLinkID, iDTMFStreamID ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not prepare DTMF stream" ) ); return; } else { iConsole->Printf( _L( "\nDTMF stream prepared" ) ); } } else { iConsole->Printf( _L( "\nCreate DTMF stream first" ) ); } } else { // Set UL priority err = iMccInterface->SetPriority( iSessionId, iUplinkId, iUpStreamId, KAudioPriorityPhoneCall ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not set priority ( up )" ) ); return; } else { iConsole->Printf( _L( "\nUpstream priority set" ) ); } // Set DL priority err = iMccInterface->SetPriority( iSessionId, iDownlinkId, iDownStreamId, KAudioPriorityPhoneCall ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not set priority ( down )" ) ); return; } else { iConsole->Printf( _L( "\nDownstream priority set" ) ); } // Prepare upstream err = iMccInterface->PrepareStream( iSessionId, iUplinkId, iUpStreamId ); // UP if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not prepare ( up )" ) ); return; } else { iConsole->Printf( _L( "\nUpstream prepared" ) ); } // Prepare downstream err = iMccInterface->PrepareStream( iSessionId, iDownlinkId, iDownStreamId ); // Down if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not prepare ( down )" ) ); return; } else { iConsole->Printf( _L( "\nDownstream prepared\n" ) ); } } } // --------------------------------------------------------------------------- // CTestAppConsole::RunTest2p // // --------------------------------------------------------------------------- // void CTestAppConsole::RunTest2p() { TUint iUpStreamId; TUint sessionID; TBool inputOK( ETrue ); DisplayMsg( _L( "\nSessionId: " ) ); if ( GetIntegerFromConsole( sessionID ) ) { inputOK = EFalse; } DisplayMsg( _L( "\nStreamId to prepare: " ) ); if ( GetIntegerFromConsole( iUpStreamId ) ) { inputOK = EFalse; } if ( inputOK ) { iMccInterface->SetPriority( sessionID, 0/*TBI*/, iUpStreamId, 100 ); iMccInterface->PrepareStream( sessionID, 0/*TBI*/, iUpStreamId ); } else { DisplayMsg( _L( "Invalid input!" ) ); } } // --------------------------------------------------------------------------- // CTestAppConsole::RunTestStartStream // // --------------------------------------------------------------------------- // void CTestAppConsole::RunTestStartStream() { TBuf<20> line; TUint input; TChar inputChar; TBool inputOK( ETrue ); TInt err( KErrNone ); TUint32 session( 0 ); TUint32 link( 0 ); TUint32 stream( 0 ); TBool startPaused( EFalse ); TBool enableRtcp( EFalse ); DisplayMsg( _L( "\nStart which stream? 1 = up, 2 = down: " ) ); if ( GetIntegerFromConsole( input ) ) { inputOK = EFalse; } if ( !inputOK ) { DisplayMsg( _L( "Invalid input!" ) ); } else if ( input == 1 ) { session = iSessionId; link = iUplinkId; stream = iUpStreamId; } else if ( input == 2 ) { session = iSessionId; link = iDownlinkId; stream = iDownStreamId; } else { DisplayMsg( _L( "Please enter 1 or 2" ) ); } // Get pause mode iConsole->Printf( _L( "\nStart stream paused? <y/n>: " ) ); GetStringFromConsole( line ); inputChar = line.Ptr()[0]; if ( inputChar == 'y' ) { startPaused = ETrue; } // Get RTCP mode iConsole->Printf( _L( "\nEnable RTCP? <y/n>: " ) ); GetStringFromConsole( line ); inputChar = line.Ptr()[0]; if ( inputChar == 'y' ) { enableRtcp = ETrue; } // Start stream iConsole->Printf( _L( "\nStarting stream..." ) ); err = iMccInterface->StartStream( session, link, stream, startPaused, enableRtcp ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not start stream, error %d" ), err ); } else { iConsole->Printf( _L( "\nStream started" ) ); } } // --------------------------------------------------------------------------- // CTestAppConsole::RunTestPauseStreams // // --------------------------------------------------------------------------- // void CTestAppConsole::RunTestPauseStreams() { TBuf<20> line; TUint input; TChar inputChar; TBool enableRtcp( EFalse ); TBool inputOK( ETrue ); TInt err( KErrNone ); DisplayMsg( _L( "\nPause which stream? 1 = up, 2 = down: " ) ); if ( GetIntegerFromConsole( input ) ) { inputOK = EFalse; } if ( !inputOK ) { DisplayMsg( _L( "Invalid input!" ) ); return; } // Get RTCP mode iConsole->Printf( _L( "\nEnable RTCP? <y/n>: " ) ); GetStringFromConsole( line ); inputChar = line.Ptr()[0]; if ( inputChar == 'y' ) { enableRtcp = ETrue; } if ( input == 1 ) { // Pause upstream iConsole->Printf( _L( "\nPausing upstream..." ) ); err = iMccInterface->PauseStream( iSessionId, iUplinkId, iUpStreamId, enableRtcp ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not pause upstream, error %d" ), err ); } else { iConsole->Printf( _L( "\nUpstream paused" ) ); } } else if ( input == 2 ) { // Pause downstream iConsole->Printf( _L( "\nPausing downstream..." ) ); err = iMccInterface->PauseStream( iSessionId, iDownlinkId, iDownStreamId, enableRtcp ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not pause downstream, error %d" ), err ); } else { iConsole->Printf( _L( "\nDownstream paused" ) ); } } else { DisplayMsg( _L( "Please enter 1 or 2" ) ); } } // --------------------------------------------------------------------------- // CTestAppConsole::RunTestResumeStreams // // --------------------------------------------------------------------------- // void CTestAppConsole::RunTestResumeStreams() { TBuf<20> line; TUint input; TBool inputOK( ETrue ); TChar inputChar; TBool enableRtcp( EFalse ); TInt err( KErrNone ); DisplayMsg( _L( "\nResume which stream? 1 = up, 2 = down: " ) ); if ( GetIntegerFromConsole( input ) ) { inputOK = EFalse; } if ( !inputOK ) { DisplayMsg( _L( "Invalid input!" ) ); return; } // Get RTCP mode iConsole->Printf( _L( "\nEnable RTCP? <y/n>: " ) ); GetStringFromConsole( line ); inputChar = line.Ptr()[0]; if ( inputChar == 'y' ) { enableRtcp = ETrue; } if ( input == 1 ) { // Resume upstream iConsole->Printf( _L( "\nResuming upstream..." ) ); err = iMccInterface->ResumeStream( iSessionId, iUplinkId, iUpStreamId, enableRtcp ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not resume upstream, error %d" ), err ); } else { iConsole->Printf( _L( "\nUpstream resumed" ) ); } } else if ( input == 2 ) { // Resume downstream iConsole->Printf( _L( "\nResuming downstream..." ) ); err = iMccInterface->ResumeStream( iSessionId, iDownlinkId, iDownStreamId, enableRtcp ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not resume downstream, error %d" ), err ); } else { iConsole->Printf( _L( "\nDownstream resumed" ) ); } } else { DisplayMsg( _L( "Please enter 1 or 2" ) ); } } // --------------------------------------------------------------------------- // CTestAppConsole::RunTestStopStream // // --------------------------------------------------------------------------- // void CTestAppConsole::RunTestStopStream() { TUint input; TBool inputOK( ETrue ); TInt err( KErrNone ); DisplayMsg( _L( "\nStop which stream? 1 = up, 2 = down: " ) ); if ( GetIntegerFromConsole( input ) ) { inputOK = EFalse; } if ( !inputOK ) { DisplayMsg( _L( "Invalid input!" ) ); } else if ( input == 1 ) { // Stop upstream iConsole->Printf( _L( "\nStopping upstream..." ) ); err = iMccInterface->StopStream( iSessionId, iUplinkId, iUpStreamId ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not stop upstream, error %d" ), err ); } else { iConsole->Printf( _L( "\nUpstream stopped" ) ); } } else if ( input == 2 ) { // Stop downstream iConsole->Printf( _L( "\nStopping downstream..." ) ); err = iMccInterface->StopStream( iSessionId, iDownlinkId, iDownStreamId ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not stop downstream, error %d" ), err ); } else { iConsole->Printf( _L( "\nDownstream stopped" ) ); } } else { DisplayMsg( _L( "Please enter 1 or 2" ) ); } } // --------------------------------------------------------------------------- // CTestAppConsole::RunTestDeleteStreams // // --------------------------------------------------------------------------- // void CTestAppConsole::RunTestDeleteStreams() { TUint input; TBool inputOK( ETrue ); TInt err( KErrNone ); DisplayMsg( _L( "\nDelete which stream? 1 = up, 2 = down: " ) ); if ( GetIntegerFromConsole( input ) ) { inputOK = EFalse; } if ( !inputOK ) { DisplayMsg( _L( "Invalid input!" ) ); } else if ( input == 1 ) { // Delete upstream iConsole->Printf( _L( "\nDeleting upstream..." ) ); err = iMccInterface->DeleteStream( iSessionId, iUplinkId, iUpStreamId ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not delete upstream, error %d" ), err ); } else { iConsole->Printf( _L( "\nUpstream deleted" ) ); } // Close link too iConsole->Printf( _L( "\nClosing uplink..." ) ); err = iMccInterface->CloseLink( iSessionId, iUplinkId ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not close uplink, error %d" ), err ); } else { iConsole->Printf( _L( "\nUplink closed" ) ); } } else if ( input == 2 ) { // Delete downstream iConsole->Printf( _L( "\nDeleting downstream..." ) ); err = iMccInterface->DeleteStream( iSessionId, iDownlinkId, iDownStreamId ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not delete downstream, error %d" ), err ); } else { iConsole->Printf( _L( "\nDownstream deleted" ) ); } // Close link too iConsole->Printf( _L( "\nClosing downlink..." ) ); err = iMccInterface->CloseLink( iSessionId, iDownlinkId ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not close downlink, error %d" ), err ); } else { iConsole->Printf( _L( "\nDownlink closed" ) ); } } else { DisplayMsg( _L( "Please enter 1 or 2" ) ); } } // --------------------------------------------------------------------------- // CTestAppConsole::RunTestCloseSession // // --------------------------------------------------------------------------- // void CTestAppConsole::RunTestCloseSession() { TUint aSessionId; iConsole->Printf( _L( "\nEnter SessionId: " ) ); TBuf<20> line; GetStringFromConsole( line ); TLex lex( line ); lex.Val( aSessionId,EDecimal ); TInt err = iMccInterface->CloseSession( aSessionId ); if ( err == KErrNone ) { iConsole->Printf( _L( "Session Closed.\n" ) ); } else { iConsole->Printf( _L( "\nCould not close session, error %d" ), err ); } } // --------------------------------------------------------------------------- // CTestAppConsole::RunTest7 // // --------------------------------------------------------------------------- // void CTestAppConsole::RunTest7() { //TInt aBitrate = 12200; TUint aVolume = 5; TUint aGain = 4; TInt aBalance = 0; iConsole->Printf( _L( "\nEnter volume: " ) ); GetIntegerFromConsole( aVolume ); iMccInterface->SetVolume( aVolume ); iConsole->Printf( _L( "\nEnter gain: " ) ); GetIntegerFromConsole( aGain ); iMccInterface->SetGain( aGain ); iMccInterface->SetBalance( iSessionId, iUplinkId, iUpStreamId, aBalance, EMccAudioPlay ); iMccInterface->SetBalance( iSessionId, iDownlinkId, iDownStreamId, aBalance, EMccAudioPlay ); iConsole->Printf( _L( "Settings done.\n " ) ); } // --------------------------------------------------------------------------- // CTestAppConsole::RunTestGetCodecAndAudioSettings // // --------------------------------------------------------------------------- // void CTestAppConsole::RunTestGetCodecAndAudioSettings() { // get codec TInt volume; TInt maxvolume; TInt aGain; TInt aMGain; CMccCodecInformation* codec( NULL ); TInt aUpBalance; TInt aDownBalance; TInt error; iMccInterface->GetGain( aGain ); iMccInterface->MaxGain( iSessionId, iUplinkId, iUpStreamId, aMGain ); TRAP( error, codec = iMccInterface->GetCodecL( iSessionId, iUplinkId, iUpStreamId ) ); if ( error != KErrNone ) { iConsole->Printf( _L( "Could not get codec, error %d\n" ), error ); } iMccInterface->Volume( volume ); iMccInterface->MaxVolume( iSessionId, iDownlinkId, iDownStreamId, maxvolume ); iMccInterface->Balance( iSessionId, iUplinkId, iUpStreamId, aUpBalance, EMccAudioPlay ); iMccInterface->Balance( iSessionId, iDownlinkId, iDownStreamId, aDownBalance, EMccAudioPlay ); iConsole->Printf( _L( "Gain: %d MaxGain: %d Codec: %d Vol: %d MaxVol: %d uBal: %d dBal: %d\n" ), aGain, aMGain, codec->FourCC(), volume, maxvolume, aUpBalance, aDownBalance ); iConsole->Printf( _L( "Get done.\n" ) ); } // --------------------------------------------------------------------------- // CTestAppConsole::RunTestDisplaySupportedCodecs // // --------------------------------------------------------------------------- // void CTestAppConsole::RunTestDisplaySupportedCodecs() { iConsole->Printf( _L( "Supported codecs: %d\n" ), iCodecArray.Count() ); for ( TInt i=0; i<iCodecArray.Count(); i++ ) { iConsole->Printf( _L( "codec %d: br:%d 4cc:%d\n" ), i, iCodecArray[i]->Bitrate(), iCodecArray[i]->FourCC() ); } } // --------------------------------------------------------------------------- // CTestAppConsole::RunSetCodecSettings // // --------------------------------------------------------------------------- // void CTestAppConsole::RunSetCodecSettings() { iConsole->Printf( _L( "\nEnter PTime: " ) ); TUint iPTime; GetIntegerFromConsole( iPTime ); iCodecArray[iCodecSelected]->SetPTime( iPTime ); iConsole->Printf( _L( "\nEnter MaxPTime: " ) ); TUint iMaxPTime; GetIntegerFromConsole( iMaxPTime ); iCodecArray[iCodecSelected]->SetMaxPTime( iMaxPTime ); iConsole->Printf( _L( "\nSettings done" ) ); } // --------------------------------------------------------------------------- // CTestAppConsole::RunSetFmtpAttr // // --------------------------------------------------------------------------- // void CTestAppConsole::RunSetFmtpAttr() { TBuf8<50> buf; TInt err( KErrNone ); // First, try to set an invalid FMTP attribute string _LIT8( KFmtpInvalid, "!PQOI;oOwiU=45;#Ur(%UT" ); buf.Append( KFmtpInvalid ); TRAP( err, iCodecArray[iCodecSelected]->SetFmtpAttrL( buf ) ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not set invalid FMTP attribute, err %d" ), err ); } else { iConsole->Printf( _L( "\nInvalid FMTP attribute set. (no error)" ) ); } // Now make a valid one _LIT8( KFmtpPayload, "%d " ); _LIT8( KFmtpOctetAlign, "octet-align=%d;" ); _LIT8( KFmtpModeSet, "mode-set=%d,%d, %d" ); TInt payload( 5 ); TInt octetAlign( 1 ); TInt fmtpModeSet( 2 ); // The string should look like this: // "xx octet-align=0/1; mode-set=0-7;" (where xx is the payload type) buf.Format( KFmtpPayload, payload ); buf.AppendFormat( KFmtpOctetAlign, octetAlign ); buf.AppendFormat( KFmtpModeSet, fmtpModeSet, 0, 5 ); TRAP( err, iCodecArray[iCodecSelected]->SetFmtpAttrL( buf ) ); if ( err != KErrNone ) { iConsole->Printf( _L( "\nCould not set FMTP attribute, err %d" ), err ); } else { iConsole->Printf( _L( "\nFMTP attribute set." ) ); } } // --------------------------------------------------------------------------- // CTestAppConsole::ToggleVAD // // --------------------------------------------------------------------------- // void CTestAppConsole::ToggleVAD() { if ( iCodecArray[iCodecSelected]->VAD() ) { iCodecArray[iCodecSelected]->EnableVAD( EFalse ); iConsole->Printf( _L( "VAD: OFF\n" ) ); } else { TInt err = iCodecArray[iCodecSelected]->EnableVAD( ETrue ); if ( err == KErrNotSupported ) iConsole->Printf( _L( "VAD: Not supported (in current codec)\n" ) ); else iConsole->Printf( _L( "VAD: ON\n" ) ); } } // --------------------------------------------------------------------------- // CTestAppConsole::ChangeCodec // // --------------------------------------------------------------------------- // void CTestAppConsole::ChangeCodec() { TInt codecs = iCodecArray.Count(); if ( codecs == 0 ) return; RDebug::Print( _L( "CodecArray size: %d" ), codecs ); iCodecSelected++; if ( iCodecSelected >= codecs ) { iCodecSelected = 0; } if ( iCodecArray[iCodecSelected]->FourCC() == KMccFourCCIdAMRNB ) { iConsole->Printf( _L( "Codec AMR-NB " ) ); iCodecArray[iCodecSelected]->SetPayloadType( 128 ); } if ( iCodecArray[iCodecSelected]->FourCC() == KMccFourCCIdG711 ) { if ( iCodecArray[iCodecSelected]->CodecMode() == EPCMU ) iConsole->Printf( _L( "Codec PCMU " ) ); if ( iCodecArray[iCodecSelected]->CodecMode() == EPCMA ) iConsole->Printf( _L( "Codec PCMA " ) ); } if ( iCodecArray[iCodecSelected]->FourCC() == KMccFourCCIdG729 ) { iConsole->Printf( _L( "Codec G.729 " ) ); } if ( iCodecArray[iCodecSelected]->FourCC() == KMccFourCCIdILBC ) { iConsole->Printf( _L( "Codec iLBC " ) ); } if ( iCodecArray[iCodecSelected]->FourCC() == KMccFourCCIdDTMF ) { iConsole->Printf( _L( "Codec DTMF " ) ); } iConsole->Printf( _L( "4CC: %d\n" ), iCodecArray[iCodecSelected]->FourCC() ); } // --------------------------------------------------------------------------- // CTestAppConsole::SetCodec // // --------------------------------------------------------------------------- // void CTestAppConsole::SetCodec() { iMccInterface->SetCodec( iSessionId, iUplinkId, iUpStreamId, iCodecArray[iCodecSelected] ); iMccInterface->SetCodec( iSessionId, iDownlinkId, iDownStreamId, iCodecArray[iCodecSelected] ); iConsole->Printf( _L( "Codec set to %d\n" ), iCodecArray[iCodecSelected]->FourCC() ); } // --------------------------------------------------------------------------- // CTestAppConsole::SetRemoteAddr // // --------------------------------------------------------------------------- // void CTestAppConsole::SetRemoteAddr() { TBuf<20> line; TLex lex( line ); iConsole->ClearScreen(); iConsole->Printf( _L( "\nEnter the Remote IP address " ) ); GetStringFromConsole( line ); iRemoteAddr.Input( line ); iConsole->Printf( _L( "\nEnter the Remote port: " ) ); TUint rport; GetStringFromConsole( line ); lex.Assign( line ); lex.Val( rport,EDecimal ); iRemoteAddr.SetPort( rport ); iConsole->Printf( _L( "Addr: %d , port %d\n" ), iRemoteAddr.Address(), rport ); // Get link type from user iConsole->Printf( _L( "Enter link type ( u for up, d for down ):\n" ) ); GetStringFromConsole( line ); TChar inputChar = line.Ptr()[0]; if ( inputChar == 'u' ) { iMccInterface->SetRemoteAddress( iSessionId, iUplinkId, iRemoteAddr ); } else if ( inputChar == 'd' ) { iMccInterface->SetRemoteAddress( iSessionId, iDownlinkId, iRemoteAddr ); } else { iConsole->Printf( _L( "Invalid input\n" ) ); } } // --------------------------------------------------------------------------- // CTestAppConsole::RunTestCodecFactory // // --------------------------------------------------------------------------- // void CTestAppConsole::RunTestCodecFactory() { RArray< CMccCodecInformation > codecArray; CMccCodecInformationFactory* infoFactory = CMccCodecInformationFactory::NewL(); TBuf8<KMaxSdpNameLength> sdpName; TInt i; for ( i = 0; i < iCodecInformation.Count(); i++ ) { sdpName = iCodecInformation[i]->SdpName(); CMccCodecInformation* tempInfo = NULL; TRAPD( err1, tempInfo = infoFactory->CreateCodecInformationL( sdpName ) ); if ( err1 ) { tempInfo = NULL; } else { codecArray.Append( *tempInfo ); delete tempInfo; } } for ( i = 0; i < codecArray.Count(); i++ ) { iCodecArray.Append( &codecArray[ i ] ); } codecArray.Close(); RDebug::Print( _L( "CodecArray size: %d" ), iCodecArray.Count() ); delete infoFactory; } // --------------------------------------------------------------------------- // CTestAppConsole::ToggleInactivityTimer // // --------------------------------------------------------------------------- // void CTestAppConsole::ToggleInactivityTimer() { TInt result( KErrNone ); TUint input; TBool inputOK( ETrue ); TUint32 link( 0 ); TUint32 stream( 0 ); const TInt KInactivityTimeout( 8000000 ); DisplayMsg( _L( "\nTimer, which stream? 1 = up, 2 = down: " ) ); if ( GetIntegerFromConsole( input ) ) { inputOK = EFalse; } if ( !inputOK ) { DisplayMsg( _L( "Invalid input!" ) ); } else if ( input == 1 ) { link = iUplinkId; stream = iUpStreamId; } else if ( input == 2 ) { link = iDownlinkId; stream = iDownStreamId; } else { DisplayMsg( _L( "Please enter 1 or 2" ) ); return; } if ( iInactivityTimerActive ) { result = iMccInterface->StopInactivityTimer( iSessionId, link, stream ); if ( result == KErrNone ) { iInactivityTimerActive = EFalse; iConsole->Printf( _L( "Inactivity timer stopped\n" ) ); } else { iConsole->Printf( _L( "Could not stop timer, error %d\n" ), result ); } } else { result = iMccInterface->StartInactivityTimer( iSessionId, link, stream, KInactivityTimeout ); if ( result == KErrNone ) { iInactivityTimerActive = ETrue; iConsole->Printf( _L( "Inactivity timer started\n" ) ); } else { iConsole->Printf( _L( "Could not start timer, error %d\n" ), result ); } } } // --------------------------------------------------------------------------- // CTestAppConsole::SendNonRtcpData // // --------------------------------------------------------------------------- // void CTestAppConsole::SendNonRtcpData() { TBuf8<50> data; _LIT8( KData, "NonRtcpData #%d" ); data.Format( KData, iNumOfNonRtcpDataSent++ ); TInt result = iMccInterface->SendRTCPAnyData( iSessionId, iDownlinkId, iDownStreamId, data ); if ( result == KErrNone ) { iConsole->Printf( _L( "Non-RTCP data sent\n" ) ); } else { iConsole->Printf( _L( "Could not send data, error %d\n" ), result ); } } // --------------------------------------------------------------------------- // CTestAppConsole::MccMediaStarted // // --------------------------------------------------------------------------- // void CTestAppConsole::MccMediaStarted( TUint32 aSessionID, TUint32 aLinkId, TUint32 aStreamID, TUint32 aSinkSourceId ) { RDebug::Print( _L( "CALLBACK: Stream Started: sess %u, link %u, stream %u, sinksource %u" ), aSessionID, aLinkId, aStreamID, aSinkSourceId ); iConsole->Printf( _L( "\nCALLBACK: Stream Started: sess %u, link %u, stream %u, sinksource %u\n" ), aSessionID, aLinkId, aStreamID, aSinkSourceId ); } // --------------------------------------------------------------------------- // CTestAppConsole::MccMediaStopped // // --------------------------------------------------------------------------- // void CTestAppConsole::MccMediaStopped( TUint32 aSessionID, TUint32 aLinkId, TUint32 aStreamID, TUint32 aSinkSourceId ) { RDebug::Print( _L( "CALLBACK: Stream Stopped: sess %u, link %u, stream %u, sinksource %u" ), aSessionID, aLinkId, aStreamID, aSinkSourceId ); iConsole->Printf( _L( "\nCALLBACK: Stream Stopped: sess %u, link %u, stream %u, sinksource %u\n" ), aSessionID, aLinkId, aStreamID, aSinkSourceId ); } // --------------------------------------------------------------------------- // CTestAppConsole::MccMediaPaused // // --------------------------------------------------------------------------- // void CTestAppConsole::MccMediaPaused( TUint32 aSessionID, TUint32 aLinkId, TUint32 aStreamID, TUint32 aSinkSourceId ) { RDebug::Print( _L( "CALLBACK: Stream Paused: sess %u, link %u, stream %u, sinksource %u" ), aSessionID, aLinkId, aStreamID, aSinkSourceId ); iConsole->Printf( _L( "\nCALLBACK: Stream Paused: sess %u, link %u, stream %u, sinksource %u\n" ), aSessionID, aLinkId, aStreamID, aSinkSourceId ); } // --------------------------------------------------------------------------- // CTestAppConsole::SMccMediaResumed // // --------------------------------------------------------------------------- // void CTestAppConsole::MccMediaResumed( TUint32 aSessionID, TUint32 aLinkId, TUint32 aStreamID, TUint32 aSinkSourceId ) { RDebug::Print( _L( "CALLBACK: Stream Resumed: sess %u, link %u, stream %u, sinksource %u" ), aSessionID, aLinkId, aStreamID, aSinkSourceId ); iConsole->Printf( _L( "\nCALLBACK: Stream Resumed: sess %u, link %u, stream %u, sinksource %u\n" ), aSessionID, aLinkId, aStreamID, aSinkSourceId ); } // --------------------------------------------------------------------------- // CTestAppConsole::MccMediaPrepared // // --------------------------------------------------------------------------- // void CTestAppConsole::MccMediaPrepared( TUint32 aSessionID, TUint32 aLinkId, TUint32 aStreamID, TUint32 aSinkSourceId ) { RDebug::Print( _L( "CALLBACK: Stream Prepared: sess %u, link %u, stream %u, sinksource %u" ), aSessionID, aLinkId, aStreamID, aSinkSourceId ); iConsole->Printf( _L( "\nCALLBACK: Stream Prepared: sess %u, link %u, stream %u, sinksource %u" ), aSessionID, aLinkId, aStreamID, aSinkSourceId ); } // --------------------------------------------------------------------------- // CTestAppConsole::MccMediaInactive // // --------------------------------------------------------------------------- // void CTestAppConsole::MccMediaInactive( TUint32 aSessionID, TUint32 aLinkId, TUint32 aStreamID, TUint32 aSinkSourceId ) { RDebug::Print( _L( "CALLBACK: Stream Inactive: sess %u, link %u, stream %u, sinksource %u" ), aSessionID, aLinkId, aStreamID, aSinkSourceId ); iConsole->Printf( _L( "\nCALLBACK: Stream Inactive: sess %u, link %u, stream %u, sinksource %u\n" ), aSessionID, aLinkId, aStreamID, aSinkSourceId ); iInactivityTimerActive = EFalse; } // --------------------------------------------------------------------------- // CTestAppConsole::MccMediaActive // // --------------------------------------------------------------------------- // void CTestAppConsole::MccMediaActive( TUint32 aSessionID, TUint32 aLinkId, TUint32 aStreamID, TUint32 aSinkSourceId ) { RDebug::Print( _L( "CALLBACK: Stream active: sess %u, link %u, stream %u, sinksource %u" ), aSessionID, aLinkId, aStreamID, aSinkSourceId ); iConsole->Printf( _L( "\nCALLBACK: Stream active: sess %u, link %u, stream %u, sinksource %u\n" ), aSessionID, aLinkId, aStreamID, aSinkSourceId ); } // --------------------------------------------------------------------------- // CTestAppConsole::MccEventReceived // // --------------------------------------------------------------------------- // void CTestAppConsole::MccEventReceived( const TMccEvent& aEvent ) { if ( aEvent.iEventCategory == KMccEventCategoryDtmf ) { TMccDtmfEventDataPackage package; package.Copy( aEvent.iEventData ); const TMccDtmfEventData& event = package(); switch ( event.iDtmfEventType ) { case KMccDtmfManualStart: DisplayMsg( _L( "Manual start event" ) ); break; case KMccDtmfManualStop: DisplayMsg( _L( "Manual stop event" ) ); break; case KMccDtmfManualAbort: DisplayMsg( _L( "Manual abort event" ) ); break; case KMccDtmfSequenceStart: DisplayMsg( _L( "Seq start event" ) ); break; case KMccDtmfSequenceStop: DisplayMsg( _L( "Seq stop event" ) ); break; case KMccDtmfSequenceAbort: DisplayMsg( _L( "Seq abort event" ) ); break; case KMccDtmfStopInDtmfString: DisplayMsg( _L( "Stop in string" ) ); break; } } else if ( aEvent.iEventCategory == KMccEventCategoryRtcp ) { TMccRtcpEventDataPackage package; package.Copy( aEvent.iEventData ); const TMccRtcpEventData& event = package(); switch ( event.iRtcpPacketType ) { case KRtcpSdesPacket: RDebug::Print( _L( "CTestAppConsole::MediaSignalReceived RTCP SDES" ) ); if ( !iSdesReported ) { iConsole->Printf( _L( "MediaSignalReceived RTCP SDES" ) ); iSdesReported = ETrue; } break; case KRtcpByePacket: { RDebug::Print( _L( "CTestAppConsole::MediaSignalReceived RTCP BYE" ) ); iConsole->Printf( _L( "MediaSignalReceived RTCP BYE" ) ); } break; case KRtcpAppPacket: { RDebug::Print( _L( "CTestAppConsole::MediaSignalReceived RTCP APP" ) ); iConsole->Printf( _L( "MediaSignalReceived RTCP APP" ) ); TPckgBuf<TRtcpApp> appPackage; appPackage.Copy( event.iRtcpPacketData ); TRtcpApp app = appPackage(); } break; case KRtcpSrPacket: RDebug::Print( _L( "CTestAppConsole::MediaSignalReceived RTCP SR" ) ); if ( !iSrReported ) { iConsole->Printf( _L( "MediaSignalReceived RTCP SR" ) ); iSrReported = ETrue; } break; case KRtcpRrPacket: RDebug::Print( _L( "CTestAppConsole::MediaSignalReceived RTCP RR" ) ); if ( !iRrReported ) { iConsole->Printf( _L( "MediaSignalReceived RTCP RR" ) ); iRrReported = ETrue; } break; case KRtcpPacketUndefined: { RDebug::Print( _L( "CTestAppConsole::MediaSignalReceived Non-RTCP:" ) ); iConsole->Printf( _L( "MediaSignalReceived Data" ) ); // Convert to 16-bit text and print HBufC* undefBuf = HBufC::NewLC( event.iRtcpPacketData.Length() ); undefBuf->Des().Copy( event.iRtcpPacketData ); RDebug::Print( _L( "%s" ), undefBuf->Des() ); CleanupStack::PopAndDestroy( undefBuf ); } break; default: RDebug::Print( _L( "CTestAppConsole::MediaSignalReceived unknown" ) ); break; } } } // --------------------------------------------------------------------------- // CTestAppConsole::MccCtrlError // // --------------------------------------------------------------------------- // void CTestAppConsole::MccCtrlError( TInt aError ) { iConsole->Printf( _L( "Mcc error: %d\n" ), aError ); RDebug::Print( _L( "Mcc Error: %d" ), aError ); } // --------------------------------------------------------------------------- // CTestAppConsole::MccCtrlError // // --------------------------------------------------------------------------- // void CTestAppConsole::MccCtrlError( TInt aError, TUint32 aSessionId, TUint32 aLinkId, TUint32 aStreamId, TUint32 aSinkSourceId ) { iConsole->Printf( _L( "Mcc error: %d Session: %u, link %u, stream %u, sinksource %u\n" ), aError, aSessionId, aLinkId, aStreamId, aSinkSourceId ); RDebug::Print( _L( "Mcc Error: %d Session: %u, link %u, stream %u, sinksource %u" ), aError, aSessionId, aLinkId, aStreamId, aSinkSourceId ); } // ----------------------------------------------------------------------------- // CTestAppConsole::GetIntegerFromConsole // Reads one integer from console to the parameter. // ----------------------------------------------------------------------------- // TInt CTestAppConsole::GetIntegerFromConsole( TInt& aVal ) { TBuf<20> line; GetStringFromConsole( line ); TLex lex( line ); TInt err = lex.Val( aVal ); return err; } // ----------------------------------------------------------------------------- // CTestAppConsole::GetIntegerFromConsole // Reads one integer from console to the parameter. // ----------------------------------------------------------------------------- // TInt CTestAppConsole::GetIntegerFromConsole( TUint& aVal ) { TBuf<20> line; GetStringFromConsole( line ); TLex lex( line ); TInt err = lex.Val( aVal ); return err; } // --------------------------------------------------------------------------- // CTestAppConsole::ProcessDTMFInput // // --------------------------------------------------------------------------- // void CTestAppConsole::ProcessDTMFInput() { TInt choice; TInt err( KErrNone ); GetIntegerFromConsole( choice ); TMccEvent event; event.iSessionId = iDTMFSessionID; event.iStreamId = iDTMFStreamID; TMccDtmfEventData eventData; switch ( choice ) { case 1: TUint input; DisplayMsg( _L( "Digit to send?" ) ); GetIntegerFromConsole( input ); eventData.iDtmfEventType = EMccDtmfSigStartTone; eventData.iDtmfString.Append( TChar( input ) ); event.iEventData.Copy( TMccDtmfEventDataPackage( eventData ) ); TRAP( err, iMccInterface->SendMediaSignalL( event ) ); if ( err == KErrNone ) { DisplayMsg( _L( "Sending started" ) ); } else { iConsole->Printf( _L( "Could not send, err %d" ), err ); } break; case 2: eventData.iDtmfEventType = EMccDtmfSigStopTone; event.iEventData.Copy( TMccDtmfEventDataPackage( eventData ) ); TRAP( err, iMccInterface->SendMediaSignalL( event ) ); if ( err == KErrNone ) { DisplayMsg( _L( "Sending stopped" ) ); } else { iConsole->Printf( _L( "Could not stop, err %d" ), err ); } break; case 3: DisplayMsg( _L( "String to send?" ) ); TBuf<KMccMaxDtmfStringLength> dtmfString; GetStringFromConsole( dtmfString ); eventData.iDtmfString.Copy( dtmfString ); eventData.iDtmfEventType = EMccDtmfSigSendString; event.iEventData.Copy( TMccDtmfEventDataPackage( eventData ) ); TRAP( err, iMccInterface->SendMediaSignalL( event ) ); if ( err == KErrNone ) { DisplayMsg( _L( "Sending started" ) ); } else { iConsole->Printf( _L( "Could not start, err %d" ), err ); } break; case 4: eventData.iDtmfEventType = EMccDtmfSigContinueSending; eventData.iContinue = ETrue; event.iEventData.Copy( TMccDtmfEventDataPackage( eventData ) ); TRAP( err, iMccInterface->SendMediaSignalL( event ) ); if ( err == KErrNone ) { DisplayMsg( _L( "Sending continues" ) ); } else { iConsole->Printf( _L( "Could not continue, err %d" ), err ); } break; case 9: iCurMenu = EMainMenu; DisplayConsoleMenu( KTxtMainInstructions ); break; default: _LIT( KTxtWrongOption, "Wrong Option!" ); DisplayMsg( KTxtWrongOption ); break; } // Ready to get next input option. DoRead(); } // ----------------------------------------------------------------------------- // CTestAppConsole::ProcessCodecInput // // ----------------------------------------------------------------------------- // void CTestAppConsole::ProcessCodecInput() { TInt choice; GetIntegerFromConsole( choice ); switch ( choice ) { case 1: RunTestDisplaySupportedCodecs(); break; case 2: ChangeCodec(); break; case 3: RunSetCodecSettings(); break; case 4: ToggleVAD(); break; case 5: SetCodec(); break; case 6: RunSetFmtpAttr(); break; case 9: iCurMenu = EMainMenu; DisplayConsoleMenu( KTxtMainInstructions ); break; default: _LIT( KTxtWrongOption, "Wrong Option!" ); DisplayMsg( KTxtWrongOption ); break; } // Ready to get next input option. DoRead(); }
7f5d74bf828426c178f1985ab08455ba8979d22d
e21c2723414b08cfda4b96140f0a7f837af8d2d2
/Code(大一)/vjudge/HEU-Training 10.8/E-GCDandLCM.cpp
f905ee48913d7be8e2a8d7e8efc98c8e33cf5889
[]
no_license
liarchgh/MyCode
e060da5489facf36523c5e58a8dbf1e4fecdc01e
2f0ba2759caa5f732b6edb023af6fbc13e8c0916
refs/heads/master
2021-10-08T07:08:28.604123
2021-09-26T17:55:09
2021-09-26T17:55:09
73,447,793
0
0
null
null
null
null
UTF-8
C++
false
false
2,890
cpp
//训练时思路有了偏差 其实当初已经接近了 然而 就是那一点点啊 第一遍写了之后WA了 不知道为什么 瞎调了一会儿过了 应该不是大问题 #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <fstream> #include <map> #include <cmath> using namespace std; int su[10000] = {2}, num; void sol(int g, int l) { map<int, int>ans; ans.clear(); if (l % g) { printf("0\n"); return; } int m = l / g; int ma = sqrt(m); for (int i = 0; su[i] <= ma;) { if (m % su[i]) { ++i; } else { m /= su[i]; ++ans[su[i]]; } } if(m > 1){ ans[m] = 1; } if(ans.empty()){ printf("1\n"); return; } int zongshu = 1; for (map<int, int>::iterator it = ans.begin(); it != ans.end(); ++it) { zongshu *= 6 * it->second; // printf("%d\n", zongshu); } printf("%d\n", zongshu); } void da() { num = 1; for (int i = 2; i < 100000; ++i) { int p = 1; for (int j = 0; j < num; ++j) { if (!(i % su[j])) {p = 0; break;} } if (p) { su[num++] = i; } } // printf("%d\n",num); } int main() { // #ifndef ONLINE_JDUGE // // freopen("D:\\in.txt", "r", stdin); // // freopen("D:\\out.txt", "w", stdout); // freopen("/home/ls/Downloads/Code/in.txt", "r", stdin); // freopen("/home/ls/Downloads/Code/out.txt", "w", stdout); // #endif da(); int t, g, l; scanf("%d", &t); while (t--) { scanf("%d%d", &g, &l); sol(g, l); } return 0; } // #include<iostream> // #include<cstring> // #include<string> // #include<algorithm> // using namespace std; // const int maxn=1e7+5; // bool vis[maxn]; // int prime[maxn/10],factor[maxn],len=0; // void is_prime()//素数打表 // { // for(int i=2;i<maxn;i++) // { // if(!vis[i]) // { // prime[len++]=i; // for(int j=i+i;j<maxn;j+=i) // { // vis[j]=1; // } // } // } // } // void getprimefactor(int nn)//得到素数幂指数 // { // int cas=0; // for(int i=0;i<len&&prime[i]*prime[i]<=nn;i++) // { // while(nn%prime[i]==0) // { // factor[cas]++; // nn/=prime[i]; // } // if(factor[cas]) // cas++; // } // if(nn>1) // factor[cas]=1; // } // int main() // { // is_prime(); // int t,g,l; // scanf("%d",&t); // while(t--) // { // memset(factor,0,sizeof(factor)); // int sum=1; // scanf("%d %d",&g,&l); // if(l%g) // { // printf("0\n"); // continue; // } // int k=l/g; // getprimefactor(k); // for(int i=0;;i++) // { // if(!factor[i]) // break; // sum*=factor[i]; // sum*=6; // } // printf("%d\n",sum); // } // return 0; // }
1187f794fc8c215ac7c561a6efeaf2dfaf873e5c
4700115f94bc2a8c83ca5349053e9684fc471c29
/tests/UnitTest/src/Geometry/Matrix.cpp
e43aca629b030a0d63270269f5dde813107d41f6
[ "Apache-2.0" ]
permissive
wangscript/RadonFramework
5ff29ad5f9a623cd3f4a2cb60ca8ae8fe669647c
7066779c1b88089d9ac220d21c1128c2cc2163a9
refs/heads/master
2020-12-28T23:45:46.151802
2015-07-03T18:42:29
2015-07-03T18:42:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
34,422
cpp
#include <RadonFramework/precompiled.hpp> #include <RadonFramework/Diagnostics/Debugging/UnitTest/TestSuite.hpp> #include <RadonFramework/Diagnostics/Debugging/UnitTest/UnitTest.hpp> #include <RadonFramework/Core/Pattern/Delegate.hpp> #include <RadonFramework/Math/Geometry/Matrix.hpp> using namespace RadonFramework::Math::Geometry; using namespace RadonFramework::Core::Types; using namespace RadonFramework::Diagnostics::Debugging::UnitTest; class GeometryMatrixTest:public TestSuite { public: GeometryMatrixTest() :TestSuite("RadonFramework::Math::Geometry::Matrix-Test") { AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fDefaultConstructor), "GeometryMatrixTest::Matrix2fDefaultConstructor", "DefaultConstructor2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fDefaultConstructor), "GeometryMatrixTest::Matrix3fDefaultConstructor", "DefaultConstructor3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fDefaultConstructor), "GeometryMatrixTest::Matrix4fDefaultConstructor", "DefaultConstructor4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fCopyConstructor), "GeometryMatrixTest::Matrix2fCopyConstructor", "CopyConstructor2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fCopyConstructor), "GeometryMatrixTest::Matrix3fCopyConstructor", "CopyConstructor3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fCopyConstructor), "GeometryMatrixTest::Matrix4fCopyConstructor", "CopyConstructor4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fAssignOperator), "GeometryMatrixTest::Matrix2fAssignOperator", "AssignOperator2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fAssignOperator), "GeometryMatrixTest::Matrix3fAssignOperator", "AssignOperator3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fAssignOperator), "GeometryMatrixTest::Matrix4fAssignOperator", "AssignOperator4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fGetRow), "GeometryMatrixTest::Matrix2fGetRow", "GetRow2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fGetRow), "GeometryMatrixTest::Matrix3fGetRow", "GetRow3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fGetRow), "GeometryMatrixTest::Matrix4fGetRow", "GetRow4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fGetColumn), "GeometryMatrixTest::Matrix2fGetColumn", "GetColumn2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fGetColumn), "GeometryMatrixTest::Matrix3fGetColumn", "GetColumn3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fGetColumn), "GeometryMatrixTest::Matrix4fGetColumn", "GetColumn4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fSetColumn), "GeometryMatrixTest::Matrix2fSetColumn", "SetColumn2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fSetColumn), "GeometryMatrixTest::Matrix3fSetColumn", "SetColumn3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fSetColumn), "GeometryMatrixTest::Matrix4fSetColumn", "SetColumn4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fTranspose), "GeometryMatrixTest::Matrix2fTranspose", "Transpose2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fTranspose), "GeometryMatrixTest::Matrix3fTranspose", "Transpose3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fTranspose), "GeometryMatrixTest::Matrix4fTranspose", "Transpose4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fScale), "GeometryMatrixTest::Matrix2fScale", "Scale2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fScale), "GeometryMatrixTest::Matrix3fScale", "Scale3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fScale), "GeometryMatrixTest::Matrix4fScale", "Scale4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fFunctionOperator), "GeometryMatrixTest::Matrix2fFunctionOperator", "FunctionOperator2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fFunctionOperator), "GeometryMatrixTest::Matrix3fFunctionOperator", "FunctionOperator3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fFunctionOperator), "GeometryMatrixTest::Matrix4fFunctionOperator", "FunctionOperator4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fArrayOperator), "GeometryMatrixTest::Matrix2fArrayOperator", "ArrayOperator2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fArrayOperator), "GeometryMatrixTest::Matrix3fArrayOperator", "ArrayOperator3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fArrayOperator), "GeometryMatrixTest::Matrix4fArrayOperator", "ArrayOperator4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fMultiplicationOperator), "GeometryMatrixTest::Matrix2fMultiplicationOperator", "MultiplicationOperator2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fMultiplicationOperator), "GeometryMatrixTest::Matrix3fMultiplicationOperator", "MultiplicationOperator3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fMultiplicationOperator), "GeometryMatrixTest::Matrix4fMultiplicationOperator", "MultiplicationOperator4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fDivisionOperator), "GeometryMatrixTest::Matrix2fDivisionOperator", "DivisionOperator2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fDivisionOperator), "GeometryMatrixTest::Matrix3fDivisionOperator", "DivisionOperator3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fDivisionOperator), "GeometryMatrixTest::Matrix4fDivisionOperator", "DivisionOperator4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fMultiplicationOperatorVector), "GeometryMatrixTest::Matrix2fMultiplicationOperatorVector", "MultiplicationOperatorVector2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fMultiplicationOperatorVector), "GeometryMatrixTest::Matrix3fMultiplicationOperatorVector", "MultiplicationOperatorVector3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fMultiplicationOperatorVector), "GeometryMatrixTest::Matrix4fMultiplicationOperatorVector", "MultiplicationOperatorVector4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fMultiplicationAssignOperator), "GeometryMatrixTest::Matrix2fMultiplicationAssignOperator", "MultiplicationAssignOperator2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fMultiplicationAssignOperator), "GeometryMatrixTest::Matrix3fMultiplicationAssignOperator", "MultiplicationAssignOperator3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fMultiplicationAssignOperator), "GeometryMatrixTest::Matrix4fMultiplicationAssignOperator", "MultiplicationAssignOperator4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fDivisionAssignOperator), "GeometryMatrixTest::Matrix2fDivisionAssignOperator", "DivisionAssignOperator2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fDivisionAssignOperator), "GeometryMatrixTest::Matrix3fDivisionAssignOperator", "DivisionAssignOperator3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fDivisionAssignOperator), "GeometryMatrixTest::Matrix4fDivisionAssignOperator", "DivisionAssignOperator4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fScale), "GeometryMatrixTest::Matrix2fScale", "Scale2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fScale), "GeometryMatrixTest::Matrix3fScale", "Scale3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fScale), "&GeometryMatrixTest::Matrix4fScale", "Scale4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fDeterminants), "GeometryMatrixTest::Matrix2fDeterminants", "Determinants2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fDeterminants), "GeometryMatrixTest::Matrix3fDeterminants", "Determinants3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fDeterminants), "GeometryMatrixTest::Matrix4fDeterminants", "Determinants4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fInverse), "GeometryMatrixTest::Matrix2fInverse", "Inverse2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fInverse), "GeometryMatrixTest::Matrix3fInverse", "Inverse3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fInverse), "GeometryMatrixTest::Matrix4fInverse", "Inverse4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fLoadIdentity), "GeometryMatrixTest::Matrix2fLoadIdentity", "LoadIdentity2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fLoadIdentity), "GeometryMatrixTest::Matrix3fLoadIdentity", "LoadIdentity3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fLoadIdentity), "GeometryMatrixTest::Matrix4fLoadIdentity", "LoadIdentity4f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix2fLoadZero), "GeometryMatrixTest::Matrix2fLoadZero", "LoadZero2f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix3fLoadZero), "GeometryMatrixTest::Matrix3fLoadZero", "LoadZero3f"); AddTest(MakeDelegate(this,&GeometryMatrixTest::Matrix4fLoadZero), "GeometryMatrixTest::Matrix4fLoadZero", "LoadZero4f"); } Bool Matrix2fDefaultConstructor() { Matrix2f m2; return (m2.Value[0]==1.0 && m2.Value[2]==0.0 && m2.Value[1]==0.0 && m2.Value[3]==1.0); } Bool Matrix3fDefaultConstructor() { Matrix3f m3; return (m3.Value[0]==1.0 && m3.Value[3]==0.0 && m3.Value[6]==0.0 && m3.Value[1]==0.0 && m3.Value[4]==1.0 && m3.Value[7]==0.0 && m3.Value[2]==0.0 && m3.Value[5]==0.0 && m3.Value[8]==1.0); } Bool Matrix4fDefaultConstructor() { Mat4f m4; return (m4.Value[0]==1.0 && m4.Value[4]==0.0 && m4.Value[8]==0.0 && m4.Value[12]==0.0 && m4.Value[1]==0.0 && m4.Value[5]==1.0 && m4.Value[9]==0.0 && m4.Value[13]==0.0 && m4.Value[2]==0.0 && m4.Value[6]==0.0 && m4.Value[10]==1.0 && m4.Value[14]==0.0 && m4.Value[3]==0.0 && m4.Value[7]==0.0 && m4.Value[11]==0.0 && m4.Value[15]==1.0); } Bool Matrix2fCopyConstructor() { Matrix2f m2b; m2b.Value[0]=2.0; m2b.Value[2]=3.0; m2b.Value[1]=1.0; m2b.Value[3]=2.0; Matrix2f m2(m2b); return (m2.Value[0]==2.0 && m2.Value[2]==3.0 && m2.Value[1]==1.0 && m2.Value[3]==2.0); } Bool Matrix3fCopyConstructor() { Matrix3f m3b; m3b.Value[0]=2.0; m3b.Value[3]=3.0; m3b.Value[6]=1.0; m3b.Value[1]=1.0; m3b.Value[4]=2.0; m3b.Value[7]=3.0; m3b.Value[2]=3.0; m3b.Value[5]=1.0; m3b.Value[8]=2.0; Matrix3f m3(m3b); return (m3.Value[0]==2.0 && m3.Value[3]==3.0 && m3.Value[6]==1.0 && m3.Value[1]==1.0 && m3.Value[4]==2.0 && m3.Value[7]==3.0 && m3.Value[2]==3.0 && m3.Value[5]==1.0 && m3.Value[8]==2.0); } Bool Matrix4fCopyConstructor() { Mat4f m4b; m4b.Value[0]=2.0; m4b.Value[4]=3.0; m4b.Value[ 8]=1.0; m4b.Value[12]=4.0; m4b.Value[1]=1.0; m4b.Value[5]=2.0; m4b.Value[ 9]=3.0; m4b.Value[13]=3.0; m4b.Value[2]=3.0; m4b.Value[6]=4.0; m4b.Value[10]=2.0; m4b.Value[14]=2.0; m4b.Value[3]=4.0; m4b.Value[7]=1.0; m4b.Value[11]=4.0; m4b.Value[15]=1.0; Mat4f m4(m4b); return (m4.Value[0]==2.0 && m4.Value[4]==3.0 && m4.Value[ 8]==1.0 && m4.Value[12]==4.0 && m4.Value[1]==1.0 && m4.Value[5]==2.0 && m4.Value[ 9]==3.0 && m4.Value[13]==3.0 && m4.Value[2]==3.0 && m4.Value[6]==4.0 && m4.Value[10]==2.0 && m4.Value[14]==2.0 && m4.Value[3]==4.0 && m4.Value[7]==1.0 && m4.Value[11]==4.0 && m4.Value[15]==1.0); } Bool Matrix2fAssignOperator() { Matrix2f m2,m2b; m2b.Value[0]=2.0; m2b.Value[2]=3.0; m2b.Value[1]=1.0; m2b.Value[3]=2.0; m2=m2b; return (m2.Value[0]==2.0 && m2.Value[2]==3.0 && m2.Value[1]==1.0 && m2.Value[3]==2.0); } Bool Matrix3fAssignOperator() { Matrix3f m3,m3b; m3b.Value[0]=2.0; m3b.Value[3]=3.0; m3b.Value[6]=1.0; m3b.Value[1]=1.0; m3b.Value[4]=2.0; m3b.Value[7]=3.0; m3b.Value[2]=3.0; m3b.Value[5]=1.0; m3b.Value[8]=2.0; m3=m3b; return (m3.Value[0]==2.0 && m3.Value[3]==3.0 && m3.Value[6]==1.0 && m3.Value[1]==1.0 && m3.Value[4]==2.0 && m3.Value[7]==3.0 && m3.Value[2]==3.0 && m3.Value[5]==1.0 && m3.Value[8]==2.0); } Bool Matrix4fAssignOperator() { Mat4f m4, m4b; m4b.Value[0]=2.0; m4b.Value[4]=3.0; m4b.Value[ 8]=1.0; m4b.Value[12]=4.0; m4b.Value[1]=1.0; m4b.Value[5]=2.0; m4b.Value[ 9]=3.0; m4b.Value[13]=3.0; m4b.Value[2]=3.0; m4b.Value[6]=4.0; m4b.Value[10]=2.0; m4b.Value[14]=2.0; m4b.Value[3]=4.0; m4b.Value[7]=1.0; m4b.Value[11]=4.0; m4b.Value[15]=1.0; m4=m4b; RF_Type::Bool result = (m4.Value[0] == 2.0 && m4.Value[4] == 3.0 && m4.Value[8] == 1.0 && m4.Value[12] == 4.0 && m4.Value[1] == 1.0 && m4.Value[5] == 2.0 && m4.Value[9] == 3.0 && m4.Value[13] == 3.0 && m4.Value[2] == 3.0 && m4.Value[6] == 4.0 && m4.Value[10] == 2.0 && m4.Value[14] == 2.0 && m4.Value[3] == 4.0 && m4.Value[7] == 1.0 && m4.Value[11] == 4.0 && m4.Value[15] == 1.0); return result; } Bool Matrix2fGetRow() { Matrix2f m2; m2.Value[1]=2.0; m2.Value[2]=2.0; return (m2.GetRow(0)[0]==1.0 && m2.GetRow(0)[1]==2.0) && (m2.GetRow(1)[0]==2.0 && m2.GetRow(1)[1]==1.0); } Bool Matrix3fGetRow() { Matrix3f m3; m3.Value[3]=2.0; m3.Value[1]=2.0; m3.Value[5]=2.0; return (m3.GetRow(0)[0]==1.0 && m3.GetRow(0)[1]==2.0 && m3.GetRow(0)[2]==0.0) && (m3.GetRow(1)[0]==2.0 && m3.GetRow(1)[1]==1.0 && m3.GetRow(1)[2]==0.0) && (m3.GetRow(2)[0]==0.0 && m3.GetRow(2)[1]==2.0 && m3.GetRow(2)[2]==1.0); } Bool Matrix4fGetRow() { Mat4f m4; m4.Value[11]=2.0; m4.Value[1]=2.0; m4.Value[6]=2.0; m4.Value[12]=2.0; return (m4.GetRow(0)[0]==1.0 && m4.GetRow(0)[1]==0.0 && m4.GetRow(0)[2]==0.0 && m4.GetRow(0)[3]==2.0) && (m4.GetRow(1)[0]==2.0 && m4.GetRow(1)[1]==1.0 && m4.GetRow(1)[2]==0.0 && m4.GetRow(1)[3]==0.0) && (m4.GetRow(2)[0]==0.0 && m4.GetRow(2)[1]==2.0 && m4.GetRow(2)[2]==1.0 && m4.GetRow(2)[3]==0.0) && (m4.GetRow(3)[0]==0.0 && m4.GetRow(3)[1]==0.0 && m4.GetRow(3)[2]==2.0 && m4.GetRow(3)[3]==1.0); } Bool Matrix2fGetColumn() { Matrix2f m2; m2.Value[1]=2.0; m2.Value[2]=2.0; return (m2.GetColumn(0)[0]==1.0 && m2.GetColumn(0)[1]==2.0) && (m2.GetColumn(1)[0]==2.0 && m2.GetColumn(1)[1]==1.0); } Bool Matrix3fGetColumn() { Matrix3f m3; m3.Value[3]=2.0; m3.Value[1]=2.0; m3.Value[5]=2.0; return (m3.GetColumn(0)[0]==1.0 && m3.GetColumn(0)[1]==2.0 && m3.GetColumn(0)[2]==0.0) && (m3.GetColumn(1)[0]==2.0 && m3.GetColumn(1)[1]==1.0 && m3.GetColumn(1)[2]==2.0) && (m3.GetColumn(2)[0]==0.0 && m3.GetColumn(2)[1]==0.0 && m3.GetColumn(2)[2]==1.0); } Bool Matrix4fGetColumn() { Mat4f m4; m4.Value[11]=2.0; m4.Value[1]=2.0; m4.Value[6]=2.0; m4.Value[12]=2.0; return (m4.GetColumn(0)[0]==1.0 && m4.GetColumn(0)[1]==2.0 && m4.GetColumn(0)[2]==0.0 && m4.GetColumn(0)[3]==0.0) && (m4.GetColumn(1)[0]==0.0 && m4.GetColumn(1)[1]==1.0 && m4.GetColumn(1)[2]==2.0 && m4.GetColumn(1)[3]==0.0) && (m4.GetColumn(2)[0]==0.0 && m4.GetColumn(2)[1]==0.0 && m4.GetColumn(2)[2]==1.0 && m4.GetColumn(2)[3]==2.0) && (m4.GetColumn(3)[0]==2.0 && m4.GetColumn(3)[1]==0.0 && m4.GetColumn(3)[2]==0.0 && m4.GetColumn(3)[3]==1.0); } Bool Matrix2fSetColumn() { Matrix2f m2; m2.SetColumn(0,Vec2f(2.0,1.0)); m2.SetColumn(1,Vec2f(3.0,2.0)); return (m2.Value[0]==2.0 && m2.Value[2]==3.0 && m2.Value[1]==1.0 && m2.Value[3]==2.0); } Bool Matrix3fSetColumn() { Matrix3f m3; m3.SetColumn(0,Vec3f(2.0,1.0,3.0)); m3.SetColumn(1,Vec3f(3.0,2.0,1.0)); m3.SetColumn(2,Vec3f(1.0,3.0,2.0)); return (m3.Value[0]==2.0 && m3.Value[3]==3.0 && m3.Value[6]==1.0 && m3.Value[1]==1.0 && m3.Value[4]==2.0 && m3.Value[7]==3.0 && m3.Value[2]==3.0 && m3.Value[5]==1.0 && m3.Value[8]==2.0); } Bool Matrix4fSetColumn() { Mat4f m4; m4.SetColumn(0,Vec4f(2.0,1.0,3.0,4.0)); m4.SetColumn(1,Vec4f(3.0,2.0,4.0,1.0)); m4.SetColumn(2,Vec4f(1.0,3.0,2.0,4.0)); m4.SetColumn(3,Vec4f(4.0,3.0,2.0,1.0)); return (m4.Value[0]==2.0 && m4.Value[4]==3.0 && m4.Value[ 8]==1.0 && m4.Value[12]==4.0 && m4.Value[1]==1.0 && m4.Value[5]==2.0 && m4.Value[9]==3.0 && m4.Value[13]==3.0 && m4.Value[2]==3.0 && m4.Value[6]==4.0 && m4.Value[10]==2.0 && m4.Value[14]==2.0 && m4.Value[3]==4.0 && m4.Value[7]==1.0 && m4.Value[11]==4.0 && m4.Value[15]==1.0); } Bool Matrix2fTranspose() { Matrix2f m2,m2b; m2.SetColumn(0,Vec2f(2.0,1.0)); m2.SetColumn(1,Vec2f(3.0,2.0)); Bool ret; ret=(m2.Value[0]==2.0 && m2.Value[2]==3.0 && m2.Value[1]==1.0 && m2.Value[3]==2.0); m2b=m2.Transpose(); return (m2b.Value[0]==2.0 && m2b.Value[2]==1.0 && m2b.Value[1]==3.0 && m2b.Value[3]==2.0) && ret; } Bool Matrix3fTranspose() { Matrix3f m3,m3b; m3.SetColumn(0,Vec3f(2.0,1.0,3.0)); m3.SetColumn(1,Vec3f(3.0,2.0,1.0)); m3.SetColumn(2,Vec3f(1.0,3.0,2.0)); Bool ret; ret=(m3.Value[0]==2.0 && m3.Value[3]==3.0 && m3.Value[6]==1.0 && m3.Value[1]==1.0 && m3.Value[4]==2.0 && m3.Value[7]==3.0 && m3.Value[2]==3.0 && m3.Value[5]==1.0 && m3.Value[8]==2.0); m3b=m3.Transpose(); return (m3b.Value[0]==2.0 && m3b.Value[3]==1.0 && m3b.Value[6]==3.0 && m3b.Value[1]==3.0 && m3b.Value[4]==2.0 && m3b.Value[7]==1.0 && m3b.Value[2]==1.0 && m3b.Value[5]==3.0 && m3b.Value[8]==2.0) && ret; } Bool Matrix4fTranspose() { Mat4f m4, m4b; m4.SetColumn(0,Vec4f(2.0,1.0,3.0,4.0)); m4.SetColumn(1,Vec4f(3.0,2.0,4.0,1.0)); m4.SetColumn(2,Vec4f(1.0,3.0,2.0,4.0)); m4.SetColumn(3,Vec4f(4.0,3.0,2.0,1.0)); Bool ret; ret=(m4.Value[0]==2.0 && m4.Value[4]==3.0 && m4.Value[ 8]==1.0 && m4.Value[12]==4.0 && m4.Value[1]==1.0 && m4.Value[5]==2.0 && m4.Value[ 9]==3.0 && m4.Value[13]==3.0 && m4.Value[2]==3.0 && m4.Value[6]==4.0 && m4.Value[10]==2.0 && m4.Value[14]==2.0 && m4.Value[3]==4.0 && m4.Value[7]==1.0 && m4.Value[11]==4.0 && m4.Value[15]==1.0); m4b=m4.Transpose(); return (m4b.Value[0]==2.0 && m4b.Value[4]==1.0 && m4b.Value[ 8]==3.0 && m4b.Value[12]==4.0 && m4b.Value[1]==3.0 && m4b.Value[5]==2.0 && m4b.Value[ 9]==4.0 && m4b.Value[13]==1.0 && m4b.Value[2]==1.0 && m4b.Value[6]==3.0 && m4b.Value[10]==2.0 && m4b.Value[14]==4.0 && m4b.Value[3]==4.0 && m4b.Value[7]==3.0 && m4b.Value[11]==2.0 && m4b.Value[15]==1.0) && ret; } Bool Matrix2fScale() { Matrix2f m2; m2.Scale(Vec2f(2.0,1.0)); return (m2.Value[0]==2.0 && m2.Value[2]==0.0 && m2.Value[1]==0.0 && m2.Value[3]==1.0); } Bool Matrix3fScale() { Matrix3f m3; m3.Scale(Vec3f(2.0,1.0,3.0)); return (m3.Value[0]==2.0 && m3.Value[3]==0.0 && m3.Value[6]==0.0 && m3.Value[1]==0.0 && m3.Value[4]==1.0 && m3.Value[7]==0.0 && m3.Value[2]==0.0 && m3.Value[5]==0.0 && m3.Value[8]==3.0); } Bool Matrix4fScale() { Mat4f m4; m4.Scale(Vec4f(2.0,1.0,3.0,4.0)); return (m4.Value[0]==2.0 && m4.Value[4]==0.0 && m4.Value[ 8]==0.0 && m4.Value[12]==0.0 && m4.Value[1]==0.0 && m4.Value[5]==1.0 && m4.Value[ 9]==0.0 && m4.Value[13]==0.0 && m4.Value[2]==0.0 && m4.Value[6]==0.0 && m4.Value[10]==3.0 && m4.Value[14]==0.0 && m4.Value[3]==0.0 && m4.Value[7]==0.0 && m4.Value[11]==0.0 && m4.Value[15]==4.0); } Bool Matrix2fFunctionOperator() { Matrix2f m2; return (m2(0,0)==1.0 && m2(1,0)==0.0 && m2(0,1)==0.0 && m2(1,1)==1.0); } Bool Matrix3fFunctionOperator() { Matrix3f m3; return (m3(0,0)==1.0 && m3(1,0)==0.0 && m3(2,0)==0.0 && m3(0,1)==0.0 && m3(1,1)==1.0 && m3(2,1)==0.0 && m3(0,2)==0.0 && m3(1,2)==0.0 && m3(2,2)==1.0); } Bool Matrix4fFunctionOperator() { Mat4f m4; return (m4(0,0)==1.0 && m4(1,0)==0.0 && m4(2,0)==0.0 && m4(3,0)==0.0 && m4(0,1)==0.0 && m4(1,1)==1.0 && m4(2,1)==0.0 && m4(3,1)==0.0 && m4(0,2)==0.0 && m4(1,2)==0.0 && m4(2,2)==1.0 && m4(3,2)==0.0 && m4(0,3)==0.0 && m4(1,3)==0.0 && m4(2,3)==0.0 && m4(3,3)==1.0); } Bool Matrix2fArrayOperator() { Matrix2f m2; return (m2[0]==1.0 && m2[2]==0.0 && m2[1]==0.0 && m2[3]==1.0); } Bool Matrix3fArrayOperator() { Matrix3f m3; return (m3[0]==1.0 && m3[3]==0.0 && m3[6]==0.0 && m3[1]==0.0 && m3[4]==1.0 && m3[7]==0.0 && m3[2]==0.0 && m3[5]==0.0 && m3[8]==1.0); } Bool Matrix4fArrayOperator() { Mat4f m4; return (m4[0]==1.0 && m4[4]==0.0 && m4[ 8]==0.0 && m4[12]==0.0 && m4[1]==0.0 && m4[5]==1.0 && m4[ 9]==0.0 && m4[13]==0.0 && m4[2]==0.0 && m4[6]==0.0 && m4[10]==1.0 && m4[14]==0.0 && m4[3]==0.0 && m4[7]==0.0 && m4[11]==0.0 && m4[15]==1.0); } Bool Matrix2fMultiplicationOperator() { Matrix2f m2,m2b; m2.SetColumn(0,Vec2f(2.0,3.0)); m2.SetColumn(1,Vec2f(1.0,2.0)); m2b=m2; m2=m2*m2b; return (m2.Value[0]==7.0 && m2.Value[2]==4.0 && m2.Value[1]==12.0 && m2.Value[3]==7.0); } Bool Matrix3fMultiplicationOperator() { Matrix3f m3,m3b; m3.SetColumn(0,Vec3f(2.0,3.0,1.0)); m3.SetColumn(1,Vec3f(1.0,2.0,3.0)); m3.SetColumn(2,Vec3f(3.0,1.0,2.0)); m3b=m3; m3=m3*m3b; RF_Type::Bool result = (m3.Value[0] == 10.0 && m3.Value[3] == 13.0 && m3.Value[6] == 13.0 && m3.Value[1] == 13.0 && m3.Value[4] == 10.0 && m3.Value[7] == 13.0 && m3.Value[2] == 13.0 && m3.Value[5] == 13.0 && m3.Value[8] == 10.0); return result; } Bool Matrix4fMultiplicationOperator() { Mat4f m4, m4b; m4.SetColumn(0,Vec4f(2.0,3.0,1.0,4.0)); m4.SetColumn(1,Vec4f(1.0,2.0,3.0,3.0)); m4.SetColumn(2,Vec4f(3.0,4.0,2.0,2.0)); m4.SetColumn(3,Vec4f(4.0,1.0,4.0,1.0)); m4b=m4; m4=m4*m4b; return (m4.Value[0]==26.0 && m4.Value[4]==25.0 && m4.Value[ 8]==24.0 && m4.Value[12]==25.0 && m4.Value[1]==20.0 && m4.Value[5]==22.0 && m4.Value[ 9]==27.0 && m4.Value[13]==31.0 && m4.Value[2]==29.0 && m4.Value[6]==25.0 && m4.Value[10]==27.0 && m4.Value[14]==19.0 && m4.Value[3]==23.0 && m4.Value[7]==19.0 && m4.Value[11]==30.0 && m4.Value[15]==28.0); } Bool Matrix2fDivisionOperator() { Matrix2f m2; m2.SetColumn(0,Vec2f(2.0,3.0)); m2.SetColumn(1,Vec2f(1.0,2.0)); m2=m2/0.5; return (m2.Value[0]==4.0 && m2.Value[2]==2.0 && m2.Value[1]==6.0 && m2.Value[3]==4.0); } Bool Matrix3fDivisionOperator() { Matrix3f m3; m3.SetColumn(0,Vec3f(2.0,3.0,1.0)); m3.SetColumn(1,Vec3f(1.0,2.0,3.0)); m3.SetColumn(2,Vec3f(3.0,1.0,2.0)); m3=m3/0.5; return (m3.Value[0]==4.0 && m3.Value[3]==2.0 && m3.Value[6]==6.0 && m3.Value[1]==6.0 && m3.Value[4]==4.0 && m3.Value[7]==2.0 && m3.Value[2]==2.0 && m3.Value[5]==6.0 && m3.Value[8]==4.0); } Bool Matrix4fDivisionOperator() { Mat4f m4; m4.SetColumn(0,Vec4f(2.0,3.0,1.0,4.0)); m4.SetColumn(1,Vec4f(1.0,2.0,3.0,3.0)); m4.SetColumn(2,Vec4f(3.0,4.0,2.0,2.0)); m4.SetColumn(3,Vec4f(4.0,1.0,4.0,1.0)); m4=m4/0.5; return (m4.Value[0]==4.0 && m4.Value[4]==2.0 && m4.Value[8]==6.0 && m4.Value[12]==8.0 && m4.Value[1]==6.0 && m4.Value[5]==4.0 && m4.Value[9]==8.0 && m4.Value[13]==2.0 && m4.Value[2]==2.0 && m4.Value[6]==6.0 && m4.Value[10]==4.0 && m4.Value[14]==8.0 && m4.Value[3]==8.0 && m4.Value[7]==6.0 && m4.Value[11]==4.0 && m4.Value[15]==2.0); } Bool Matrix2fMultiplicationOperatorVector() { Matrix2f m2; Vec2f v; m2.SetColumn(0,Vec2f(2.0,3.0)); m2.SetColumn(1,Vec2f(1.0,2.0)); v=m2*Vec2f(0.5,0.25); return (v.Value[0]==1.25 && v.Value[1]==2.0); } Bool Matrix3fMultiplicationOperatorVector() { Matrix3f m3; Vec3f v; m3.SetColumn(0,Vec3f(2.0,3.0,1.0)); m3.SetColumn(1,Vec3f(1.0,2.0,3.0)); m3.SetColumn(2,Vec3f(3.0,1.0,2.0)); v=m3*Vec3f(0.5,0.25,0.125); return (v.Value[0]==1.625 && v.Value[1]==2.125 && v.Value[2]==1.5); } Bool Matrix4fMultiplicationOperatorVector() { Mat4f m4; Vec4f v; m4.SetColumn(0,Vec4f(2.0,3.0,1.0,4.0)); m4.SetColumn(1,Vec4f(1.0,2.0,3.0,3.0)); m4.SetColumn(2,Vec4f(3.0,4.0,2.0,2.0)); m4.SetColumn(3,Vec4f(4.0,1.0,4.0,1.0)); v=m4*Vec4f(0.5,0.25,0.125,0.0625); return (v.Value[0]==1.875 && v.Value[1]==2.5625 && v.Value[2]==1.75 && v.Value[3]==3.0625); } Bool Matrix2fMultiplicationAssignOperator() { Matrix2f m2,m2b; m2.SetColumn(0,Vec2f(2.0,3.0)); m2.SetColumn(1,Vec2f(1.0,2.0)); m2b=m2; m2*=m2b; return (m2.Value[0]==7.0 && m2.Value[2]==4.0 && m2.Value[1]==12.0 && m2.Value[3]==7.0); } Bool Matrix3fMultiplicationAssignOperator() { Matrix3f m3,m3b; m3.SetColumn(0,Vec3f(2.0,3.0,1.0)); m3.SetColumn(1,Vec3f(1.0,2.0,3.0)); m3.SetColumn(2,Vec3f(3.0,1.0,2.0)); m3b=m3; m3*=m3b; return (m3.Value[0]==10.0 && m3.Value[3]==13.0 && m3.Value[6]==13.0 && m3.Value[1]==13.0 && m3.Value[4]==10.0 && m3.Value[7]==13.0 && m3.Value[2]==13.0 && m3.Value[5]==13.0 && m3.Value[8]==10.0); } Bool Matrix4fMultiplicationAssignOperator() { Mat4f m4, m4b; m4.SetColumn(0,Vec4f(2.0,3.0,1.0,4.0)); m4.SetColumn(1,Vec4f(1.0,2.0,3.0,3.0)); m4.SetColumn(2,Vec4f(3.0,4.0,2.0,2.0)); m4.SetColumn(3,Vec4f(4.0,1.0,4.0,1.0)); m4b=m4; m4*=m4b; return (m4.Value[0]==26.0 && m4.Value[4]==25.0 && m4.Value[ 8]==24.0 && m4.Value[12]==25.0 && m4.Value[1]==20.0 && m4.Value[5]==22.0 && m4.Value[ 9]==27.0 && m4.Value[13]==31.0 && m4.Value[2]==29.0 && m4.Value[6]==25.0 && m4.Value[10]==27.0 && m4.Value[14]==19.0 && m4.Value[3]==23.0 && m4.Value[7]==19.0 && m4.Value[11]==30.0 && m4.Value[15]==28.0); } Bool Matrix2fDivisionAssignOperator() { Matrix2f m2; m2.SetColumn(0,Vec2f(2.0,3.0)); m2.SetColumn(1,Vec2f(1.0,2.0)); m2/=0.5; return (m2.Value[0]==4.0 && m2.Value[2]==2.0 && m2.Value[1]==6.0 && m2.Value[3]==4.0); } Bool Matrix3fDivisionAssignOperator() { Matrix3f m3; m3.SetColumn(0,Vec3f(2.0,3.0,1.0)); m3.SetColumn(1,Vec3f(1.0,2.0,3.0)); m3.SetColumn(2,Vec3f(3.0,1.0,2.0)); m3/=0.5; return (m3.Value[0]==4.0 && m3.Value[3]==2.0 && m3.Value[6]==6.0 && m3.Value[1]==6.0 && m3.Value[4]==4.0 && m3.Value[7]==2.0 && m3.Value[2]==2.0 && m3.Value[5]==6.0 && m3.Value[8]==4.0); } Bool Matrix4fDivisionAssignOperator() { Mat4f m4; m4.SetColumn(0,Vec4f(2.0,3.0,1.0,4.0)); m4.SetColumn(1,Vec4f(1.0,2.0,3.0,3.0)); m4.SetColumn(2,Vec4f(3.0,4.0,2.0,2.0)); m4.SetColumn(3,Vec4f(4.0,1.0,4.0,1.0)); m4/=0.5; return (m4.Value[0]==4.0 && m4.Value[4]==2.0 && m4.Value[8]==6.0 && m4.Value[12]==8.0 && m4.Value[1]==6.0 && m4.Value[5]==4.0 && m4.Value[9]==8.0 && m4.Value[13]==2.0 && m4.Value[2]==2.0 && m4.Value[6]==6.0 && m4.Value[10]==4.0 && m4.Value[14]==8.0 && m4.Value[3]==8.0 && m4.Value[7]==6.0 && m4.Value[11]==4.0 && m4.Value[15]==2.0); } Bool Matrix2fDeterminants() { Matrix2f m2; m2.SetColumn(0,Vec2f(2.0,3.0)); m2.SetColumn(1,Vec2f(1.0,2.0)); return m2.Determinants()==1.0; } Bool Matrix3fDeterminants() { Matrix3f m3; m3.SetColumn(0,Vec3f(2.0,3.0,1.0)); m3.SetColumn(1,Vec3f(1.0,2.0,3.0)); m3.SetColumn(2,Vec3f(3.0,4.0,2.0)); return m3.Determinants()==3.0; } Bool Matrix4fDeterminants() { Mat4f m4; m4.SetColumn(0,Vec4f(2.0,3.0,1.0,4.0)); m4.SetColumn(1,Vec4f(1.0,2.0,3.0,3.0)); m4.SetColumn(2,Vec4f(3.0,4.0,2.0,2.0)); m4.SetColumn(3,Vec4f(4.0,1.0,4.0,1.0)); return m4.Determinants()==90.0; } Bool Matrix2fInverse() { Matrix2f m2; m2.SetColumn(0,Vec2f(2.0,3.0)); m2.SetColumn(1,Vec2f(1.0,2.0)); Matrix2f m2inv; m2inv=m2.Inverse(); return m2*m2inv==Matrix2f(); } Bool Matrix3fInverse() { Matrix3f m3; m3.SetColumn(0,Vec3f(3.0,2.0,1.0)); m3.SetColumn(1,Vec3f(5.0,4.0,2.0)); m3.SetColumn(2,Vec3f(1.0,5.0,2.0)); Matrix3f m3inv; m3inv=m3.Inverse(); return m3*m3inv==Matrix3f(); } Bool Matrix4fInverse() { Mat4f m4; m4.SetColumn(0,Vec4f(2.0,3.0,1.0,4.0)); m4.SetColumn(1,Vec4f(1.0,2.0,3.0,3.0)); m4.SetColumn(2,Vec4f(3.0,4.0,2.0,2.0)); m4.SetColumn(3,Vec4f(4.0,1.0,4.0,1.0)); Mat4f m4inv; m4inv=m4.Inverse(); return m4*m4inv == Mat4f(); } Bool Matrix2fLoadIdentity() { Matrix2f m2; return (m2.Value[0]==1.0 && m2.Value[2]==0.0 && m2.Value[1]==0.0 && m2.Value[3]==1.0); } Bool Matrix3fLoadIdentity() { Matrix3f m3; return (m3.Value[0]==1.0 && m3.Value[3]==0.0 && m3.Value[6]==0.0 && m3.Value[1]==0.0 && m3.Value[4]==1.0 && m3.Value[7]==0.0 && m3.Value[2]==0.0 && m3.Value[5]==0.0 && m3.Value[8]==1.0); } Bool Matrix4fLoadIdentity() { Mat4f m4; return (m4.Value[0]==1.0 && m4.Value[4]==0.0 && m4.Value[8]==0.0 && m4.Value[12]==0.0 && m4.Value[1]==0.0 && m4.Value[5]==1.0 && m4.Value[9]==0.0 && m4.Value[13]==0.0 && m4.Value[2]==0.0 && m4.Value[6]==0.0 && m4.Value[10]==1.0 && m4.Value[14]==0.0 && m4.Value[3]==0.0 && m4.Value[7]==0.0 && m4.Value[11]==0.0 && m4.Value[15]==1.0); } Bool Matrix2fLoadZero() { Matrix2f m2; m2.LoadZero(); return (m2.Value[0]==0.0 && m2.Value[2]==0.0 && m2.Value[1]==0.0 && m2.Value[3]==0.0); } Bool Matrix3fLoadZero() { Matrix3f m3; m3.LoadZero(); return (m3.Value[0]==0.0 && m3.Value[3]==0.0 && m3.Value[6]==0.0 && m3.Value[1]==0.0 && m3.Value[4]==0.0 && m3.Value[7]==0.0 && m3.Value[2]==0.0 && m3.Value[5]==0.0 && m3.Value[8]==0.0); } Bool Matrix4fLoadZero() { Mat4f m4; m4.LoadZero(); return (m4.Value[0]==0.0 && m4.Value[4]==0.0 && m4.Value[8]==0.0 && m4.Value[12]==0.0 && m4.Value[1]==0.0 && m4.Value[5]==0.0 && m4.Value[9]==0.0 && m4.Value[13]==0.0 && m4.Value[2]==0.0 && m4.Value[6]==0.0 && m4.Value[10]==0.0 && m4.Value[14]==0.0 && m4.Value[3]==0.0 && m4.Value[7]==0.0 && m4.Value[11]==0.0 && m4.Value[15]==0.0); } }; GeometryMatrixTest MatrixTest;
f23ec40136f6a2083170484447041a99ff0a02a9
92211fc562653dfbf827729913f770d2ec286485
/source/get_process_input/initial_data_handling/Handle_Pressure_Vessel.cpp
0175b0ffbb8d4ad10b4fe34c9af1f5e571ffee09
[ "MIT" ]
permissive
ysadat7/chemical-kinetics-solver
95f24bd30a5cac09b55c01877c2d2f08ccf85df8
7010fd6c72c29a0d912ad0c353ff13a5b643cc04
refs/heads/master
2022-10-24T05:49:24.748031
2021-05-24T16:28:52
2021-05-24T16:28:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,518
cpp
/* * Handle_PressureVessel.cpp * * Created on: 26.10.2017 * Author: DetlevCM */ #include "../headers/Headers.hpp" /* * New input options for the inclusion of a pressure vessel */ void Handle_Pressure_Vessel( Initial_Data& InitialParameters, vector<string> Input ) { PressureVessel Pressure_Vessel; size_t i; for(i=0;i<Input.size();i++) { vector< string > line_content; if(Test_If_Word_Found(Input[i],"Liquid Volume")) { line_content = Tokenise_String_To_String(Input[i]," \t"); // it is mL -> make into m^3 Pressure_Vessel.Liquid_Sample_Volume = stod(line_content[3],NULL)*1e-6; cout << "Sample Size: " << InitialParameters.PetroOxy.SampleSize << "\n"; line_content.clear(); } if(Test_If_Word_Found(Input[i],"Gas Volume")) { line_content = Tokenise_String_To_String(Input[i]," \t"); // it is mL -> make into m^3 Pressure_Vessel.Gas_Sample_Volume = stod(line_content[3],NULL)*1e-6; cout << "Sample Size: " << InitialParameters.PetroOxy.SampleSize << "\n"; line_content.clear(); } } // Need to think about useful additional information // Maybe Gas Phase pressure so that we can calculate a concentration in case we do not know it? // how do I handle a "gap" between expected and actual pressure - mainly from the PetroOxy calculation where I had // an initial pressure and a max pressure which wasn't fully covered by the oxygen component... // assume fuel filled the rest? ... InitialParameters.Pressure_Vessel = Pressure_Vessel; }
67c24656e66f391f5b6b2ae98fb17c33ac259ed2
6159bbd0c37d0d8ebe195d4df8eeb84a180bc064
/joel/catmarkframework/CatmarkSubdiv/mainview.cpp
4d18a4a21a8002edb12a1d07ccc2ee322615e543
[]
no_license
joelgrondman/AGC_Pixar
917bfc76a52fcf6679343716330de3c2089d9f72
930c9b774a27e600a6b990119e1b84bf57c4771b
refs/heads/master
2021-05-06T03:24:54.217878
2018-01-17T12:20:49
2018-01-17T12:20:49
114,899,463
0
0
null
null
null
null
UTF-8
C++
false
false
11,561
cpp
#include "mainview.h" MainView::MainView(QWidget *Parent) : QOpenGLWidget(Parent) { qDebug() << "✓✓ MainView constructor"; modelLoaded = false; wireframeMode = true; rotAngle = 0.0; FoV = 60.0; } MainView::~MainView() { qDebug() << "✗✗ MainView destructor"; glDeleteBuffers(1, &meshCoordsBO); glDeleteBuffers(1, &meshNormalsBO); glDeleteBuffers(1, &meshIndexBO); glDeleteVertexArrays(1, &meshVAO); debugLogger->stopLogging(); delete mainShaderProg, tessShaderProg; } // --- void MainView::createShaderPrograms() { qDebug() << ".. createShaderPrograms"; mainShaderProg = new QOpenGLShaderProgram(); mainShaderProg->addShaderFromSourceFile(QOpenGLShader::Vertex, ":/shaders/vertshader.glsl"); mainShaderProg->addShaderFromSourceFile(QOpenGLShader::Fragment, ":/shaders/fragshader.glsl"); mainShaderProg->link(); tessShaderProg = new QOpenGLShaderProgram(); tessShaderProg->addShaderFromSourceFile(QOpenGLShader::Vertex, ":/shaders/vertshadertess.glsl"); tessShaderProg->addShaderFromSourceFile(QOpenGLShader::TessellationControl, ":/shaders/tesselationcontrolshader.glsl"); tessShaderProg->addShaderFromSourceFile(QOpenGLShader::TessellationEvaluation, ":/shaders/tesselationevaluationshader.glsl"); tessShaderProg->addShaderFromSourceFile(QOpenGLShader::Fragment, ":/shaders/fragshader.glsl"); tessShaderProg->link(); uniModelViewMatrix = glGetUniformLocation(mainShaderProg->programId(), "modelviewmatrix"); uniProjectionMatrix = glGetUniformLocation(mainShaderProg->programId(), "projectionmatrix"); uniNormalMatrix = glGetUniformLocation(mainShaderProg->programId(), "normalmatrix"); uniTessModelViewMatrix = glGetUniformLocation(tessShaderProg->programId(), "modelviewmatrix"); uniTessProjectionMatrix = glGetUniformLocation(tessShaderProg->programId(), "projectionmatrix"); uniTessNormalMatrix = glGetUniformLocation(tessShaderProg->programId(), "normalmatrix"); uniInner1 = glGetUniformLocation(tessShaderProg->programId(), "inner1"); uniInner2 = glGetUniformLocation(tessShaderProg->programId(), "inner2"); uniOuter = glGetUniformLocation(tessShaderProg->programId(), "outer"); } void MainView::createBuffers() { qDebug() << ".. createBuffers"; glGenVertexArrays(1, &meshVAO); glBindVertexArray(meshVAO); glGenBuffers(1, &meshCoordsBO); glBindBuffer(GL_ARRAY_BUFFER, meshCoordsBO); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glGenBuffers(1, &meshNormalsBO); glBindBuffer(GL_ARRAY_BUFFER, meshNormalsBO); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0); glGenBuffers(1, &meshIndexBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshIndexBO); glBindVertexArray(0); } void MainView::updateMeshBuffers(Mesh* currentMesh) { qDebug() << ".. updateBuffers"; unsigned int k; unsigned short n, m; HalfEdge* currentEdge; vertexCoords.clear(); vertexCoords.reserve(currentMesh->Vertices.size()); for (k=0; k<currentMesh->Vertices.size(); k++) { vertexCoords.append(currentMesh->Vertices[k].coords); } vertexNormals.clear(); vertexNormals.reserve(currentMesh->Vertices.size()); for (k=0; k<currentMesh->Faces.size(); k++) { currentMesh->setFaceNormal(&currentMesh->Faces[k]); } for (k=0; k<currentMesh->Vertices.size(); k++) { vertexNormals.append( currentMesh->computeVertexNormal(&currentMesh->Vertices[k]) ); } polyIndices.clear(); if (surfacePatches) { //probably not the right amount to reserve polyIndices.reserve(currentMesh->HalfEdges.size() + currentMesh->Faces.size()); //used to hold quad indices QVector<unsigned int> quadInd = QVector<unsigned int>(16,0); for (k=0; k<currentMesh->Faces.size(); k++) { n = currentMesh->Faces[k].val; //continue if the face is a quad if (currentMesh->Faces[k].val == 4) { //skip if one of the vertices doesn't have valency 4 currentEdge = currentMesh->Faces[k].side; bool regular = true; for (int v = 0; v < 4; ++v) { if (currentEdge->target->val != 4 || currentEdge->twin->polygon == nullptr || currentEdge->twin->next->twin->polygon == nullptr) { regular = false; break; } currentEdge = currentEdge->next; } if (regular) { /* for (int r = 0; r < 4; ++ r) { currentEdge->target->index; currentEdge->twin->prev->prev->target->index; currentEdge->twin->prev->twin->next->target->index; } */ //start at one of the corners currentEdge = currentEdge->twin->next->twin->next->next; for(int r = 0; r < 4; ++r) { for (int k = 0; k < 4; ++k) { polyIndices.append(currentEdge->target->index); if (k == 2) { if (r != 3) currentEdge = currentEdge->prev; else currentEdge = currentEdge->next->next->twin; } else if (k == 3) { if (r != 2) currentEdge = currentEdge->prev->prev->twin->prev->prev->twin->prev->twin ; else currentEdge = currentEdge->prev->prev->twin->prev->prev->twin->prev->prev; } else { if (r != 3) currentEdge = currentEdge->prev->twin->prev; else currentEdge = currentEdge->next->next->twin; } } } polyIndices.append(maxInt); } } } //for 4 vertices per primitive } else { polyIndices.reserve(currentMesh->HalfEdges.size() + currentMesh->Faces.size()); for (k=0; k<currentMesh->Faces.size(); k++) { n = currentMesh->Faces[k].val; currentEdge = currentMesh->Faces[k].side; for (m=0; m<n; m++) { polyIndices.append(currentEdge->target->index); currentEdge = currentEdge->next; } polyIndices.append(maxInt); } } // --- glBindBuffer(GL_ARRAY_BUFFER, meshCoordsBO); glBufferData(GL_ARRAY_BUFFER, sizeof(QVector3D)*vertexCoords.size(), vertexCoords.data(), GL_DYNAMIC_DRAW); qDebug() << " → Updated meshCoordsBO"; glBindBuffer(GL_ARRAY_BUFFER, meshNormalsBO); glBufferData(GL_ARRAY_BUFFER, sizeof(QVector3D)*vertexNormals.size(), vertexNormals.data(), GL_DYNAMIC_DRAW); qDebug() << " → Updated meshNormalsBO"; glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshIndexBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int)*polyIndices.size(), polyIndices.data(), GL_DYNAMIC_DRAW); qDebug() << " → Updated meshIndexBO"; meshIBOSize = polyIndices.size(); update(); } void MainView::updateMatrices() { modelViewMatrix.setToIdentity(); modelViewMatrix.translate(QVector3D(0.0, 0.0, -3.0)); modelViewMatrix.scale(QVector3D(1.0, 1.0, 1.0)); modelViewMatrix.rotate(rotAngle, QVector3D(0.0, 1.0, 0.0)); projectionMatrix.setToIdentity(); projectionMatrix.perspective(FoV, dispRatio, 0.2, 4.0); normalMatrix = modelViewMatrix.normalMatrix(); uniformUpdateRequired = true; update(); } void MainView::updateUniforms() { // mainShaderProg should be bound at this point! glUniformMatrix4fv(uniModelViewMatrix, 1, false, modelViewMatrix.data()); glUniformMatrix4fv(uniProjectionMatrix, 1, false, projectionMatrix.data()); glUniformMatrix3fv(uniNormalMatrix, 1, false, normalMatrix.data()); } void MainView::updateTessUniforms() { // mainShaderProg should be bound at this point! glUniformMatrix4fv(uniTessModelViewMatrix, 1, false, modelViewMatrix.data()); glUniformMatrix4fv(uniTessProjectionMatrix, 1, false, projectionMatrix.data()); glUniformMatrix3fv(uniTessNormalMatrix, 1, false, normalMatrix.data()); glUniform1f(uniInner1, inner1); glUniform1f(uniInner2, inner2); glUniform1f(uniOuter, outer); } // --- void MainView::initializeGL() { initializeOpenGLFunctions(); qDebug() << ":: OpenGL initialized"; debugLogger = new QOpenGLDebugLogger(); connect( debugLogger, SIGNAL( messageLogged( QOpenGLDebugMessage ) ), this, SLOT( onMessageLogged( QOpenGLDebugMessage ) ), Qt::DirectConnection ); if ( debugLogger->initialize() ) { qDebug() << ":: Logging initialized"; debugLogger->startLogging( QOpenGLDebugLogger::SynchronousLogging ); debugLogger->enableMessages(); } QString glVersion; glVersion = reinterpret_cast<const char*>(glGetString(GL_VERSION)); qDebug() << ":: Using OpenGL" << qPrintable(glVersion); // Enable depth buffer glEnable(GL_DEPTH_TEST); // Default is GL_LESS glDepthFunc(GL_LEQUAL); glEnable(GL_PRIMITIVE_RESTART); maxInt = ((unsigned int) -1); glPrimitiveRestartIndex(maxInt); glPatchParameteri(GL_PATCH_VERTICES, 16); // --- createShaderPrograms(); createBuffers(); // --- updateMatrices(); } void MainView::resizeGL(int newWidth, int newHeight) { qDebug() << ".. resizeGL"; dispRatio = (float)newWidth/newHeight; updateMatrices(); } void MainView::paintGL() { if (modelLoaded) { glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if(surfacePatches) { tessShaderProg->bind(); if (uniformUpdateRequired) { updateTessUniforms(); uniformUpdateRequired = false; } renderTessMesh(); tessShaderProg->release(); } else { mainShaderProg->bind(); if (uniformUpdateRequired) { updateUniforms(); uniformUpdateRequired = false; } renderMesh(); mainShaderProg->release(); } } } // --- void MainView::renderMesh() { glBindVertexArray(meshVAO); if (wireframeMode) { glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); glDrawElements(GL_LINE_LOOP, meshIBOSize, GL_UNSIGNED_INT, 0); //glDrawElements(GL_LINE_LOOP, meshIBOSize, GL_UNSIGNED_INT, 0); } else { glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); //glDrawElements(GL_TRIANGLE_FAN, meshIBOSize, GL_UNSIGNED_INT, 0); glDrawElements(GL_TRIANGLE_FAN, meshIBOSize, GL_UNSIGNED_INT, 0); } glBindVertexArray(0); } void MainView::renderTessMesh() { glBindVertexArray(meshVAO); if (wireframeMode) { glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); glDrawElements(GL_PATCHES, meshIBOSize, GL_UNSIGNED_INT, 0); //glDrawElements(GL_LINE_LOOP, meshIBOSize, GL_UNSIGNED_INT, 0); } else { glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); //glDrawElements(GL_TRIANGLE_FAN, meshIBOSize, GL_UNSIGNED_INT, 0); glDrawElements(GL_PATCHES, meshIBOSize, GL_UNSIGNED_INT, 0); } glBindVertexArray(0); } // --- void MainView::mousePressEvent(QMouseEvent* event) { setFocus(); } void MainView::wheelEvent(QWheelEvent* event) { FoV -= event->delta() / 60.0; updateMatrices(); } void MainView::keyPressEvent(QKeyEvent* event) { switch(event->key()) { case 'Z': wireframeMode = !wireframeMode; update(); break; } } // --- void MainView::onMessageLogged( QOpenGLDebugMessage Message ) { qDebug() << " → Log:" << Message; }
bb17d7e698eed61df797b6d816d13b5728a337d1
2f78e134c5b55c816fa8ee939f54bde4918696a5
/code/gui/comboscreen/cslistobjecttri.h
56a52da26226948e8f5194bb8b5033e10b70885b
[]
no_license
narayanr7/HeavenlySword
b53afa6a7a6c344e9a139279fbbd74bfbe70350c
a255b26020933e2336f024558fefcdddb48038b2
refs/heads/master
2022-08-23T01:32:46.029376
2020-05-26T04:45:56
2020-05-26T04:45:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,049
h
/*************************************************************************************************** * * DESCRIPTION This is a will render 3 combo list object at once, basically its a wrapper. * * NOTES * ***************************************************************************************************/ #ifndef CSLISTOBJECTTRI_H #define CSLISTOBJECTTRI_H #include "cslistobjectbase.h" #define NUMCHILDREN 14 class CSListObjectTri : public CSListObjectBase { public: CSListObjectTri(); ~CSListObjectTri(); virtual void Render( void ); virtual void Update( void ); virtual void SetFirstControl( CSListObjectBase* pFirstControl ); virtual void SetSecondControl( CSListObjectBase* pSecondControl ); virtual void SetThirdControl( CSListObjectBase* pThridControl ); virtual void SetControl( CSListObjectBase* pControl, int iControl ); virtual void DeleteControls( void ); protected: void SetWidthAndHeightDetails( void ); CSListObjectBase* m_pChildren[ NUMCHILDREN ]; }; //end class CSListObjectTri #endif //CSLISTOBJECTTRI_H
ce63e1861d3546a96aacf846c066936cc491f0fd
2e0472397ec7145d50081d4890eb0af2323eb175
/Code/include/OE/Math/Vec4.inl
422dfba12bd19ef162113756a4f0c76c9b5badee
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mlomb/OrbitEngine
5c471a853ea555f0738427999dd9cef3a1c90a01
41f053626f05782e81c2e48f5c87b04972f9be2c
refs/heads/master
2021-09-09T01:27:31.097901
2021-08-28T16:07:16
2021-08-28T16:07:16
99,012,019
26
3
null
null
null
null
UTF-8
C++
false
false
5,545
inl
#ifndef VEC4_INL #define VEC4_INL #include "OE/Math/Math.hpp" #include "Vec4.hpp" namespace OrbitEngine { namespace Math { template<typename T> inline Vec4<T>::Vec4(const T& _x, const T& _y, const T& _z, const T& _w) : x(_x), y(_y), z(_z), w(_w) { } template<typename T> inline Vec4<T>::Vec4(const Vec2<T> _xy, const Vec2<T> _zw) : xy(_xy), zw(_zw) { } template<typename T> inline Vec4<T>::Vec4() : Vec4(0, 0, 0, 0) { } template<typename T> inline T& Vec4<T>::operator[](int i) { return data[i]; } template<typename T> template<typename U> inline bool Vec4<T>::operator==(const Vec4<U> &b) const { return x == b.x && y == b.y && z == b.z && w == b.w; } template<typename T> template<typename U> inline bool Vec4<T>::operator!=(const Vec4<U> &b) const { return x != b.x || y != b.y || z != b.z || w != b.w; } template<typename T> inline Vec4<T>& Vec4<T>::operator+() const { return *this; } template<typename T> inline Vec4<T>& Vec4<T>::operator-() const { return Vec4<T>(-x, -y, -z, -w); } template<typename T> inline Vec4<T>& Vec4<T>::operator+=(const Vec4& b) { this->x += b.x; this->y += b.y; this->z += b.z; this->w += b.w; return *this; } template<typename T> inline Vec4<T>& Vec4<T>::operator-=(const Vec4& b) { this->x -= b.x; this->y -= b.y; this->z -= b.z; this->w -= b.w; return *this; } template<typename T> inline Vec4<T>& Vec4<T>::operator*=(const Vec4& b) { this->x *= b.x; this->y *= b.y; this->z *= b.z; this->w *= b.w; return *this; } template<typename T> inline Vec4<T>& Vec4<T>::operator/=(const Vec4& b) { this->x /= b.x; this->y /= b.y; this->z /= b.z; this->w /= b.w; return *this; } template<typename T> inline Vec4<T>& Vec4<T>::operator+=(const T& b) { this->x += b; this->y += b; this->z += b; this->w += b; return *this; } template<typename T> inline Vec4<T>& Vec4<T>::operator-=(const T& b) { this->x -= b; this->y -= b; this->z -= b; this->w -= b; return *this; } template<typename T> inline Vec4<T>& Vec4<T>::operator*=(const T& b) { this->x *= b; this->y *= b; this->z *= b; this->w *= b; return *this; } template<typename T> inline Vec4<T>& Vec4<T>::operator/=(const T& b) { this->x /= b; this->y /= b; this->z /= b; this->w /= b; return *this; } template<typename T> inline Vec4<T> operator+(const Vec4<T>& a, const Vec4<T>& b) { return Vec4<T>(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); } template<typename T> inline Vec4<T> operator-(const Vec4<T>& a, const Vec4<T>& b) { return Vec4<T>(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); } template<typename T> inline Vec4<T> operator*(const Vec4<T>& a, const Vec4<T>& b) { return Vec4<T>(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w); } template<typename T> inline Vec4<T> operator/(const Vec4<T>& a, const Vec4<T>& b) { return Vec4<T>(a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w); } template<typename T> inline Vec4<T> operator+(const Vec4<T>& a, const T& b) { return Vec4<T>(a.x + b, a.y + b, a.z + b, a.w + b); } template<typename T> inline Vec4<T> operator+(const T& a, const Vec4<T>& b) { return b + a; } template<typename T> inline Vec4<T> operator*(const Vec4<T>& a, const T& b) { return Vec4<T>(a.x * b, a.y * b, a.z * b, a.w * b); } template<typename T> inline Vec4<T> operator*(const T& a, const Vec4<T>& b) { return b * a; } template<typename T> inline Vec4<T> operator-(const Vec4<T>& a, const T& b) { return Vec4<T>(a.x - b, a.y - b, a.z - b, a.w - b); } template<typename T> inline Vec4<T> operator-(const T& a, const Vec4<T>& b) { return Vec4<T>(a - b.x, a - b.y, a - b.z, a - b.w); } template<typename T> inline Vec4<T> operator/(const Vec4<T>& a, const T& b) { return Vec4<T>(a.x / b, a.y / b, a.z / b, a.w / b); } template<typename T> inline Vec4<T> operator/(const T& a, const Vec4<T>& b) { return Vec4<T>(a / b.x, a / b.y, a / b.z, a / b.w); } // -- template<typename T> inline void Vec4<T>::normalize() { float length = sqrt(x * x + y * y + z * z + w * w); if (length == 0) return; x /= length; y /= length; z /= length; w /= length; } template<typename T> template<typename U> inline bool Vec4<T>::isInside(Vec2<U> point) { return point.x >= x && point.x <= x + z && point.y >= y && point.y <= y + w; } template<typename T> inline Vec2<T> Vec4<T>::xz() { return Vec2<T>(x, z); } template<typename T> inline Vec2<T> Vec4<T>::yw() { return Vec2<T>(y, w); } template<typename T> inline Vec4<T> Vec4<T>::Min(const Vec4<T>& a, const Vec4<T>& b) { return Vec4<T>(std::min(a.x, b.x), std::min(a.y, b.y), std::min(a.z, b.z), std::min(a.w, b.w)); } template<typename T> inline Vec4<T> Vec4<T>::Max(const Vec4<T>& a, const Vec4<T>& b) { return Vec4<T>(std::max(a.x, b.x), std::max(a.y, b.y), std::max(a.z, b.z), std::max(a.w, b.w)); } template<typename T> inline Vec4<T> Vec4<T>::Lerp(const Vec4<T>& a, const Vec4<T>& b, T t) { return Vec4<T>(lerp(a.x, b.x, t), lerp(a.y, b.y, t), lerp(a.z, b.z, t), lerp(a.w, b.w, t)); } template<typename T> inline Vec4<T> Vec4<T>::Normalize(const Vec4<T>& a) { Vec4<T> v(a); v.normalize(); return v; } } } #endif
32e40124f14d1d5bc89977681b3ee85635ab4aba
43b5060c3a2d9a6e57a20919351462819d3d07ed
/02564_stud/lib02564/CGLA/gel_rand.cpp
7b8eb05e7160e4728d87a2cfb543e068e8412569
[]
no_license
qotsafan1/graphics
2d72539f09f742b9a4f9ea25dedb9d27ba36c94f
646b821839b82c3d018770e51a85f97209e1f24a
refs/heads/master
2021-04-06T00:28:35.860088
2018-03-15T13:23:06
2018-03-15T13:23:06
124,408,166
0
0
null
null
null
null
UTF-8
C++
false
false
595
cpp
#include "CGLA.h" namespace { unsigned int seed = 1; unsigned int current_rand = 1; } namespace CGLA { void gel_srand(unsigned int s) { seed = current_rand = s; } unsigned int gel_rand(unsigned int k) { unsigned int b = 3125; unsigned int c = 49; unsigned int result = seed; for (;k > 0;k>>=1) { if (k & 1) result = result * b + c; c += b * c; b *= b; } return result; } unsigned int gel_rand() { unsigned int b = 3125; unsigned int c = 49; current_rand = current_rand*b + c; return current_rand; } }
8798cec37fbe81b40d60553f3ae63b6ca895aa9e
009d78e631239fee0b6404f904c251c4d94d0574
/COP4530-LacherOnline/proj2/gssearch.h
6fb602a80e61147c0b34e277afa8d9048d77949d
[ "MIT" ]
permissive
il16d/FSUCSundergrad
3665bef7df8b6810baa42d62033fa849163db7f6
4341613124499305df9d496079d7a7db2ecf935e
refs/heads/master
2022-07-27T18:40:48.195138
2020-05-18T18:06:09
2020-05-18T18:06:09
262,361,559
0
0
null
null
null
null
UTF-8
C++
false
false
647
h
/* gssearch.h January 30th 2017 */ #ifndef GSSEARCH_H #define GSSEARCH_H #include <compare_spy.h> namespace seq { // return upper bound of T template < class I, typename T, class P > I g_lower_bound(I beg, I end, const T& val, P& cmp) { while (beg != end) { if (!cmp(*beg, val)) return beg; ++beg; } return beg; } // return upper bound of T template < class I, typename T, class P> I g_upper_bound(I beg, I end, const T& val, P& cmp) { while (beg != end) { if (cmp(val, *beg)) return beg; ++beg; } return beg; } } //namespace seq #endif
1820f84a95650443ccf538baeeec76b6e789c89d
79cedbcf7d93850d58f4f4e2a0acd997b82d8c55
/libappfuse/tests/AppFuseTest.cc
8c2cc47129df4a84dbca2b9f958d4108d2f21221
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
imagegithub/platform_system_core
9a6a2f4b1b0150b03ff9595fcc43440d012087bb
e381ecf63bb6a68a7bae6970a3491d4d00e61506
refs/heads/master
2021-01-11T06:26:43.399604
2016-10-28T06:22:32
2016-10-28T06:22:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,731
cc
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specic language governing permissions and * limitations under the License. */ #include "libappfuse/AppFuse.h" #include <fcntl.h> #include <string.h> #include <sys/socket.h> #include <android-base/unique_fd.h> #include <gtest/gtest.h> namespace android { constexpr char kTempFile[] = "/data/local/tmp/appfuse_test_dump"; void OpenTempFile(android::base::unique_fd* fd) { fd->reset(open(kTempFile, O_CREAT | O_RDWR)); ASSERT_NE(-1, *fd) << strerror(errno); unlink(kTempFile); ASSERT_NE(-1, *fd) << strerror(errno); } void TestReadInvalidLength(size_t headerSize, size_t write_size) { android::base::unique_fd fd; OpenTempFile(&fd); char buffer[std::max(headerSize, sizeof(FuseRequest))]; FuseRequest* const packet = reinterpret_cast<FuseRequest*>(buffer); packet->header.len = headerSize; ASSERT_NE(-1, write(fd, packet, write_size)) << strerror(errno); lseek(fd, 0, SEEK_SET); EXPECT_FALSE(packet->Read(fd)); } void TestWriteInvalidLength(size_t size) { android::base::unique_fd fd; OpenTempFile(&fd); char buffer[std::max(size, sizeof(FuseRequest))]; FuseRequest* const packet = reinterpret_cast<FuseRequest*>(buffer); packet->header.len = size; EXPECT_FALSE(packet->Write(fd)); } // Use FuseRequest as a template instance of FuseMessage. TEST(FuseMessageTest, ReadAndWrite) { android::base::unique_fd fd; OpenTempFile(&fd); FuseRequest request; request.header.len = sizeof(FuseRequest); request.header.opcode = 1; request.header.unique = 2; request.header.nodeid = 3; request.header.uid = 4; request.header.gid = 5; request.header.pid = 6; strcpy(request.lookup_name, "test"); ASSERT_TRUE(request.Write(fd)); memset(&request, 0, sizeof(FuseRequest)); lseek(fd, 0, SEEK_SET); ASSERT_TRUE(request.Read(fd)); EXPECT_EQ(sizeof(FuseRequest), request.header.len); EXPECT_EQ(1u, request.header.opcode); EXPECT_EQ(2u, request.header.unique); EXPECT_EQ(3u, request.header.nodeid); EXPECT_EQ(4u, request.header.uid); EXPECT_EQ(5u, request.header.gid); EXPECT_EQ(6u, request.header.pid); EXPECT_STREQ("test", request.lookup_name); } TEST(FuseMessageTest, Read_InconsistentLength) { TestReadInvalidLength(sizeof(fuse_in_header), sizeof(fuse_in_header) + 1); } TEST(FuseMessageTest, Read_TooLong) { TestReadInvalidLength(sizeof(FuseRequest) + 1, sizeof(FuseRequest) + 1); } TEST(FuseMessageTest, Read_TooShort) { TestReadInvalidLength(sizeof(fuse_in_header) - 1, sizeof(fuse_in_header) - 1); } TEST(FuseMessageTest, Write_TooLong) { TestWriteInvalidLength(sizeof(FuseRequest) + 1); } TEST(FuseMessageTest, Write_TooShort) { TestWriteInvalidLength(sizeof(fuse_in_header) - 1); } TEST(FuseResponseTest, Reset) { FuseResponse response; // Write 1 to the first ten bytes. memset(response.read_data, 'a', 10); response.Reset(0, -1, 2); EXPECT_EQ(sizeof(fuse_out_header), response.header.len); EXPECT_EQ(-1, response.header.error); EXPECT_EQ(2u, response.header.unique); EXPECT_EQ('a', response.read_data[0]); EXPECT_EQ('a', response.read_data[9]); response.Reset(5, -4, 3); EXPECT_EQ(sizeof(fuse_out_header) + 5, response.header.len); EXPECT_EQ(-4, response.header.error); EXPECT_EQ(3u, response.header.unique); EXPECT_EQ(0, response.read_data[0]); EXPECT_EQ(0, response.read_data[1]); EXPECT_EQ(0, response.read_data[2]); EXPECT_EQ(0, response.read_data[3]); EXPECT_EQ(0, response.read_data[4]); EXPECT_EQ('a', response.read_data[5]); } TEST(FuseResponseTest, ResetHeader) { FuseResponse response; // Write 1 to the first ten bytes. memset(response.read_data, 'a', 10); response.ResetHeader(0, -1, 2); EXPECT_EQ(sizeof(fuse_out_header), response.header.len); EXPECT_EQ(-1, response.header.error); EXPECT_EQ(2u, response.header.unique); EXPECT_EQ('a', response.read_data[0]); EXPECT_EQ('a', response.read_data[9]); response.ResetHeader(5, -4, 3); EXPECT_EQ(sizeof(fuse_out_header) + 5, response.header.len); EXPECT_EQ(-4, response.header.error); EXPECT_EQ(3u, response.header.unique); EXPECT_EQ('a', response.read_data[0]); EXPECT_EQ('a', response.read_data[9]); } TEST(FuseBufferTest, HandleInit) { FuseBuffer buffer; memset(&buffer, 0, sizeof(FuseBuffer)); buffer.request.header.opcode = FUSE_INIT; buffer.request.init_in.major = FUSE_KERNEL_VERSION; buffer.request.init_in.minor = FUSE_KERNEL_MINOR_VERSION; buffer.HandleInit(); ASSERT_EQ(sizeof(fuse_out_header) + sizeof(fuse_init_out), buffer.response.header.len); EXPECT_EQ(kFuseSuccess, buffer.response.header.error); EXPECT_EQ(static_cast<unsigned int>(FUSE_KERNEL_VERSION), buffer.response.init_out.major); EXPECT_EQ(15u, buffer.response.init_out.minor); EXPECT_EQ(static_cast<unsigned int>(FUSE_ATOMIC_O_TRUNC | FUSE_BIG_WRITES), buffer.response.init_out.flags); EXPECT_EQ(kFuseMaxWrite, buffer.response.init_out.max_write); } TEST(FuseBufferTest, HandleNotImpl) { FuseBuffer buffer; memset(&buffer, 0, sizeof(FuseBuffer)); buffer.HandleNotImpl(); ASSERT_EQ(sizeof(fuse_out_header), buffer.response.header.len); EXPECT_EQ(-ENOSYS, buffer.response.header.error); } } // namespace android
444f499227a25021f4d4f44494472a323e685cee
aa4c17d1847e19c5b5ab3978ba765bb22b5d6c53
/LeetCode/LeetCode-CPP/Array/977. Squares of a Sorted Array.cpp
6f6a82319f4a75d039aa2ccb2523a4ec06087924
[]
no_license
jiajia0/algorithmTopic
bffc95528c6ed99482e9150898ac42f7a633b910
4ea865ecb0f5a7375fd41a1362217057b687937c
refs/heads/master
2023-02-22T12:38:40.907284
2021-01-30T16:27:47
2021-01-30T16:27:47
103,752,364
0
0
null
null
null
null
UTF-8
C++
false
false
1,084
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; /* class Solution { public: vector<int> sortedSquares(vector<int>& A) { for(int i = 0; i < A.size(); i++) { A[i] *= A[i];// 平方 } sort(A.begin(), A.end()); return A; } }; */ // 利用非递减的特性 class Solution { public: vector<int> sortedSquares(vector<int>& A) { int left = 0; int right = A.size() - 1; int n = A.size() - 1; vector<int> result(A.size(), 0); while(left <= right) { // 平方最大的数字在数组的两侧 if(abs(A[left]) < abs(A[right])) result[n--] = A[right]*A[right--]; else result[n--] = A[left]*A[left++]; } return result; } }; int main() { Solution s; vector<int> num; num.push_back(-7); num.push_back(-3); num.push_back(2); num.push_back(3); num.push_back(11); vector<int> ret = s.sortedSquares(num); for(int n : ret) { cout << n << " "; } }
dbd93e39b0c46b1bf169944ef96118a1003441d8
54f62e14405fb25bae9c88e4767944a1d75dec2e
/files/asobiba/youjyo/RStreamMemory.h
bd59d3329517fb63b7f75f2c43ffbe6aee7a9fdf
[]
no_license
Susuo/rtilabs
408975914dde59f44c1670ce3db663ed785d00b2
822a39d1605de7ea2639bdffdc016d8cc46b0875
refs/heads/master
2020-12-11T01:48:08.562065
2012-04-10T14:22:37
2012-04-10T14:22:37
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
765
h
// RStreamMemory.h: RStreamMemory クラスのインターフェイス // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_RSTREAMMEMORY_H__BFE710F6_A2FE_44B8_8B9E_ABFD353E042E__INCLUDED_) #define AFX_RSTREAMMEMORY_H__BFE710F6_A2FE_44B8_8B9E_ABFD353E042E__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "RStream.h" class RStreamMemory : public RStream { public: RStreamMemory(char *ioMem,int inSize); virtual ~RStreamMemory(); virtual int Write(const char *inBuffer ,int inBufferSize) ; virtual int Read(char *outBuffer ,int inBufferSize) ; private: char *Mem; int Size; int NowReadSize; }; #endif // !defined(AFX_RSTREAMMEMORY_H__BFE710F6_A2FE_44B8_8B9E_ABFD353E042E__INCLUDED_)
bb35ebfadd146e0c660ff3d25205aaa87257ef3f
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/net/mmc/rtrlib/ipctrl.cpp
d3f739fc3e3097fa02f24f8b609b942d1d3c54a1
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,844
cpp
//============================================================================ // Copyright (C) Microsoft Corporation, 1996 - 1999 // // File: ipctrl.cpp // // History: // Tony Romano Created. // 06/17/96 Abolade Gbadegesin Revised. // // Implements the C++ class encapsulating the IP-address custom control. //============================================================================ #include "stdafx.h" extern "C" { #include "ipaddr.h" }; #include "ipctrl.h" IPControl::IPControl( ) { m_hIPaddr = 0; } IPControl::~IPControl( ) { } BOOL IPControl::Create( HWND hParent, UINT nID ) { ASSERT(IsWindow(hParent)); if (hParent) m_hIPaddr = GetDlgItem(hParent, nID); return m_hIPaddr != NULL; } LRESULT IPControl::SendMessage( UINT uMsg, WPARAM wParam, LPARAM lParam ) { ASSERT(IsWindow(m_hIPaddr)); return ::SendMessage(m_hIPaddr, uMsg, wParam, lParam); } BOOL IPControl::IsBlank( ) { return (BOOL)SendMessage(IP_ISBLANK, 0, 0); } VOID IPControl::SetAddress( DWORD ardwAddress[4] ) { SendMessage( IP_SETADDRESS, 0, MAKEIPADDRESS( ardwAddress[0], ardwAddress[1], ardwAddress[2], ardwAddress[3] ) ); } VOID IPControl::SetAddress( DWORD a1, DWORD a2, DWORD a3, DWORD a4 ) { SendMessage(IP_SETADDRESS, 0, MAKEIPADDRESS(a1,a2,a3,a4)); } VOID IPControl::SetAddress( LPCTSTR lpszString ) { if (!lpszString) { ClearAddress(); } SendMessage(WM_SETTEXT, 0, (LPARAM)lpszString); } INT IPControl::GetAddress( DWORD *a1, DWORD *a2, DWORD *a3, DWORD *a4 ) { INT_PTR nSet; DWORD dwAddress; ASSERT(a1 && a2 && a3 && a4); if ((nSet = SendMessage(IP_GETADDRESS,0,(LPARAM)&dwAddress)) == 0) { *a1 = 0; *a2 = 0; *a3 = 0; *a4 = 0; } else { *a1 = FIRST_IPADDRESS( dwAddress ); *a2 = SECOND_IPADDRESS( dwAddress ); *a3 = THIRD_IPADDRESS( dwAddress ); *a4 = FOURTH_IPADDRESS( dwAddress ); } return (INT)nSet; } INT IPControl::GetAddress( DWORD ardwAddress[4] ) { INT_PTR nSet; DWORD dwAddress; if ((nSet = SendMessage(IP_GETADDRESS, 0, (LPARAM)&dwAddress )) == 0) { ardwAddress[0] = 0; ardwAddress[1] = 0; ardwAddress[2] = 0; ardwAddress[3] = 0; } else { ardwAddress[0] = FIRST_IPADDRESS( dwAddress ); ardwAddress[1] = SECOND_IPADDRESS( dwAddress ); ardwAddress[2] = THIRD_IPADDRESS( dwAddress ); ardwAddress[3] = FOURTH_IPADDRESS( dwAddress ); } return (INT)nSet; } INT IPControl::GetAddress( CString& address ) { INT_PTR c, nSet; DWORD dwAddress; nSet = SendMessage(IP_GETADDRESS, 0, (LPARAM)&dwAddress); address.ReleaseBuffer((int)(c = SendMessage(WM_GETTEXT, 256, (LPARAM)address.GetBuffer(256)))); return (INT)nSet; } VOID IPControl::SetFocusField( DWORD dwField ) { SendMessage(IP_SETFOCUS, dwField, 0); } VOID IPControl::ClearAddress( ) { SendMessage(IP_CLEARADDRESS, 0, 0); } VOID IPControl::SetFieldRange( DWORD dwField, DWORD dwMin, DWORD dwMax ) { SendMessage(IP_SETRANGE, dwField, MAKERANGE(dwMin,dwMax)); } #if 0 WCHAR * inet_ntoaw( struct in_addr dwAddress ) { static WCHAR szAddress[16]; mbstowcs(szAddress, inet_ntoa(*(struct in_addr *)&dwAddress), 16); return szAddress; } DWORD inet_addrw( LPCWSTR szAddressW ) { CHAR szAddressA[16]; wcstombs(szAddressA, szAddressW, 16); return inet_addr(szAddressA); } #endif
7b90b6696a1f659fd707b5208640fc5af83a281b
d24cef73100a0c5d5c275fd0f92493f86d113c62
/SRC/engine/elements/quad9.swg
f6dd22edb8209ffc8d09904a6e87c36dd671193c
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
rlinder1/oof3d
813e2a8acfc89e67c3cf8fdb6af6b2b983b8b8ee
1fb6764d9d61126bd8ad4025a2ce7487225d736e
refs/heads/master
2021-01-23T00:40:34.642449
2016-09-15T20:51:19
2016-09-15T20:51:19
92,832,740
1
0
null
null
null
null
UTF-8
C++
false
false
752
swg
// -*- C++ -*- // $RCSfile: quad9.swg,v $ // $Revision: 1.2.18.1 $ // $Author: langer $ // $Date: 2014/09/27 22:34:28 $ /* This software was produced by NIST, an agency of the U.S. government, * and by statute is not subject to copyright in the United States. * Recipients of this software assume all responsibilities associated * with its operation, modification and maintenance. However, to * facilitate maintenance we ask that before distributing modified * versions of this software, you first contact the authors at * [email protected]. */ #ifndef QUAD9_SWIG #define QUAD9_SWIG %module quad9 %include "engine/typemaps.swg" %{ extern void quad9init(); %} void quad9init(); %pragma(python) include="quad9.spy" #endif // QUAD9_SWIG
2cf31e31b3b01975e7d9d7bf5d5593f3284ec046
836b7863ef6cd5e181cbd3a2b7fbcd15c8236ced
/cyclops/ShaderManager.h
62bcbd8f7ce995e55d240819dd6888117d977bf0
[]
no_license
omega-hub/cyclops
54773e4e8bd772f45c4458ec9a0356b2664b385a
2ad0c7546756a9f52a12cd16c4b8b40522b78d94
refs/heads/master
2021-01-18T22:41:32.044056
2016-05-20T22:51:49
2016-05-20T22:51:49
13,288,353
2
2
null
2014-07-13T01:22:04
2013-10-03T02:10:26
C++
UTF-8
C++
false
false
5,640
h
/****************************************************************************** * THE OMEGA LIB PROJECT *----------------------------------------------------------------------------- * Copyright 2010-2015 Electronic Visualization Laboratory, * University of Illinois at Chicago * Authors: * Alessandro Febretti [email protected] *----------------------------------------------------------------------------- * Copyright (c) 2010-2015, Electronic Visualization Laboratory, * University of Illinois at Chicago * 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. *----------------------------------------------------------------------------- * What's in this file * A manager that stores all programs and shaders that make p an independent * shading environment. Multiple shading environments can exist at the same time * in a cyclops scene (for instance for sub-scenes with different light * settings) ******************************************************************************/ #ifndef __CY_SHADER_MANAGER__ #define __CY_SHADER_MANAGER__ #include <omegaOsg/omegaOsg.h> #include <osg/Shader> #include <osg/Program> #include "cyclopsConfig.h" #include "Light.h" namespace cyclops { /////////////////////////////////////////////////////////////////////////// //! Stores all programs and shaders that make p an independent shading //! environment. Multiple shading environments can exist at the same time //! in a cyclops scene (for instance for sub-scenes with different light //! settings) class ProgramAsset: public ReferenceType { public: enum PrimitiveType { Points = GL_POINTS, Triangles = GL_TRIANGLES, TriangleStrip = GL_TRIANGLE_STRIP, LineStrip = GL_LINE_STRIP }; public: ProgramAsset(): program(NULL), vertexShaderBinary(NULL), fragmentShaderBinary(NULL), geometryShaderBinary(NULL), geometryOutVertices(0), embedded(false) {} String name; String vertexShaderName; String fragmentShaderName; String geometryShaderName; bool embedded; String vertexShaderSource; String fragmentShaderSource; String geometryShaderSource; Ref<osg::Program> program; Ref<osg::Shader> vertexShaderBinary; Ref<osg::Shader> fragmentShaderBinary; Ref<osg::Shader> geometryShaderBinary; // Geometry shader parameters int geometryOutVertices; PrimitiveType geometryInput; PrimitiveType geometryOutput; }; class CY_API ShaderManager: public ReferenceType { public: typedef Dictionary<String, String> ShaderMacroDictionary; typedef Dictionary<String, String> ShaderCache; // A shader may process at most 8 simultaneous shadow maps. static const int MaxShadows = 4; // First texture unit used by shadow maps. static const int ShadowFirstTexUnit = 4; public: ShaderManager(); ~ShaderManager(); void addLightInstance(LightInstance* l); void removeLightInstance(LightInstance* l); //! Shader management //@{ ProgramAsset* getOrCreateProgram(const String& name, const String& vertexShaderName, const String& fragmentShaderName); void addProgram(ProgramAsset* program); void updateProgram(ProgramAsset* program); ProgramAsset* createProgramFromString(const String& name, const String& vertexShaderCode, const String& fragmentShaderCode); void initShading(); void setShaderMacroToString(const String& macroName, const String& macroString); void setShaderMacroToFile(const String& macroName, const String& path); void reloadAndRecompileShaders(); void recompileShaders(ProgramAsset* program, const String& variationName = ""); //! CacheId is used as a cache identifier to re-use results of previous //! recompilations. In general, when some shader macro changes, a new //! unique cacheId should be used. void setActiveCacheId(const String& cacheId); const String& getActiveCacheId(); void recompileShaders(); void update(); //@} private: void loadShader(osg::Shader* shader, const String& name); void compileShader(osg::Shader* shader, const String& source); protected: Dictionary<String, Ref<ProgramAsset> > myPrograms; Dictionary<String, Ref<osg::Shader> > myShaders; ShaderMacroDictionary myShaderMacros; ShaderCache myShaderCache; List<LightInstance*> myActiveLights; int myNumActiveLights; String myActiveCacheId; String myShaderVariationName; }; }; #endif
9b47c8577fea87e22759d3fb65693fca61f93412
ab402dcbd73089005450f447259aa75546b337a3
/dialog.h
38581559eff7136f7d23b80e2e25b7f744af5034
[]
no_license
zZENiro/mathGraphs
2aff8dd61bc7e050970c37db5251f0b9782a37d6
749286a1a077fbe679270dda365d1b4f055db92c
refs/heads/master
2020-05-04T01:14:56.616891
2019-04-01T16:19:48
2019-04-01T16:19:48
178,901,090
0
0
null
null
null
null
UTF-8
C++
false
false
304
h
#ifndef DIALOG_H #define DIALOG_H #include <QDialog> #include "mainwindow.h" namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = nullptr); ~Dialog(); private: Ui::Dialog *ui; }; #endif // DIALOG_H
604e26c0596d02ef0eb3bac9050adfcfdd161ae2
713a93eeec7c9f9f759eb6bc4b552f0c31307cb1
/11.04.2021/b.cpp
3dfc2da6fbbcac3e81e0881dbd6d9d9df7bf6cf3
[]
no_license
markov-alex/practice
98a55d1a0dd46a4fa729108ac440ad74839b4245
83f679698f29a6ed34ac8ac64a2b07bcb2a2247c
refs/heads/main
2023-06-07T08:21:12.940256
2021-07-05T13:53:53
2021-07-05T13:53:53
383,140,566
0
0
null
null
null
null
UTF-8
C++
false
false
496
cpp
#include <bits/stdc++.h> #define ll long long int main() { ll n, k; std::cin >> n >> k; if (n & 0) { } else { std::vector<ll> cnt(n, 0); ll cur = 0; for (ll i = 0; i < n; i++) { cnt[cur]++; cur = (cur + k) % n; } for (ll i = 0; i < n; i++) { if (cnt[i] != 1) { std::cout << "No\n"; return 0; } } std::cout << "Yes\n"; } return 0; }
19a16615d7e983697a80b106fb59688b5e9fdee9
7f62f204ffde7fed9c1cb69e2bd44de9203f14c8
/DboClient/Client/Gui/QuestInventoryGui.cpp
c891d5080cd3b9ebe7daaf611e3e454ea95c78af
[]
no_license
4l3dx/DBOGLOBAL
9853c49f19882d3de10b5ca849ba53b44ab81a0c
c5828b24e99c649ae6a2953471ae57a653395ca2
refs/heads/master
2022-05-28T08:57:10.293378
2020-05-01T00:41:08
2020-05-01T00:41:08
259,094,679
3
3
null
2020-04-29T17:06:22
2020-04-26T17:43:08
null
UTF-8
C++
false
false
17,156
cpp
#include "precomp_dboclient.h" #include "QuestInventoryGui.h" // core #include "NtlDebug.h" // presentation #include "NtlPLGuiManager.h" // simulation #include "NtlSLDef.h" #include "NtlSLEvent.h" #include "NtlInventory.h" #include "NtlSLGlobal.h" #include "NtlSobAvatar.h" #include "NtlSobQuestItem.h" #include "NtlSobQuestItemAttr.h" #include "NtlSobIcon.h" // Dbo #include "DboDef.h" #include "DboEvent.h" #include "DboEventGenerator.h" #include "DboLogic.h" #include "InfoWndManager.h" #include "DialogManager.h" #include "IconMoveManager.h" #include "PopupManager.h" #include "QuestListGui.h" #include "AlarmManager.h" #include "DisplayStringManager.h" #include "GUISoundDefine.h" CQuestInventoryGui::CQuestInventoryGui(VOID) { Init(); } CQuestInventoryGui::~CQuestInventoryGui(VOID) { } VOID CQuestInventoryGui::Init(VOID) { m_pNextInvenBtn = NULL; m_pPrevInvenBtn = NULL; m_pInvenInfo = NULL; m_nLSelectedSlotIdx = -1; m_nRSelectedSlotIdx = -1; m_nMouseOnIdx = -1; m_nPushDownIdx = -1; m_nInvenPage = 0; m_nShowFocus = -1; m_nShowPickedUp = -1; memset( m_pStackNum, 0, sizeof( m_pStackNum ) ); m_pQuestListGui = NULL; } RwBool CQuestInventoryGui::Create( CQuestListGui* pQuestListGui ) { NTL_FUNCTION( "CQuestInventoryGui::Create" ); m_pQuestListGui = pQuestListGui; m_pBack = (gui::CDialog*)pQuestListGui->GetComponent( "dlgInven" ); m_pbtnDiscard = (gui::CButton*)pQuestListGui->GetComponent( "btnDiscard" ); m_pNextInvenBtn = (gui::CButton*)pQuestListGui->GetComponent( "btnNextInven" ); m_pPrevInvenBtn = (gui::CButton*)pQuestListGui->GetComponent( "btnPrevInven" ); m_pInvenInfo = (gui::CStaticBox*)pQuestListGui->GetComponent( "stbInvenInfo" ); m_pNextInvenBtn->SetToolTip( std::wstring( GetDisplayStringManager()->GetString( "DST_QUEST_NEXT_INVENTORY" ) ) ); m_pPrevInvenBtn->SetToolTip( std::wstring( GetDisplayStringManager()->GetString( "DST_QUEST_PREV_INVENTORY" ) ) ); m_pbtnDiscard->SetToolTip( std::wstring( GetDisplayStringManager()->GetString( "DST_DISCARD_BTN" ) ) ); m_slotMouseDown = m_pBack->SigMouseDown().Connect( this, &CQuestInventoryGui::OnMouseDown ); m_slotMouseUp = m_pBack->SigMouseUp().Connect( this, &CQuestInventoryGui::OnMouseUp ); m_slotMouseMove = m_pBack->SigMouseMove().Connect( this, &CQuestInventoryGui::OnMouseMove ); m_slotMouseOut = m_pBack->SigMouseLeave().Connect( this, &CQuestInventoryGui::OnMouseOut ); m_slotPaint = m_pBack->SigPaint().Connect( this, &CQuestInventoryGui::OnPaint ); m_slotMove = m_pBack->SigMove().Connect( this, &CQuestInventoryGui::OnMove ); m_slotClickNextInven= m_pNextInvenBtn->SigClicked().Connect( this, &CQuestInventoryGui::OnNextInvenBtnClick ); m_slotClickPrevInven= m_pPrevInvenBtn->SigClicked().Connect( this, &CQuestInventoryGui::OnPrevInvenBtnClick ); m_slotClickDiscardButton = m_pbtnDiscard->SigClicked().Connect( this, &CQuestInventoryGui::OnClickDiscardButton ); SetSlotRectHardCode(); UpdateInvenInfo(); m_pbtnDiscard->Raise(); // raise so the button is click-able NTL_RETURN( TRUE ); } VOID CQuestInventoryGui::Destroy(VOID) { ClearInventory(); } VOID CQuestInventoryGui::UpdateData(VOID) { CNtlSobAvatar* pAvatar = GetNtlSLGlobal()->GetSobAvatar(); if( !pAvatar ) return; CNtlQuestInventory* pInventory = pAvatar->GetQuestInventory(); for( RwInt32 i = 0 ; i < QUESTINVENTORY_MAXCOL ; ++i ) { CNtlSobQuestItem* pItem = GetQuestItemFromIdx( i ); if( pItem ) { m_surSlot[i].SetTexture( (gui::CTexture*)pItem->GetIcon()->GetImage() ); CNtlSobQuestItemAttr* pItemAttr = reinterpret_cast<CNtlSobQuestItemAttr*>( pItem->GetSobAttr() ); RwInt32 nStackNumber = pItemAttr->GetStackNum(); if( nStackNumber > 0 ) { if( m_pStackNum[i] ) { m_pStackNum[i]->SetText( nStackNumber ); } else { CreateStackNumber( i, nStackNumber ); } } else { if( m_pStackNum[i] ) { DeleteStackNumber( i ); } } } else { ClearInventorySlot( i, m_nInvenPage ); } } if( m_nMouseOnIdx >= 0 && GetInfoWndManager()->GetInfoWndState() == CInfoWndManager::INFOWND_QUESTITEM ) { CNtlSobQuestItem* pItem = pInventory->GetQuestItemFromIdx( (RwUInt8)m_nMouseOnIdx ); if( pItem ) { CRectangle rtScreen = m_pBack->GetScreenRect(); GetInfoWndManager()->ShowInfoWindow( TRUE, CInfoWndManager::INFOWND_QUESTITEM, m_rtSlot[m_nMouseOnIdx].left + rtScreen.left, m_rtSlot[m_nMouseOnIdx].top + rtScreen.top, pItem, DIALOG_QUESTLIST ); } else { GetInfoWndManager()->ShowInfoWindow( FALSE ); } } } VOID CQuestInventoryGui::ClearInventory(VOID) { for( RwInt32 i = 0 ; i < QUESTINVENTORY_MAXROW ; ++i ) { for( RwInt32 j = 0 ; j < QUESTINVENTORY_MAXCOL ; ++j ) { ClearInventorySlot( j, i ); } } } VOID CQuestInventoryGui::ClearInventorySlot( RwInt32 nSlotIdx, RwInt32 nRow ) { NTL_ASSERT( nSlotIdx >= 0 && nSlotIdx < QUESTINVENTORY_MAXCOL, "CQuestInventoryGui::ClearInventorySlot : Invalid Col Index" ); NTL_ASSERT( nRow >= 0 && nRow < QUESTINVENTORY_MAXROW, "CQuestInventoryGui::ClearInventorySlot : Invalid Row Index" ); if( m_nInvenPage == nRow ) { m_surSlot[nSlotIdx].SetTexture( (gui::CTexture*)NULL ); DeleteStackNumber( nSlotIdx ); } m_surDisable[nSlotIdx][nRow].Show( FALSE ); } VOID CQuestInventoryGui::HandleEvents( RWS::CMsg& msg ) { if( msg.Id == g_EventSobInfoUpdate ) { SNtlEventSobInfoUpdate* pData = reinterpret_cast<SNtlEventSobInfoUpdate*>( msg.pData ); CNtlSobAvatar* pAvatar = GetNtlSLGlobal()->GetSobAvatar(); if( !pAvatar ) return; if( pData->hSerialId != pAvatar->GetSerialID() ) return; if( pData->uiUpdateType & EVENT_AIUT_QUESTITEM ) { UpdateData(); } } else if( msg.Id == g_EventPickedUpHide ) { RwInt32 nPlace = (RwInt32)msg.pData; if( nPlace != PLACE_QUESTBAG ) return; ShowPickedUp( FALSE ); } else if( msg.Id == g_EventEnableItemIcon ) { SDboEventEnableItemIcon* pData = reinterpret_cast<SDboEventEnableItemIcon*>( msg.pData ); if( pData->ePlace != PLACE_QUESTBAG ) return; ShowDisable( !pData->bEnable, pData->uiSlotIdx ); } else if( msg.Id == g_EventGameServerChangeOut ) { ClearInventory(); } } RwBool CQuestInventoryGui::CreateStackNumber( RwInt32 nSlotIdx, RwInt32 nValue ) { NTL_FUNCTION( "CQuestInventoryGui::CreateStackNubmer" ); CRectangle rect; rect.SetRect( m_rtSlot[nSlotIdx].left, m_rtSlot[nSlotIdx].bottom - DBOGUI_STACKNUM_HEIGHT, m_rtSlot[nSlotIdx].left + DBOGUI_STACKNUM_WIDTH, m_rtSlot[nSlotIdx].bottom ); m_pStackNum[nSlotIdx] = NTL_NEW gui::CStaticBox( rect, m_pBack, GetNtlGuiManager()->GetSurfaceManager(), DBOGUI_STACKNUM_ALIGN ); if( !m_pStackNum[nSlotIdx] ) NTL_RETURN( FALSE ); m_pStackNum[nSlotIdx]->CreateFontStd( DBOGUI_STACKNUM_FONT, DBOGUI_STACKNUM_FONTHEIGHT, DBOGUI_STACKNUM_FONTATTR ); m_pStackNum[nSlotIdx]->SetEffectMode( DBOGUI_STACKNUM_FONTEFFECTMODE ); m_pStackNum[nSlotIdx]->SetText( nValue ); m_pStackNum[nSlotIdx]->Enable( false ); NTL_RETURN( TRUE ); } VOID CQuestInventoryGui::DeleteStackNumber( RwInt32 nSlotIdx ) { if( m_pStackNum[nSlotIdx] ) NTL_DELETE( m_pStackNum[nSlotIdx] ); } VOID CQuestInventoryGui::SetSlotRectHardCode(VOID) { CRectangle rtScreen = m_pBack->GetScreenRect(); for( RwInt32 i = 0 ; i < QUESTINVENTORY_MAXCOL ; ++i ) { RwInt32 nCol = i % 5; RwInt32 nRow = i / 5; m_rtSlot[i].left = nCol * 40 + 13; m_rtSlot[i].top = nRow * 38 + 7; m_rtSlot[i].right = m_rtSlot[i].left + DBOGUI_ICON_SIZE; m_rtSlot[i].bottom = m_rtSlot[i].top + DBOGUI_ICON_SIZE; m_surSlot[i].SetRectWH( rtScreen.left + m_rtSlot[i].left, rtScreen.top + m_rtSlot[i].top, DBOGUI_ICON_SIZE, DBOGUI_ICON_SIZE ); for( RwInt32 j = 0 ; j < QUESTINVENTORY_MAXROW ; ++j ) { m_surDisable[i][j].SetSurface( GetNtlGuiManager()->GetSurfaceManager()->GetSurface( "GameCommon.srf", "srfSlotDisableEffect" ) ); m_surDisable[i][j].SetRectWH( m_rtSlot[i].left, m_rtSlot[i].top, DBOGUI_ICON_SIZE, DBOGUI_ICON_SIZE ); m_surDisable[i][j].Show( FALSE ); } } m_surFocusSlot.SetSurface( GetNtlGuiManager()->GetSurfaceManager()->GetSurface( "GameCommon.srf", "srfSlotFocusEffect" ) ); m_surFocusSlot.SetRectWH( 0, 0, DBOGUI_ICON_SIZE, DBOGUI_ICON_SIZE ); m_surPickedUp.SetSurface( GetNtlGuiManager()->GetSurfaceManager()->GetSurface( "GameCommon.srf", "srfSlotGrayedEffect" ) ); } VOID CQuestInventoryGui::ClickEffect( RwBool bPush, RwInt32 nSlotIdx /* = -1 */) { CRectangle rtScreen = m_pBack->GetScreenRect(); if( bPush ) { m_surSlot[nSlotIdx].SetRect( rtScreen.left + m_rtSlot[nSlotIdx].left + ICONPUSH_SIZEDIFF, rtScreen.top + m_rtSlot[nSlotIdx].top + ICONPUSH_SIZEDIFF, rtScreen.left + m_rtSlot[nSlotIdx].right - ICONPUSH_SIZEDIFF, rtScreen.top + m_rtSlot[nSlotIdx].bottom - ICONPUSH_SIZEDIFF ); } else if( m_nPushDownIdx >= 0 ) { m_surSlot[m_nPushDownIdx].SetRect( rtScreen.left + m_rtSlot[m_nPushDownIdx].left, rtScreen.top + m_rtSlot[m_nPushDownIdx].top, rtScreen.left + m_rtSlot[m_nPushDownIdx].right, rtScreen.top + m_rtSlot[m_nPushDownIdx].bottom ); } m_nPushDownIdx = nSlotIdx; } VOID CQuestInventoryGui::ShowPickedUp( RwBool bShow, RwInt32 nSlotIdx /* = -1 */) { if( bShow ) { CRectangle rtScreen = m_pBack->GetScreenRect(); m_nShowPickedUp = GetQuestItemIdxFromIdx( nSlotIdx ); m_surPickedUp.SetPosition( m_rtSlot[nSlotIdx].left + rtScreen.left, m_rtSlot[nSlotIdx].top + rtScreen.top ); } else { m_nShowPickedUp = -1; } } VOID CQuestInventoryGui::ShowFocus( RwBool bShow, RwInt32 nSlotIdx /* = -1 */) { if( bShow ) { CRectangle rtScreen = m_pBack->GetScreenRect(); m_nShowFocus = nSlotIdx; m_surFocusSlot.SetPosition( m_rtSlot[nSlotIdx].left + rtScreen.left, m_rtSlot[nSlotIdx].top + rtScreen.top ); } else { m_nShowFocus = nSlotIdx; } } VOID CQuestInventoryGui::ShowDisable( RwBool bShow, RwInt32 nSlotIdx ) { RwInt32 nRow = nSlotIdx / QUESTINVENTORY_MAXCOL; RwInt32 nCol = nSlotIdx % QUESTINVENTORY_MAXCOL; m_surDisable[nCol][nRow].Show( bShow ); } RwInt32 CQuestInventoryGui::GetChildSlotIdx( RwInt32 nX, RwInt32 nY ) { for( RwInt32 i = 0 ; i < QUESTINVENTORY_MAXCOL ; ++i ) { if( m_rtSlot[i].PtInRect( nX, nY ) ) return i; } return -1; } RwBool CQuestInventoryGui::IsEnablePickUp( RwInt32 nSlotIdx ) { if( nSlotIdx < 0 || nSlotIdx >= QUESTINVENTORY_MAXCOL ) return FALSE; if( m_surDisable[nSlotIdx][m_nInvenPage].IsShow() ) return FALSE; if( !GetIconMoveManager()->IsEnable() ) return FALSE; CNtlSobQuestItem* pItem = GetQuestItemFromIdx( nSlotIdx ); if( pItem ) return TRUE; return FALSE; } RwBool CQuestInventoryGui::IsEnablePutDown( RwInt32 nSlotIdx ) { if( nSlotIdx < 0 || nSlotIdx >= QUESTINVENTORY_MAXCOL ) return FALSE; if( m_surDisable[nSlotIdx][m_nInvenPage].IsShow() ) return FALSE; return TRUE; } VOID CQuestInventoryGui::UpdateInvenInfo(VOID) { m_pInvenInfo->Format( "%d / %d", m_nInvenPage + 1, QUESTINVENTORY_MAXROW ); if( m_nInvenPage <= 0 ) m_pPrevInvenBtn->ClickEnable( FALSE ); else m_pPrevInvenBtn->ClickEnable( TRUE ); if( m_nInvenPage + 1 >= QUESTINVENTORY_MAXROW ) m_pNextInvenBtn->ClickEnable( FALSE ); else m_pNextInvenBtn->ClickEnable( TRUE ); } CNtlSobQuestItem* CQuestInventoryGui::GetQuestItemFromIdx( RwInt32 nIdx ) { CNtlSobAvatar* pAvatar = GetNtlSLGlobal()->GetSobAvatar(); if( !pAvatar ) return NULL; return pAvatar->GetQuestInventory()->GetQuestItemFromIdx((RwUInt8)GetQuestItemIdxFromIdx(nIdx) ); } RwUInt32 CQuestInventoryGui::GetQuestItemSerialFromIdx( RwInt32 nIdx ) { CNtlSobAvatar* pAvatar = GetNtlSLGlobal()->GetSobAvatar(); if( !pAvatar ) return NULL; return pAvatar->GetQuestInventory()->GetQuestItemSerial( (RwUInt8)GetQuestItemIdxFromIdx( nIdx ) ); } RwInt32 CQuestInventoryGui::GetQuestItemIdxFromIdx( RwInt32 nIdx ) { return nIdx + ( m_nInvenPage * QUESTINVENTORY_MAXCOL ); } RwInt32 CQuestInventoryGui::GetCurrentPageFromIdx( RwInt32 nIdx ) { if( nIdx < 0 ) return -1; return nIdx / QUESTINVENTORY_MAXCOL; } VOID CQuestInventoryGui::OnMouseDown( const CKey& key ) { RwInt32 nClickIdx = GetChildSlotIdx( (RwInt32)key.m_fX, (RwInt32)key.m_fY ); if( nClickIdx >= 0 && !GetIconMoveManager()->IsActive() ) ClickEffect( TRUE, nClickIdx ); if( key.m_nID == UD_LEFT_BUTTON ) { if( GetIconMoveManager()->IsActive() ) { if( IsEnablePutDown( nClickIdx ) ) m_nLSelectedSlotIdx = nClickIdx; } else { if( IsEnablePickUp( nClickIdx ) ) m_nLSelectedSlotIdx = nClickIdx; } } else if( key.m_nID == UD_RIGHT_BUTTON ) { if( !GetIconMoveManager()->IsActive() ) { m_nRSelectedSlotIdx = nClickIdx; } } m_pBack->CaptureMouse(); if( m_nLSelectedSlotIdx >= 0 && m_nRSelectedSlotIdx >= 0 ) { m_nLSelectedSlotIdx = -1; m_nRSelectedSlotIdx = -1; ClickEffect( FALSE ); m_pBack->ReleaseMouse(); } } VOID CQuestInventoryGui::OnMouseUp( const CKey& key ) { RwInt32 nSlotIdx = GetChildSlotIdx( (RwInt32)key.m_fX, (RwInt32)key.m_fY ); ClickEffect( FALSE ); m_pBack->ReleaseMouse(); if( nSlotIdx < 0 || !m_pBack->IsVisibleTruly() ) { m_nLSelectedSlotIdx = -1; m_nRSelectedSlotIdx = -1; return; } if( key.m_nID == UD_LEFT_BUTTON ) { if( nSlotIdx == m_nLSelectedSlotIdx ) { if( GetIconMoveManager()->IsActive() ) { GetIconMoveManager()->IconMovePutDown( PLACE_QUESTBAG, INVALID_SERIAL_ID, GetQuestItemIdxFromIdx( nSlotIdx ) ); } else { CNtlSobQuestItem* pItem = GetQuestItemFromIdx( nSlotIdx ); if( pItem ) { if( GetIconMoveManager()->IconMovePickUp( pItem->GetSerialID(), PLACE_QUESTBAG, GetQuestItemIdxFromIdx( nSlotIdx ), 0, pItem->GetIcon()->GetImage() ) ) ShowPickedUp( TRUE, nSlotIdx ); } } } m_nLSelectedSlotIdx = -1; } else if( key.m_nID == UD_RIGHT_BUTTON ) { //if( nSlotIdx == m_nRSelectedSlotIdx ) //{ // CRectangle rtScreen = m_pBack->GetScreenRect(); // SERIAL_HANDLE hSerial = GetQuestItemSerialFromIdx( nSlotIdx ); // CDboEventGenerator::IconPopupShow( TRUE, hSerial, PLACE_QUESTBAG, GetQuestItemIdxFromIdx( nSlotIdx ), m_rtSlot[nSlotIdx].left + rtScreen.left, m_rtSlot[nSlotIdx].top + rtScreen.top ); //} m_nRSelectedSlotIdx = -1; } } VOID CQuestInventoryGui::OnMouseMove( RwInt32 nKey, RwInt32 nXPos, RwInt32 nYPos ) { RwInt32 nMouseOnIdx = GetChildSlotIdx( nXPos, nYPos ); if( nMouseOnIdx >= 0 ) { ShowFocus( TRUE, nMouseOnIdx ); if( m_nMouseOnIdx != nMouseOnIdx ) { CNtlSobQuestItem* pItem = GetQuestItemFromIdx( nMouseOnIdx ); if( pItem ) { CRectangle rtScreen = m_pBack->GetScreenRect(); CNtlSobQuestItemAttr* pAttr = reinterpret_cast<CNtlSobQuestItemAttr*>( pItem->GetSobAttr() ); GetInfoWndManager()->ShowInfoWindow( TRUE, CInfoWndManager::INFOWND_QUESTITEM, m_rtSlot[nMouseOnIdx].left + rtScreen.left, m_rtSlot[nMouseOnIdx].top + rtScreen.top, pAttr->GetQuestItemTbl(), DIALOG_QUESTLIST ); m_nMouseOnIdx = nMouseOnIdx; } if( nMouseOnIdx == m_nPushDownIdx ) ClickEffect( TRUE, nMouseOnIdx ); else if( m_nPushDownIdx >= 0 ) ClickEffect( FALSE ); } } else { ShowFocus( FALSE ); if( m_nMouseOnIdx >= 0 ) { GetInfoWndManager()->ShowInfoWindow( FALSE ); if( m_nPushDownIdx >= 0 ) ClickEffect( FALSE ); m_nMouseOnIdx = -1; } } } VOID CQuestInventoryGui::OnMouseOut( gui::CComponent* pComonent ) { ShowFocus( FALSE ); if( m_nMouseOnIdx >= 0 ) { GetInfoWndManager()->ShowInfoWindow( FALSE ); if( m_nPushDownIdx >= 0 ) ClickEffect( FALSE ); m_nMouseOnIdx = -1; } } VOID CQuestInventoryGui::OnPaint(VOID) { for( RwInt32 i = 0 ; i < QUESTINVENTORY_MAXCOL ; ++i ) { if( m_surSlot[i].GetTexture() ) m_surSlot[i].Render(); m_surDisable[i][m_nInvenPage].Render(); } if( GetCurrentPageFromIdx( m_nShowPickedUp ) == m_nInvenPage ) m_surPickedUp.Render(); if( m_nShowFocus >= 0 ) m_surFocusSlot.Render(); } VOID CQuestInventoryGui::OnMove( RwInt32 nXPos, RwInt32 nYPos ) { CRectangle rtScreen = m_pBack->GetScreenRect(); CRectangle rect; for( RwInt32 i = 0 ; i < QUESTINVENTORY_MAXCOL ; ++i ) { m_surSlot[i].SetPosition( rtScreen.left + m_rtSlot[i].left, rtScreen.top + m_rtSlot[i].top ); for( RwInt32 j = 0 ; j < QUESTINVENTORY_MAXROW ; ++j ) m_surDisable[i][j].SetPosition( rtScreen.left + m_rtSlot[i].left, rtScreen.top + m_rtSlot[i].top ); } if( m_nShowPickedUp >= 0 ) m_surPickedUp.SetPosition( rtScreen.left + m_rtSlot[GetQuestItemIdxFromIdx( m_nShowPickedUp )].left, rtScreen.top + m_rtSlot[GetQuestItemIdxFromIdx(m_nShowPickedUp)].top ); if( m_nShowFocus >= 0) m_surFocusSlot.SetPosition( rtScreen.left + m_rtSlot[m_nShowFocus].left, rtScreen.top + m_rtSlot[m_nShowFocus].top ); } VOID CQuestInventoryGui::OnNextInvenBtnClick( gui::CComponent* pComponent ) { if( ++m_nInvenPage >= QUESTINVENTORY_MAXROW ) m_nInvenPage = QUESTINVENTORY_MAXROW - 1; UpdateData(); UpdateInvenInfo(); } VOID CQuestInventoryGui::OnPrevInvenBtnClick( gui::CComponent* pComponent ) { if( --m_nInvenPage < 0 ) m_nInvenPage = 0; UpdateData(); UpdateInvenInfo(); } VOID CQuestInventoryGui::OnClickDiscardButton( gui::CComponent* pComponent ) { Logic_ItemDropConfirmProc(); }
094a477e5a71bd3535cad280d2302258c0015c2e
04b1803adb6653ecb7cb827c4f4aa616afacf629
/chrome/browser/sync/test/integration/two_client_wallet_sync_test.cc
eb9f3417f80a52723b50acf5268c7d2e5eef1be6
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
24,507
cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/macros.h" #include "chrome/browser/sync/test/integration/autofill_helper.h" #include "chrome/browser/sync/test/integration/sync_test.h" #include "chrome/browser/sync/test/integration/wallet_helper.h" #include "components/autofill/core/browser/data_model/autofill_metadata.h" #include "components/autofill/core/browser/data_model/autofill_profile.h" #include "components/autofill/core/browser/data_model/credit_card.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/browser/test_autofill_clock.h" #include "components/autofill/core/common/autofill_util.h" #include "components/sync/driver/profile_sync_service.h" #include "components/sync/test/fake_server/fake_server_http_post_provider.h" #include "net/base/network_change_notifier.h" #include "testing/gtest/include/gtest/gtest.h" namespace { using autofill::AutofillMetadata; using autofill::AutofillProfile; using autofill::CreditCard; using autofill::PersonalDataManager; using wallet_helper::CreateDefaultSyncPaymentsCustomerData; using wallet_helper::CreateSyncWalletAddress; using wallet_helper::CreateSyncWalletCard; using wallet_helper::GetCreditCard; using wallet_helper::GetLocalProfiles; using wallet_helper::GetPersonalDataManager; using wallet_helper::GetServerAddressesMetadata; using wallet_helper::GetServerCardsMetadata; using wallet_helper::GetServerCreditCards; using wallet_helper::GetServerProfiles; using wallet_helper::kDefaultBillingAddressID; using wallet_helper::UpdateServerAddressMetadata; using wallet_helper::UpdateServerCardMetadata; const char kDifferentBillingAddressId[] = "another address entity ID"; constexpr char kLocalBillingAddressId[] = "local billing address ID has size 36"; constexpr char kLocalBillingAddressId2[] = "another local billing address id wow"; static_assert(sizeof(kLocalBillingAddressId) == autofill::kLocalGuidSize + 1, "|kLocalBillingAddressId| has to have the right length to be " "considered a local guid"); static_assert(sizeof(kLocalBillingAddressId) == sizeof(kLocalBillingAddressId2), "|kLocalBillingAddressId2| has to have the right length to be " "considered a local guid"); const base::Time kArbitraryDefaultTime = base::Time::FromDoubleT(25); const base::Time kLaterTime = base::Time::FromDoubleT(5000); const base::Time kEvenLaterTime = base::Time::FromDoubleT(6000); class TwoClientWalletSyncTest : public UssWalletSwitchToggler, public SyncTest { public: TwoClientWalletSyncTest() : SyncTest(TWO_CLIENT) { InitWithDefaultFeatures(); } ~TwoClientWalletSyncTest() override {} // Needed for AwaitQuiescence(). bool TestUsesSelfNotifications() override { return true; } bool SetupSync() override { test_clock_.SetNow(kArbitraryDefaultTime); if (!SyncTest::SetupSync()) { return false; } // As this test does not use self notifications, wait for the metadata to // converge with the specialized wallet checker. return AutofillWalletChecker(0, 1).Wait(); } private: autofill::TestAutofillClock test_clock_; DISALLOW_COPY_AND_ASSIGN(TwoClientWalletSyncTest); }; IN_PROC_BROWSER_TEST_P(TwoClientWalletSyncTest, UpdateCreditCardMetadata) { GetFakeServer()->SetWalletData( {CreateSyncWalletCard(/*name=*/"card-1", /*last_four=*/"0001", kDefaultBillingAddressID), CreateDefaultSyncPaymentsCustomerData()}); ASSERT_TRUE(SetupSync()); // Grab the current card on the first client. std::vector<CreditCard*> credit_cards = GetServerCreditCards(0); ASSERT_EQ(1u, credit_cards.size()); CreditCard card = *credit_cards[0]; // Simulate using it -- increase both its use count and use date. ASSERT_EQ(1u, card.use_count()); card.set_use_count(2); card.set_use_date(kLaterTime); UpdateServerCardMetadata(0, card); // Wait for the change to propagate. EXPECT_TRUE(AutofillWalletChecker(0, 1).Wait()); credit_cards = GetServerCreditCards(1); EXPECT_EQ(1U, credit_cards.size()); EXPECT_EQ(2u, credit_cards[0]->use_count()); EXPECT_EQ(kLaterTime, credit_cards[0]->use_date()); credit_cards = GetServerCreditCards(0); EXPECT_EQ(1U, credit_cards.size()); EXPECT_EQ(2u, credit_cards[0]->use_count()); EXPECT_EQ(kLaterTime, credit_cards[0]->use_date()); } IN_PROC_BROWSER_TEST_P(TwoClientWalletSyncTest, UpdateCreditCardMetadataWhileNotSyncing) { GetFakeServer()->SetWalletData( {CreateSyncWalletCard(/*name=*/"card-1", /*last_four=*/"0001", kDefaultBillingAddressID), CreateDefaultSyncPaymentsCustomerData()}); ASSERT_TRUE(SetupSync()); // Sumulate going offline on both clients. fake_server::FakeServerHttpPostProvider::DisableNetwork(); // Grab the current card on the first client. std::vector<CreditCard*> credit_cards = GetServerCreditCards(0); ASSERT_EQ(1u, credit_cards.size()); CreditCard card = *credit_cards[0]; // Simulate using it -- increase both its use count and use date. ASSERT_EQ(1u, card.use_count()); card.set_use_count(2); card.set_use_date(kLaterTime); UpdateServerCardMetadata(0, card); // Simulate going online again. fake_server::FakeServerHttpPostProvider::EnableNetwork(); net::NetworkChangeNotifier::NotifyObserversOfNetworkChangeForTests( net::NetworkChangeNotifier::CONNECTION_ETHERNET); // Wait for the change to propagate. EXPECT_TRUE(AutofillWalletChecker(0, 1).Wait()); credit_cards = GetServerCreditCards(0); EXPECT_EQ(1U, credit_cards.size()); EXPECT_EQ(2u, credit_cards[0]->use_count()); EXPECT_EQ(kLaterTime, credit_cards[0]->use_date()); credit_cards = GetServerCreditCards(1); EXPECT_EQ(1U, credit_cards.size()); EXPECT_EQ(2u, credit_cards[0]->use_count()); EXPECT_EQ(kLaterTime, credit_cards[0]->use_date()); } IN_PROC_BROWSER_TEST_P(TwoClientWalletSyncTest, UpdateCreditCardMetadataConflictsWhileNotSyncing) { GetFakeServer()->SetWalletData( {CreateSyncWalletCard(/*name=*/"card-1", /*last_four=*/"0001", kDefaultBillingAddressID), CreateDefaultSyncPaymentsCustomerData()}); ASSERT_TRUE(SetupSync()); // Sumulate going offline on both clients. fake_server::FakeServerHttpPostProvider::DisableNetwork(); // Increase use stats on both clients, make use count higher on the first // client and use date higher on the second client. std::vector<CreditCard*> credit_cards = GetServerCreditCards(0); ASSERT_EQ(1u, credit_cards.size()); CreditCard card = *credit_cards[0]; ASSERT_EQ(1u, card.use_count()); card.set_use_count(3); card.set_use_date(kLaterTime); UpdateServerCardMetadata(0, card); credit_cards = GetServerCreditCards(1); ASSERT_EQ(1u, credit_cards.size()); card = *credit_cards[0]; ASSERT_EQ(1u, card.use_count()); card.set_use_count(2); card.set_use_date(kEvenLaterTime); UpdateServerCardMetadata(1, card); // Simulate going online again. fake_server::FakeServerHttpPostProvider::EnableNetwork(); net::NetworkChangeNotifier::NotifyObserversOfNetworkChangeForTests( net::NetworkChangeNotifier::CONNECTION_ETHERNET); // Wait for the clients to coverge and both resolve the conflicts by taking // maxima in both components. EXPECT_TRUE(AutofillWalletChecker(0, 1).Wait()); credit_cards = GetServerCreditCards(0); EXPECT_EQ(1U, credit_cards.size()); EXPECT_EQ(3u, credit_cards[0]->use_count()); EXPECT_EQ(kEvenLaterTime, credit_cards[0]->use_date()); credit_cards = GetServerCreditCards(1); EXPECT_EQ(1U, credit_cards.size()); EXPECT_EQ(3u, credit_cards[0]->use_count()); EXPECT_EQ(kEvenLaterTime, credit_cards[0]->use_date()); } IN_PROC_BROWSER_TEST_P(TwoClientWalletSyncTest, UpdateServerAddressMetadata) { GetFakeServer()->SetWalletData( {CreateSyncWalletCard(/*name=*/"card-1", /*last_four=*/"0001", kDefaultBillingAddressID), CreateSyncWalletAddress(/*name=*/"address-1", /*company=*/"Company-1"), CreateDefaultSyncPaymentsCustomerData()}); ASSERT_TRUE(SetupSync()); // Grab the current address on the first client. std::vector<AutofillProfile*> server_addresses = GetServerProfiles(0); ASSERT_EQ(1u, server_addresses.size()); AutofillProfile address = *server_addresses[0]; // Simulate using it -- increase both its use count and use date. ASSERT_EQ(1u, address.use_count()); address.set_use_count(2); address.set_use_date(kLaterTime); UpdateServerAddressMetadata(0, address); // Wait for the change to propagate. EXPECT_TRUE(AutofillWalletChecker(0, 1).Wait()); server_addresses = GetServerProfiles(1); EXPECT_EQ(1U, server_addresses.size()); EXPECT_EQ(2u, server_addresses[0]->use_count()); EXPECT_EQ(kLaterTime, server_addresses[0]->use_date()); server_addresses = GetServerProfiles(0); EXPECT_EQ(1U, server_addresses.size()); EXPECT_EQ(2u, server_addresses[0]->use_count()); EXPECT_EQ(kLaterTime, server_addresses[0]->use_date()); } IN_PROC_BROWSER_TEST_P(TwoClientWalletSyncTest, UpdateServerAddressMetadataWhileNotSyncing) { GetFakeServer()->SetWalletData( {CreateSyncWalletAddress(/*name=*/"address-1", /*company=*/"Company-1"), CreateDefaultSyncPaymentsCustomerData()}); ASSERT_TRUE(SetupSync()); // Sumulate going offline on both clients. fake_server::FakeServerHttpPostProvider::DisableNetwork(); // Grab the current address on the first client. std::vector<AutofillProfile*> server_addresses = GetServerProfiles(0); ASSERT_EQ(1u, server_addresses.size()); AutofillProfile address = *server_addresses[0]; // Simulate using it -- increase both its use count and use date. ASSERT_EQ(1u, address.use_count()); address.set_use_count(2); address.set_use_date(kLaterTime); UpdateServerAddressMetadata(0, address); // Simulate going online again. fake_server::FakeServerHttpPostProvider::EnableNetwork(); net::NetworkChangeNotifier::NotifyObserversOfNetworkChangeForTests( net::NetworkChangeNotifier::CONNECTION_ETHERNET); // Wait for the change to propagate. EXPECT_TRUE(AutofillWalletChecker(0, 1).Wait()); server_addresses = GetServerProfiles(1); EXPECT_EQ(1U, server_addresses.size()); EXPECT_EQ(2u, server_addresses[0]->use_count()); EXPECT_EQ(kLaterTime, server_addresses[0]->use_date()); server_addresses = GetServerProfiles(0); EXPECT_EQ(1U, server_addresses.size()); EXPECT_EQ(2u, server_addresses[0]->use_count()); EXPECT_EQ(kLaterTime, server_addresses[0]->use_date()); } IN_PROC_BROWSER_TEST_P(TwoClientWalletSyncTest, UpdateServerAddressMetadataConflictsWhileNotSyncing) { GetFakeServer()->SetWalletData( {CreateSyncWalletAddress(/*name=*/"address-1", /*company=*/"Company-1"), CreateDefaultSyncPaymentsCustomerData()}); ASSERT_TRUE(SetupSync()); // Sumulate going offline on both clients. fake_server::FakeServerHttpPostProvider::DisableNetwork(); // Increase use stats on both clients, make use count higher on the first // client and use date higher on the second client. std::vector<AutofillProfile*> server_addresses = GetServerProfiles(0); ASSERT_EQ(1u, server_addresses.size()); AutofillProfile address = *server_addresses[0]; ASSERT_EQ(1u, address.use_count()); address.set_use_count(3); address.set_use_date(kLaterTime); UpdateServerAddressMetadata(0, address); server_addresses = GetServerProfiles(1); ASSERT_EQ(1u, server_addresses.size()); address = *server_addresses[0]; ASSERT_EQ(1u, address.use_count()); address.set_use_count(2); address.set_use_date(kEvenLaterTime); UpdateServerAddressMetadata(1, address); // Simulate going online again. fake_server::FakeServerHttpPostProvider::EnableNetwork(); net::NetworkChangeNotifier::NotifyObserversOfNetworkChangeForTests( net::NetworkChangeNotifier::CONNECTION_ETHERNET); // Wait for the clients to coverge and both resolve the conflicts by taking // maxima in both components. EXPECT_TRUE(AutofillWalletChecker(0, 1).Wait()); server_addresses = GetServerProfiles(0); EXPECT_EQ(1U, server_addresses.size()); EXPECT_EQ(3u, server_addresses[0]->use_count()); EXPECT_EQ(kEvenLaterTime, server_addresses[0]->use_date()); server_addresses = GetServerProfiles(1); EXPECT_EQ(1U, server_addresses.size()); EXPECT_EQ(3u, server_addresses[0]->use_count()); EXPECT_EQ(kEvenLaterTime, server_addresses[0]->use_date()); } IN_PROC_BROWSER_TEST_P(TwoClientWalletSyncTest, UpdateCreditCardMetadataWithNewBillingAddressId) { GetFakeServer()->SetWalletData( {CreateSyncWalletCard(/*name=*/"card-1", /*last_four=*/"0001", /*billing_address_id=*/""), CreateDefaultSyncPaymentsCustomerData()}); ASSERT_TRUE(SetupSync()); // Grab the current card on the first client. std::vector<CreditCard*> credit_cards = GetServerCreditCards(0); ASSERT_EQ(1U, credit_cards.size()); CreditCard card = *credit_cards[0]; ASSERT_TRUE(card.billing_address_id().empty()); // Update the billing address. card.set_billing_address_id(kDefaultBillingAddressID); UpdateServerCardMetadata(0, card); EXPECT_TRUE(AutofillWalletChecker(0, 1).Wait()); // Make sure both clients have the updated billing_address_id. credit_cards = GetServerCreditCards(1); EXPECT_EQ(1U, credit_cards.size()); EXPECT_EQ(kDefaultBillingAddressID, credit_cards[0]->billing_address_id()); credit_cards = GetServerCreditCards(0); EXPECT_EQ(1U, credit_cards.size()); EXPECT_EQ(kDefaultBillingAddressID, credit_cards[0]->billing_address_id()); } IN_PROC_BROWSER_TEST_P(TwoClientWalletSyncTest, UpdateCreditCardMetadataWithChangedBillingAddressId) { GetFakeServer()->SetWalletData( {CreateSyncWalletCard(/*name=*/"card-1", /*last_four=*/"0001", kDefaultBillingAddressID), CreateDefaultSyncPaymentsCustomerData()}); ASSERT_TRUE(SetupSync()); // Grab the current card on the first client. std::vector<CreditCard*> credit_cards = GetServerCreditCards(0); ASSERT_EQ(1U, credit_cards.size()); CreditCard card = *credit_cards[0]; // Update the billing address. ASSERT_EQ(kDefaultBillingAddressID, card.billing_address_id()); card.set_billing_address_id(kDifferentBillingAddressId); UpdateServerCardMetadata(0, card); EXPECT_TRUE(AutofillWalletChecker(0, 1).Wait()); // Make sure both clients have the updated billing_address_id. credit_cards = GetServerCreditCards(1); EXPECT_EQ(1U, credit_cards.size()); EXPECT_EQ(kDifferentBillingAddressId, credit_cards[0]->billing_address_id()); credit_cards = GetServerCreditCards(0); EXPECT_EQ(1U, credit_cards.size()); EXPECT_EQ(kDifferentBillingAddressId, credit_cards[0]->billing_address_id()); } IN_PROC_BROWSER_TEST_P( TwoClientWalletSyncTest, UpdateCreditCardMetadataWithChangedBillingAddressId_RemoteToLocal) { GetFakeServer()->SetWalletData( {CreateSyncWalletCard(/*name=*/"card-1", /*last_four=*/"0001", kDefaultBillingAddressID), CreateDefaultSyncPaymentsCustomerData()}); ASSERT_TRUE(SetupSync()); // Grab the current card on the first client. std::vector<CreditCard*> credit_cards = GetServerCreditCards(0); ASSERT_EQ(1U, credit_cards.size()); CreditCard card = *credit_cards[0]; ASSERT_EQ(kDefaultBillingAddressID, card.billing_address_id()); // Update the billing address (replace a remote profile by a local profile). card.set_billing_address_id(kLocalBillingAddressId); UpdateServerCardMetadata(0, card); EXPECT_TRUE(AutofillWalletChecker(0, 1).Wait()); // Make sure both clients have the updated billing_address_id (local profile // wins). credit_cards = GetServerCreditCards(1); EXPECT_EQ(1U, credit_cards.size()); EXPECT_EQ(kLocalBillingAddressId, credit_cards[0]->billing_address_id()); credit_cards = GetServerCreditCards(0); EXPECT_EQ(1U, credit_cards.size()); EXPECT_EQ(kLocalBillingAddressId, credit_cards[0]->billing_address_id()); } IN_PROC_BROWSER_TEST_P( TwoClientWalletSyncTest, UpdateCreditCardMetadataWithChangedBillingAddressId_RemoteToLocalConflict) { GetFakeServer()->SetWalletData( {CreateSyncWalletCard(/*name=*/"card-1", /*last_four=*/"0001", kDefaultBillingAddressID), CreateDefaultSyncPaymentsCustomerData()}); ASSERT_TRUE(SetupSync()); // Sumulate going offline on both clients. fake_server::FakeServerHttpPostProvider::DisableNetwork(); // Update the billing address id on both clients to different local ids. std::vector<CreditCard*> credit_cards = GetServerCreditCards(0); ASSERT_EQ(1u, credit_cards.size()); CreditCard card = *credit_cards[0]; ASSERT_EQ(kDefaultBillingAddressID, card.billing_address_id()); card.set_billing_address_id(kLocalBillingAddressId); card.set_use_date(kLaterTime); // We treat the corner-case of merging data after initial sync (with // use_count==1) differently, set use-count to a higher value. card.set_use_count(2); UpdateServerCardMetadata(0, card); credit_cards = GetServerCreditCards(1); ASSERT_EQ(1u, credit_cards.size()); card = *credit_cards[0]; ASSERT_EQ(kDefaultBillingAddressID, card.billing_address_id()); card.set_billing_address_id(kLocalBillingAddressId2); card.set_use_date(kEvenLaterTime); // We treat the corner-case of merging data after initial sync (with // use_count==1) differently, set use-count to a higher value. card.set_use_count(2); UpdateServerCardMetadata(1, card); // Simulate going online again. fake_server::FakeServerHttpPostProvider::EnableNetwork(); net::NetworkChangeNotifier::NotifyObserversOfNetworkChangeForTests( net::NetworkChangeNotifier::CONNECTION_ETHERNET); // Wait for the clients to coverge and both resolve the conflicts by taking // maxima in both components. EXPECT_TRUE(AutofillWalletChecker(0, 1).Wait()); credit_cards = GetServerCreditCards(0); EXPECT_EQ(1U, credit_cards.size()); EXPECT_EQ(kLocalBillingAddressId2, credit_cards[0]->billing_address_id()); EXPECT_EQ(kEvenLaterTime, credit_cards[0]->use_date()); credit_cards = GetServerCreditCards(1); EXPECT_EQ(1U, credit_cards.size()); EXPECT_EQ(kLocalBillingAddressId2, credit_cards[0]->billing_address_id()); EXPECT_EQ(kEvenLaterTime, credit_cards[0]->use_date()); } // Flaky. http://crbug.com/917498 IN_PROC_BROWSER_TEST_P(TwoClientWalletSyncTest, DISABLED_ServerAddressConvertsToSameLocalAddress) { GetFakeServer()->SetWalletData( {CreateSyncWalletAddress(/*name=*/"address-1", /*company=*/"Company-1"), CreateDefaultSyncPaymentsCustomerData()}); ASSERT_TRUE(SetupSync()); // On top of expecting convergence on AutofillWalletChecker, expect // convergence on wallet metadata and on autofill profiles. EXPECT_TRUE(AutofillWalletMetadataSizeChecker(0, 1).Wait()); EXPECT_TRUE(AutofillProfileChecker(0, 1).Wait()); // Make sure both have has_converted true. std::vector<AutofillProfile*> server_addresses = GetServerProfiles(0); EXPECT_EQ(1u, server_addresses.size()); EXPECT_TRUE(server_addresses[0]->has_converted()); server_addresses = GetServerProfiles(1); EXPECT_EQ(1U, server_addresses.size()); EXPECT_TRUE(server_addresses[0]->has_converted()); // Make sure they have the same local profile. std::vector<AutofillProfile*> local_addresses_0 = GetLocalProfiles(0); ASSERT_EQ(1u, local_addresses_0.size()); // Make a copy in case it gets freed later. AutofillProfile local_address_0 = *local_addresses_0[0]; std::vector<AutofillProfile*> local_addresses_1 = GetLocalProfiles(1); ASSERT_EQ(1u, local_addresses_1.size()); EXPECT_TRUE(local_address_0.EqualsForSyncPurposes(*local_addresses_1[0])); } IN_PROC_BROWSER_TEST_P(TwoClientWalletSyncTest, DeleteServerCardMetadataWhenDataGetsRemoved) { GetFakeServer()->SetWalletData( {CreateSyncWalletCard(/*name=*/"card-1", /*last_four=*/"0001", kDefaultBillingAddressID), CreateSyncWalletAddress(/*name=*/"address-1", /*company=*/"Company-1"), CreateDefaultSyncPaymentsCustomerData()}); ASSERT_TRUE(SetupSync()); // Wait until sync settles (for the wallet metadata) before we change the // data again. ASSERT_TRUE(AwaitQuiescence()); // Grab the current address on the first client. std::vector<AutofillProfile*> server_addresses = GetServerProfiles(0); ASSERT_EQ(1u, server_addresses.size()); AutofillProfile address = *server_addresses[0]; // Remove the card from the data. GetFakeServer()->SetWalletData( {CreateSyncWalletAddress(/*name=*/"address-1", /*company=*/"Company-1"), CreateDefaultSyncPaymentsCustomerData()}); // Simulate using the address locally, only to force an update for wallet // cards when committing a change. ASSERT_EQ(1u, address.use_count()); address.set_use_count(2); address.set_use_date(kLaterTime); UpdateServerAddressMetadata(0, address); // Wait for the change to propagate. EXPECT_TRUE(AutofillWalletChecker(0, 1).Wait()); // Equal data does not mean equal metadata, there can be a metadata entity // without a data entity that gets ignored by the PDM-based // AutofillWalletChecker; we need to wait until the count of metadata entities // converges. EXPECT_TRUE(AutofillWalletMetadataSizeChecker(0, 1).Wait()); EXPECT_EQ(0U, GetServerCreditCards(0).size()); EXPECT_EQ(0U, GetServerCreditCards(1).size()); // Also check the DB directly that there is no _metadata_. EXPECT_EQ(0U, GetServerCardsMetadata(0).size()); EXPECT_EQ(0U, GetServerCardsMetadata(1).size()); // Double check that profiles data & metadata is intact. EXPECT_EQ(1U, GetServerProfiles(0).size()); EXPECT_EQ(1U, GetServerProfiles(1).size()); EXPECT_EQ(1U, GetServerAddressesMetadata(0).size()); EXPECT_EQ(1U, GetServerAddressesMetadata(1).size()); } IN_PROC_BROWSER_TEST_P(TwoClientWalletSyncTest, DeleteServerAddressMetadataWhenDataGetsRemoved) { GetFakeServer()->SetWalletData( {CreateSyncWalletCard(/*name=*/"card-1", /*last_four=*/"0001", kDefaultBillingAddressID), CreateSyncWalletAddress(/*name=*/"address-1", /*company=*/"Company-1"), CreateDefaultSyncPaymentsCustomerData()}); ASSERT_TRUE(SetupSync()); // Wait until sync settles (for the wallet metadata) before we change the // data again. ASSERT_TRUE(AwaitQuiescence()); // Grab the current card on the first client. std::vector<CreditCard*> credit_cards = GetServerCreditCards(0); ASSERT_EQ(1u, credit_cards.size()); CreditCard card = *credit_cards[0]; // Remove the address from the data. GetFakeServer()->SetWalletData( {CreateSyncWalletCard(/*name=*/"card-1", /*last_four=*/"0001", kDefaultBillingAddressID), CreateDefaultSyncPaymentsCustomerData()}); // Simulate using the card locally, only to force an update for wallet // addresses when committing a change. ASSERT_EQ(1u, card.use_count()); card.set_use_count(2); card.set_use_date(kLaterTime); UpdateServerCardMetadata(0, card); // Wait for the change to propagate. EXPECT_TRUE(AutofillWalletChecker(0, 1).Wait()); // Equal data does not mean equal metadata, there can be a metadata entity // without a data entity that gets ignored by the PDM-based // AutofillWalletChecker; we need to wait until the count of metadata entities // converges. EXPECT_TRUE(AutofillWalletMetadataSizeChecker(0, 1).Wait()); EXPECT_EQ(0U, GetServerProfiles(0).size()); EXPECT_EQ(0U, GetServerProfiles(1).size()); // Also check the DB directly that there is no _metadata_. EXPECT_EQ(0U, GetServerAddressesMetadata(0).size()); EXPECT_EQ(0U, GetServerAddressesMetadata(1).size()); // Double check that cards data & metadata is intact. EXPECT_EQ(1U, GetServerCreditCards(0).size()); EXPECT_EQ(1U, GetServerCreditCards(1).size()); EXPECT_EQ(1U, GetServerCardsMetadata(0).size()); EXPECT_EQ(1U, GetServerCardsMetadata(1).size()); } INSTANTIATE_TEST_SUITE_P(USS, TwoClientWalletSyncTest, ::testing::Values(false, true)); } // namespace
eedcf0469aaa8f17d2d16f078832d6ca6fdd07bb
6ed471f36e5188f77dc61cca24daa41496a6d4a0
/SDK/WeapPistol_ShotgunCameraShake_parameters.h
0c268acd064fa84a47a6a51d15199f5bd19f7455
[]
no_license
zH4x-SDK/zARKSotF-SDK
77bfaf9b4b9b6a41951ee18db88f826dd720c367
714730f4bb79c07d065181caf360d168761223f6
refs/heads/main
2023-07-16T22:33:15.140456
2021-08-27T13:40:06
2021-08-27T13:40:06
400,521,086
0
0
null
null
null
null
UTF-8
C++
false
false
726
h
#pragma once #include "../SDK.h" // Name: ARKSotF, Version: 178.8.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function WeapPistol_ShotgunCameraShake.WeapPistol_ShotgunCameraShake_C.ExecuteUbergraph_WeapPistol_ShotgunCameraShake struct UWeapPistol_ShotgunCameraShake_C_ExecuteUbergraph_WeapPistol_ShotgunCameraShake_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
77564811b930c7c0428fa7638e2e27e2723d0415
029cfe958db295a246460cbb1355c73482a2588b
/tests/concepts/has_multiplication_assignment.cpp
ac2db8bf4a636386a44aed2ded10110b1f50956c
[ "MIT" ]
permissive
SamuelAlonsoDev/lux
941bf543edfcc337d0d3830f4586c86969b1f962
268a9fabddb60a06e226d8bad27a5d5d7a29dcb2
refs/heads/master
2023-01-10T16:07:51.059604
2020-11-09T10:31:09
2020-11-09T10:31:09
310,223,392
2
0
null
null
null
null
UTF-8
C++
false
false
443
cpp
#include <iostream> #include <core/types.hpp> #include <concepts/has_multiplication_assignment.hpp> int main() { std::cout << std::boolalpha << "Do 'u8' and 's8' share a multiplication assignment '*=' operator? " << lux::concepts::has_multiplication_assignment<lux::u8, lux::s8> << "\nDoes 'u8' have with itself a multiplication assignment '*=' operator? " << lux::concepts::has_multiplication_assignment<lux::u8>; return 0; }
ed0d1ae691c2071be4feb164f68a1f674f83a242
761a023b55d9a4a74afc3391ff9ee75b28b1d59b
/src/test/csrc/difftest/difftest.cpp
4c6fd107868ea689b8cf270d3059fdfdfd8fbcc7
[]
no_license
ironmanfan/XiangShan
52aa17f214e5371a694f916db8b67920b5bc2607
330595df0edea4e1985bbfe68e2b0649ee5be2f5
refs/heads/master
2023-05-12T21:15:28.488375
2021-06-01T10:07:59
2021-06-01T10:07:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,449
cpp
#include "difftest.h" #include "goldenmem.h" #include "ram.h" static const char *reg_name[DIFFTEST_NR_REG+1] = { "$0", "ra", "sp", "gp", "tp", "t0", "t1", "t2", "s0", "s1", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11", "t3", "t4", "t5", "t6", "ft0", "ft1", "ft2", "ft3", "ft4", "ft5", "ft6", "ft7", "fs0", "fs1", "fa0", "fa1", "fa2", "fa3", "fa4", "fa5", "fa6", "fa7", "fs2", "fs3", "fs4", "fs5", "fs6", "fs7", "fs8", "fs9", "fs10", "fs11", "ft8", "ft9", "ft10", "ft11", "this_pc", "mstatus", "mcause", "mepc", "sstatus", "scause", "sepc", "satp", "mip", "mie", "mscratch", "sscratch", "mideleg", "medeleg", "mtval", "stval", "mtvec", "stvec", "mode", }; Difftest **difftest = NULL; int difftest_init() { // init global memory (used for consistency) ref_misc_put_gmaddr(pmem); difftest = new Difftest*[EMU_CORES]; for (int i = 0; i < EMU_CORES; i++) { difftest[i] = new Difftest(i); } return 0; } int difftest_state() { for (int i = 0; i < EMU_CORES; i++) { // if (difftest[i]->step(&diff[i], i)) { // trapCode = STATE_ABORT; // } // lastcommit[i] = max_cycle; // // update instr_cnt // uint64_t commit_count = (core_max_instr[i] >= diff[i].commit) ? diff[i].commit : core_max_instr[i]; // core_max_instr[i] -= commit_count; if (difftest[i]->get_trap_valid()) { return difftest[i]->get_trap_code(); } } return -1; } int difftest_step() { for (int i = 0; i < EMU_CORES; i++) { int ret = difftest[i]->step(); if (ret) { return ret; } } return 0; } Difftest::Difftest(int coreid) : id(coreid) { proxy = new DIFF_PROXY(coreid); state = new DiffState(); clear_step(); // nemu_this_pc = 0x80000000; // pc_retire_pointer = DEBUG_GROUP_TRACE_SIZE - 1; } int Difftest::step() { progress = false; ticks++; // TODO: update nemu/xs to fix this_pc comparison dut.csr.this_pc = dut.commit[0].pc; if (check_timeout()) { return 1; } do_first_instr_commit(); if (do_store_check()) { return 1; } if (do_golden_memory_update()) { return 1; } if (!has_commit) { return 0; } num_commit = 0; // reset num_commit this cycle to 0 // interrupt has the highest priority if (dut.event.interrupt) { dut.csr.this_pc = dut.event.exceptionPC; do_interrupt(); } else if(dut.event.exception) { // We ignored instrAddrMisaligned exception (0) for better debug interface // XiangShan should always support RVC, so instrAddrMisaligned will never happen // TODO: update NEMU, for now, NEMU will update pc when exception happen dut.csr.this_pc = dut.event.exceptionPC; do_exception(); } else { // TODO: is this else necessary? while (num_commit < DIFFTEST_COMMIT_WIDTH && dut.commit[num_commit].valid) { do_instr_commit(num_commit); dut.commit[num_commit].valid = 0; num_commit++; } } if (!progress) { return 0; } proxy->get_regs(ref_regs_ptr); if (num_commit > 0) { state->record_group(dut.commit[0].pc, num_commit); } // swap nemu_pc and ref.csr.this_pc for comparison uint64_t nemu_next_pc = ref.csr.this_pc; ref.csr.this_pc = nemu_this_pc; nemu_this_pc = nemu_next_pc; if (memcmp(dut_regs_ptr, ref_regs_ptr, DIFFTEST_NR_REG * sizeof(uint64_t))) { display(); for (int i = 0; i < DIFFTEST_NR_REG; i ++) { if (dut_regs_ptr[i] != ref_regs_ptr[i]) { printf("%7s different at pc = 0x%010lx, right= 0x%016lx, wrong = 0x%016lx\n", reg_name[i], ref.csr.this_pc, ref_regs_ptr[i], dut_regs_ptr[i]); } } return 1; } // return 0; } void Difftest::do_interrupt() { state->record_abnormal_inst(dut.commit[0].pc, dut.commit[0].inst, RET_INT, dut.event.interrupt); proxy->raise_intr(dut.event.interrupt | (1ULL << 63)); progress = true; } void Difftest::do_exception() { state->record_abnormal_inst(dut.event.exceptionPC, dut.commit[0].inst, RET_EXC, dut.event.exception); if (dut.event.exception == 12 || dut.event.exception == 13 || dut.event.exception == 15) { // printf("exception cause: %d\n", dut.event.exception); struct DisambiguationState ds; ds.exceptionNo = dut.event.exception; ds.mtval = dut.csr.mtval; ds.stval = dut.csr.stval; proxy->disambiguate_exec(&ds); } else { proxy->exec(1); } progress = true; } void Difftest::do_instr_commit(int i) { progress = true; last_commit = ticks; // store the writeback info to debug array state->record_inst(dut.commit[i].pc, dut.commit[i].inst, dut.commit[i].wen, dut.commit[i].wdest, dut.commit[i].wdata); // sync lr/sc reg status if (dut.commit[i].scFailed) { struct SyncState sync; sync.lrscValid = 0; sync.lrscAddr = 0; proxy->set_mastatus((uint64_t*)&sync); // sync lr/sc microarchitectural regs } // MMIO accessing should not be a branch or jump, just +2/+4 to get the next pc // to skip the checking of an instruction, just copy the reg state to reference design if (dut.commit[i].skip) { proxy->get_regs(ref_regs_ptr); ref.csr.this_pc += dut.commit[i].isRVC ? 2 : 4; if (dut.commit[i].wen && dut.commit[i].wdest != 0) { // TODO: FPR ref_regs_ptr[dut.commit[i].wdest] = dut.commit[i].wdata; } proxy->set_regs(ref_regs_ptr); return; } // single step exec proxy->exec(1); // IPF, LPF, SPF // if (dut.event.exception == 12 || dut.event.exception == 13 || dut.event.exception == 15) { // printf("exception cause: %ld\n", dut.event.exception); // struct DisambiguationState ds; // ds.exceptionNo = dut.event.exception; // ds.mtval = dut.csr.mtval; // ds.stval = dut.csr.stval; // proxy->disambiguate_exec(&ds); // } // Handle load instruction carefully for SMP if (dut.load[i].fuType == 0xC || dut.load[i].fuType == 0xF) { proxy->get_regs(ref_regs_ptr); if (dut.commit[i].wen && ref_regs_ptr[dut.commit[i].wdest] != dut.commit[i].wdata) { // printf("---[DIFF Core%d] This load instruction gets rectified!\n", this->id); // printf("--- ltype: 0x%x paddr: 0x%lx wen: 0x%x wdst: 0x%x wdata: 0x%lx pc: 0x%lx\n", dut.load[i].opType, dut.load[i].paddr, dut.commit[i].wen, dut.commit[i].wdest, dut.commit[i].wdata, dut.commit[i].pc); uint64_t golden; int len = 0; if (dut.load[i].fuType == 0xC) { switch (dut.load[i].opType) { case 0: len = 1; break; case 1: len = 2; break; case 2: len = 4; break; case 3: len = 8; break; case 4: len = 1; break; case 5: len = 2; break; case 6: len = 4; break; default: printf("Unknown fuOpType: 0x%x\n", dut.load[i].opType); } } else { // dut.load[i].fuType == 0xF if (dut.load[i].opType % 2 == 0) { len = 4; } else { // dut.load[i].opType % 2 == 1 len = 8; } } read_goldenmem(dut.load[i].paddr, &golden, len); if (dut.load[i].fuType == 0xC) { switch (dut.load[i].opType) { case 0: golden = (int64_t)(int8_t)golden; break; case 1: golden = (int64_t)(int16_t)golden; break; case 2: golden = (int64_t)(int32_t)golden; break; } } // printf("--- golden: 0x%lx original: 0x%lx\n", golden, ref_regs_ptr[dut.commit[i].wdest]); if (golden == dut.commit[i].wdata) { proxy->memcpy_from_dut(dut.load[i].paddr, &golden, len); if (dut.commit[i].wdest != 0) { ref_regs_ptr[dut.commit[i].wdest] = dut.commit[i].wdata; proxy->set_regs(ref_regs_ptr); } } else if (dut.load[i].fuType == 0xF) { // atomic instr carefully handled proxy->memcpy_from_dut(dut.load[i].paddr, &golden, len); if (dut.commit[i].wdest != 0) { ref_regs_ptr[dut.commit[i].wdest] = dut.commit[i].wdata; proxy->set_regs(ref_regs_ptr); } } else { // goldenmem check failed as well, raise error printf("--- SMP difftest mismatch!\n"); printf("--- Trying to probe local data of another core\n"); uint64_t buf; difftest[(EMU_CORES-1) - this->id]->proxy->memcpy_from_ref(&buf, dut.load[i].paddr, len); printf("--- content: %lx\n", buf); } } } } void Difftest::do_first_instr_commit() { if (!has_commit && dut.commit[0].valid && dut.commit[0].pc == 0x80000000) { // when dut commits the first instruction, its state should be copied to ref, // because dut is probably randomly initialized. // int first_instr_commit = dut_ptr->io_difftest_commit && dut_ptr->io_difftest_thisPC == 0x80000000u; has_commit = 1; nemu_this_pc = dut.csr.this_pc; proxy->memcpy_from_dut(0x80000000, get_img_start(), get_img_size()); proxy->set_regs(dut_regs_ptr); printf("The first instruction of core %d has commited. Difftest enabled. \n", id); } } int Difftest::do_store_check() { for (int i = 0; i < DIFFTEST_STORE_WIDTH; i++) { if (!dut.store[i].valid) { return 0; } auto addr = dut.store[i].addr; auto data = dut.store[i].data; auto mask = dut.store[i].mask; if (proxy->store_commit(&addr, &data, &mask)) { display(); printf("Mismatch for store commits %d: \n", i); printf(" REF commits addr 0x%lx, data 0x%lx, mask 0x%x\n", addr, data, mask); printf(" DUT commits addr 0x%lx, data 0x%lx, mask 0x%x\n", dut.store[i].addr, dut.store[i].data, dut.store[i].mask); return 1; } dut.store[i].valid = 0; } return 0; } inline int handle_atomic(int coreid, uint64_t atomicAddr, uint64_t atomicData, uint64_t atomicMask, uint8_t atomicFuop, uint64_t atomicOut) { // We need to do atmoic operations here so as to update goldenMem if (!(atomicMask == 0xf || atomicMask == 0xf0 || atomicMask == 0xff)) { printf("Unrecognized mask: %lx\n", atomicMask); return 1; } if (atomicMask == 0xff) { uint64_t rs = atomicData; // rs2 uint64_t t = atomicOut; // original value uint64_t ret; uint64_t mem; read_goldenmem(atomicAddr, &mem, 8); if (mem != t && atomicFuop != 007 && atomicFuop != 003) { // ignore sc_d & lr_d printf("Core %d atomic instr mismatch goldenMem, mem: 0x%lx, t: 0x%lx, op: 0x%x, addr: 0x%lx\n", coreid, mem, t, atomicFuop, atomicAddr); return 1; } switch (atomicFuop) { case 002: case 003: ret = t; break; case 006: case 007: ret = rs; break; case 012: case 013: ret = rs; break; case 016: case 017: ret = t+rs; break; case 022: case 023: ret = (t^rs); break; case 026: case 027: ret = t & rs; break; case 032: case 033: ret = t | rs; break; case 036: case 037: ret = ((int64_t)t < (int64_t)rs)? t : rs; break; case 042: case 043: ret = ((int64_t)t > (int64_t)rs)? t : rs; break; case 046: case 047: ret = (t < rs) ? t : rs; break; case 052: case 053: ret = (t > rs) ? t : rs; break; default: printf("Unknown atomic fuOpType: 0x%x\n", atomicFuop); } update_goldenmem(atomicAddr, &ret, atomicMask, 8); } if (atomicMask == 0xf || atomicMask == 0xf0) { uint32_t rs = (uint32_t)atomicData; // rs2 uint32_t t = (uint32_t)atomicOut; // original value uint32_t ret; uint32_t mem; uint64_t mem_raw; uint64_t ret_sel; atomicAddr = (atomicAddr & 0xfffffffffffffff8); read_goldenmem(atomicAddr, &mem_raw, 8); if (atomicMask == 0xf) mem = (uint32_t)mem_raw; else mem = (uint32_t)(mem_raw >> 32); if (mem != t && atomicFuop != 006 && atomicFuop != 002) { // ignore sc_w & lr_w printf("Core %d atomic instr mismatch goldenMem, rawmem: 0x%lx mem: 0x%x, t: 0x%x, op: 0x%x, addr: 0x%lx\n", coreid, mem_raw, mem, t, atomicFuop, atomicAddr); return 1; } switch (atomicFuop) { case 002: case 003: ret = t; break; case 006: case 007: ret = rs; break; // TODO case 012: case 013: ret = rs; break; case 016: case 017: ret = t+rs; break; case 022: case 023: ret = (t^rs); break; case 026: case 027: ret = t & rs; break; case 032: case 033: ret = t | rs; break; case 036: case 037: ret = ((int32_t)t < (int32_t)rs)? t : rs; break; case 042: case 043: ret = ((int32_t)t > (int32_t)rs)? t : rs; break; case 046: case 047: ret = (t < rs) ? t : rs; break; case 052: case 053: ret = (t > rs) ? t : rs; break; default: printf("Unknown atomic fuOpType: 0x%x\n", atomicFuop); } ret_sel = ret; if (atomicMask == 0xf0) ret_sel = (ret_sel << 32); update_goldenmem(atomicAddr, &ret_sel, atomicMask, 8); } return 0; } int Difftest::do_golden_memory_update() { // Update Golden Memory info if (dut.sbuffer.resp) { dut.sbuffer.resp = 0; update_goldenmem(dut.sbuffer.addr, dut.sbuffer.data, dut.sbuffer.mask, 64); } if (dut.atomic.resp) { dut.atomic.resp = 0; int ret = handle_atomic(id, dut.atomic.addr, dut.atomic.data, dut.atomic.mask, dut.atomic.fuop, dut.atomic.out); if (ret) return ret; } return 0; } int Difftest::check_timeout() { // check whether there're any commits since the simulation starts if (!has_commit && ticks > last_commit + firstCommit_limit) { eprintf("No instruction commits for %lu cycles of core %d. Please check the first instruction.\n", firstCommit_limit, id); eprintf("Note: The first instruction may lie in 0x10000000 which may executes and commits after 500 cycles.\n"); eprintf(" Or the first instruction may lie in 0x80000000 which may executes and commits after 2000 cycles.\n"); display(); return 1; } // check whether there're any commits in the last 5000 cycles if (has_commit && ticks > last_commit + stuck_limit) { eprintf("No instruction of core %d commits for %lu cycles, maybe get stuck\n" "(please also check whether a fence.i instruction requires more than %lu cycles to flush the icache)\n", id, stuck_limit, stuck_limit); eprintf("Let REF run one more instruction.\n"); proxy->exec(1); display(); return 1; } return 0; } void Difftest::raise_trap(int trapCode) { dut.trap.valid = 1; dut.trap.code = trapCode; } void Difftest::clear_step() { dut.trap.valid = 0; for (int i = 0; i < DIFFTEST_COMMIT_WIDTH; i++) { dut.commit[i].valid = 0; } dut.sbuffer.resp = 0; for (int i = 0; i < DIFFTEST_STORE_WIDTH; i++) { dut.store[i].valid = 0; } for (int i = 0; i < DIFFTEST_LOAD_WIDTH; i++) { dut.load[i].valid = 0; } dut.atomic.resp = 0; dut.ptw.resp = 0; } void Difftest::display() { state->display(this->id); printf("\n============== REF Regs ==============\n"); fflush(stdout); proxy->isa_reg_display(); printf("priviledgeMode: %lu\n", dut.csr.priviledgeMode); } void DiffState::display(int coreid) { printf("\n============== Commit Group Trace (Core %d) ==============\n", coreid); for (int j = 0; j < DEBUG_GROUP_TRACE_SIZE; j++) { printf("commit group [%x]: pc %010lx cmtcnt %d %s\n", j, retire_group_pc_queue[j], retire_group_cnt_queue[j], (j==((retire_group_pointer-1)%DEBUG_INST_TRACE_SIZE))?"<--":""); } printf("\n============== Commit Instr Trace ==============\n"); for (int j = 0; j < DEBUG_INST_TRACE_SIZE; j++) { switch(retire_inst_type_queue[j]){ case RET_NORMAL: printf("commit inst [%x]: pc %010lx inst %08x wen %x dst %08x data %016lx %s\n", j, retire_inst_pc_queue[j], retire_inst_inst_queue[j], retire_inst_wen_queue[j]!=0, retire_inst_wdst_queue[j], retire_inst_wdata_queue[j], (j==((retire_inst_pointer-1)%DEBUG_INST_TRACE_SIZE))?"<--":""); break; case RET_EXC: printf("exception [%x]: pc %010lx inst %08x cause %016lx %s\n", j, retire_inst_pc_queue[j], retire_inst_inst_queue[j], retire_inst_wdata_queue[j], (j==((retire_inst_pointer-1)%DEBUG_INST_TRACE_SIZE))?"<--":""); break; case RET_INT: printf("interrupt [%x]: pc %010lx inst %08x cause %016lx %s\n", j, retire_inst_pc_queue[j], retire_inst_inst_queue[j], retire_inst_wdata_queue[j], (j==((retire_inst_pointer-1)%DEBUG_INST_TRACE_SIZE))?"<--":""); break; } } fflush(stdout); } DiffState::DiffState(int history_length) { }
d392719c60feee3f9e604ba6eb92a0812ba66e40
0fcd4d2a1007803105fb7d46d50fc75de974f881
/lab-6/part-B/lab-6B.cpp
1a2fa6093c2249544492a05dd5a8166233960942
[ "MIT" ]
permissive
tejashah88/COMSC-165
c4cda158e7245d03dbd07edc44bd3c356af53f18
30efa87130bfa2dc61e98dd2cbebc9f9f6d7d9d5
refs/heads/master
2020-04-11T17:28:25.849019
2018-12-16T02:52:52
2018-12-16T02:52:52
161,962,194
0
0
null
null
null
null
UTF-8
C++
false
false
1,411
cpp
/* * Name: Lab 6B * Class: COMSC-165 * Date: 10/26/2018 * Author: Tejas Shah * Description: Prompts the user to read a character at the requested location in the input file until he/she is done */ #include <iostream> #include <string> #include <iomanip> #include <fstream> using namespace std; int readInt(); char readChar(ifstream &file, int location); char readChar(ifstream &file, int location) { if (file.eof()) { file.clear(); file.ignore(); } file.seekg(location, ios::cur); char input; file.get(input); return input; } int readInt() { int input; cin >> input; while (cin.fail()) { cin.clear(); cin.ignore(); cin >> input; } cin.ignore(); return input; } int main() { ifstream file("Lab6BInputProverb.txt"); int currentLoc = file.tellg(); cout << "Current read location: " << currentLoc << endl << endl; bool isRunning = true; while (isRunning) { cout << "Ennter read location or -1 to exit: "; currentLoc = readInt(); if (currentLoc < 0) { isRunning = false; continue; } cout << "Current read location: " << file.tellg() << endl; cout << "Character at location: '" << readChar(file, currentLoc) << "'" << endl; cout << "New read location: " << file.tellg() << endl << endl; } return 0; }
700b149ec7fe2198900f08241abb8a2348c2b35b
c7b270492e0348214dd9d65fa651280506d09bd8
/ORCA on-off/hectorquad/src/Rrt.hpp
569c393e5aa3a914ff5570801f2544ad3c6ba3ce
[]
no_license
erenerisken/drone_motion
10f54eca3df9fdb2a4a56f9a3e0fc1194cc4987e
727dcc5759963e5f84873557606b719cabdc5f1c
refs/heads/master
2021-07-25T05:13:03.691489
2020-07-08T06:03:02
2020-07-08T06:03:02
196,026,836
6
0
null
null
null
null
UTF-8
C++
false
false
5,385
hpp
#ifndef _RRT_HPP_ #define _RRT_HPP_ #include <ros/ros.h> #include "motionUtilities.hpp" #include <stack> typedef std::pair<Coordinate, int> RrtNode; namespace Rrt { std::vector<Obstacle*> *obs; Coordinate start, end; double stepSize, xStart, yStart, xEnd, yEnd; std::vector<RrtNode> startNodes, endNodes; void init(const Coordinate &startCoord, const Coordinate &endCoord, double step, std::vector<Obstacle*> &obstacles) { srand(time(NULL)); start = startCoord; end = endCoord; obs = &obstacles; stepSize = step; startNodes.push_back(RrtNode(start, -1)); endNodes.push_back(RrtNode(end, -1)); } std::vector<Coordinate> rrtGetMap(double xS, double xE, double yS, double yE) { xStart = xS; yStart = yS; xEnd = xE; yEnd = yE; bool finished = false; while(!finished) { double randX = xStart + (double)rand() / (double)RAND_MAX * (xEnd - xStart); double randY = yStart + (double)rand() / (double)RAND_MAX * (yEnd - yStart); Coordinate randomPoint(randX, randY, HEIGHT); int closestStart = 0, closestEnd = 0; Coordinate closestStartPoint = startNodes[0].first; Coordinate closestEndPoint = endNodes[0].first; for(int i = 1; i<startNodes.size(); i++) { if(dist(startNodes[i].first, randomPoint) < dist(closestStartPoint, randomPoint)) { closestStart = i; closestStartPoint = startNodes[i].first; } } for(int i = 1; i<endNodes.size(); i++) { if(dist(endNodes[i].first, randomPoint) < dist(closestEndPoint, randomPoint)) { closestEnd = i; closestEndPoint = endNodes[i].first; } } double magStart = std::min(stepSize, dist(closestStartPoint, randomPoint)); double magEnd = std::min(stepSize, dist(closestEndPoint, randomPoint)); double newStartX = closestStartPoint.x + magStart * (randomPoint.x - closestStartPoint.x) / dist(closestStartPoint, randomPoint); double newStartY = closestStartPoint.y + magStart * (randomPoint.y - closestStartPoint.y) / dist(closestStartPoint, randomPoint); double newEndX = closestEndPoint.x + magEnd * (randomPoint.x - closestEndPoint.x) / dist(closestEndPoint, randomPoint); double newEndY = closestEndPoint.y + magStart * (randomPoint.y - closestEndPoint.y) / dist(closestEndPoint, randomPoint); Coordinate newStart(newStartX, newStartY, HEIGHT), newEnd(newEndX, newEndY, HEIGHT); bool inBoundStart = false, inBoundEnd = false; for(auto i = obs->begin(); i != obs->end(); i++) { inBoundStart = inBoundStart || (*i)->inObstacle(newStart); inBoundEnd = inBoundEnd || (*i)->inObstacle(newEnd); } if(!inBoundStart) { startNodes.push_back(RrtNode(newStart, closestStart)); } if(!inBoundEnd) { endNodes.push_back(RrtNode(newEnd, closestEnd)); } if(inBoundEnd || inBoundStart) { continue; } if(dist(newStart, newEnd) < stepSize) { finished = true; } //finished güncelle } std::stack<Coordinate> s; std::vector<Coordinate> ret; int cur = startNodes.size() - 1; while(cur != -1) { s.push(startNodes[cur].first); cur = startNodes[cur].second; } while(!s.empty()) { ret.push_back(s.top()); s.pop(); } cur = endNodes.size() - 1; while(cur != -1) { ret.push_back(endNodes[cur].first); cur = endNodes[cur].second; } ret[0].z += INITIAL_HEIGHT; ret = planningUtilities::filterCoordinates(ret, obs); return ret; } } #endif
133ccecb40882096f5a78f2dc757178cd76b897c
bc16d26b3a1db2977b536dd370861e01921ee3e8
/dune/Utilities/SignalShapingServiceDUNE_service.cc
9d7000557e4fbb2c4dab7e67ddeb00a056fe7dc8
[]
no_license
jhugon/dunetpc
b6f5cb420492753b9d1890bcf526d26f7e425bb2
13f26ab523ff9e350f7e93a9d6e49302a2b48843
refs/heads/master
2020-04-12T09:41:08.977996
2016-09-02T00:34:26
2016-09-02T00:34:26
63,374,613
0
0
null
null
null
null
UTF-8
C++
false
false
27,102
cc
//////////////////////////////////////////////////////////////////////// /// \file SignalShapingServiceDUNE_service.cc /// \author H. Greenlee //////////////////////////////////////////////////////////////////////// #include "dune/Utilities/SignalShapingServiceDUNE.h" #include "art/Framework/Services/Registry/ServiceHandle.h" #include "messagefacility/MessageLogger/MessageLogger.h" #include "cetlib/exception.h" #include "larcore/Geometry/Geometry.h" #include "larcore/Geometry/TPCGeo.h" #include "larcore/Geometry/PlaneGeo.h" #include "lardata/DetectorInfoServices/DetectorPropertiesService.h" #include "lardata/DetectorInfoServices/DetectorClocksService.h" #include "lardata/Utilities/LArFFT.h" #include "TFile.h" //---------------------------------------------------------------------- // Constructor. util::SignalShapingServiceDUNE::SignalShapingServiceDUNE(const fhicl::ParameterSet& pset, art::ActivityRegistry& /* reg */) : fInit(false) { reconfigure(pset); } //---------------------------------------------------------------------- // Destructor. util::SignalShapingServiceDUNE::~SignalShapingServiceDUNE() {} //---------------------------------------------------------------------- // Reconfigure method. void util::SignalShapingServiceDUNE::reconfigure(const fhicl::ParameterSet& pset) { // Reset initialization flag. fInit = false; // Reset kernels. fColSignalShaping.Reset(); fIndUSignalShaping.Reset(); fIndVSignalShaping.Reset(); // Fetch fcl parameters. fNFieldBins = pset.get<int>("FieldBins"); fCol3DCorrection = pset.get<double>("Col3DCorrection"); fInd3DCorrection = pset.get<double>("Ind3DCorrection"); fColFieldRespAmp = pset.get<double>("ColFieldRespAmp"); fIndUFieldRespAmp = pset.get<double>("IndUFieldRespAmp"); fIndVFieldRespAmp = pset.get<double>("IndVFieldRespAmp"); fDeconNorm = pset.get<double>("DeconNorm"); fADCPerPCAtLowestASICGain = pset.get<double>("ADCPerPCAtLowestASICGain"); fASICGainInMVPerFC = pset.get<std::vector<double> >("ASICGainInMVPerFC"); fShapeTimeConst = pset.get<std::vector<double> >("ShapeTimeConst"); fNoiseFactVec = pset.get<std::vector<DoubleVec> >("NoiseFactVec"); fInputFieldRespSamplingPeriod = pset.get<double>("InputFieldRespSamplingPeriod"); fFieldResponseTOffset = pset.get<std::vector<double> >("FieldResponseTOffset"); fCalibResponseTOffset = pset.get<std::vector<double> >("CalibResponseTOffset"); fUseFunctionFieldShape= pset.get<bool>("UseFunctionFieldShape"); fUseHistogramFieldShape = pset.get<bool>("UseHistogramFieldShape"); fGetFilterFromHisto= pset.get<bool>("GetFilterFromHisto"); // Construct parameterized collection filter function. if(!fGetFilterFromHisto) { mf::LogInfo("SignalShapingServiceDUNE") << "Getting Filter from .fcl file"; std::string colFilt = pset.get<std::string>("ColFilter"); std::vector<double> colFiltParams = pset.get<std::vector<double> >("ColFilterParams"); fColFilterFunc = new TF1("colFilter", colFilt.c_str()); for(unsigned int i=0; i<colFiltParams.size(); ++i) fColFilterFunc->SetParameter(i, colFiltParams[i]); // Construct parameterized induction filter function. std::string indUFilt = pset.get<std::string>("IndUFilter"); std::vector<double> indUFiltParams = pset.get<std::vector<double> >("IndUFilterParams"); fIndUFilterFunc = new TF1("indUFilter", indUFilt.c_str()); for(unsigned int i=0; i<indUFiltParams.size(); ++i) fIndUFilterFunc->SetParameter(i, indUFiltParams[i]); std::string indVFilt = pset.get<std::string>("IndVFilter"); std::vector<double> indVFiltParams = pset.get<std::vector<double> >("IndVFilterParams"); fIndVFilterFunc = new TF1("indVFilter", indVFilt.c_str()); for(unsigned int i=0; i<indVFiltParams.size(); ++i) fIndVFilterFunc->SetParameter(i, indVFiltParams[i]); } else { std::string histoname = pset.get<std::string>("FilterHistoName"); mf::LogInfo("SignalShapingServiceDUNE") << " using filter from .root file "; int fNPlanes=3; // constructor decides if initialized value is a path or an environment variable std::string fname; cet::search_path sp("FW_SEARCH_PATH"); sp.find_file(pset.get<std::string>("FilterFunctionFname"), fname); TFile * in=new TFile(fname.c_str(),"READ"); for(int i=0;i<fNPlanes;i++){ TH1D * temp=(TH1D *)in->Get(Form(histoname.c_str(),i)); fFilterHist[i]=new TH1D(Form(histoname.c_str(),i),Form(histoname.c_str(),i),temp->GetNbinsX(),0,temp->GetNbinsX()); temp->Copy(*fFilterHist[i]); } in->Close(); } ///////////////////////////////////// if(fUseFunctionFieldShape) { std::string colField = pset.get<std::string>("ColFieldShape"); std::vector<double> colFieldParams = pset.get<std::vector<double> >("ColFieldParams"); fColFieldFunc = new TF1("colField", colField.c_str()); for(unsigned int i=0; i<colFieldParams.size(); ++i) fColFieldFunc->SetParameter(i, colFieldParams[i]); // Construct parameterized induction filter function. std::string indUField = pset.get<std::string>("IndUFieldShape"); std::vector<double> indUFieldParams = pset.get<std::vector<double> >("IndUFieldParams"); fIndUFieldFunc = new TF1("indUField", indUField.c_str()); for(unsigned int i=0; i<indUFieldParams.size(); ++i) fIndUFieldFunc->SetParameter(i, indUFieldParams[i]); // Warning, last parameter needs to be multiplied by the FFTSize, in current version of the code, std::string indVField = pset.get<std::string>("IndVFieldShape"); std::vector<double> indVFieldParams = pset.get<std::vector<double> >("IndVFieldParams"); fIndVFieldFunc = new TF1("indVField", indVField.c_str()); for(unsigned int i=0; i<indVFieldParams.size(); ++i) fIndVFieldFunc->SetParameter(i, indVFieldParams[i]); // Warning, last parameter needs to be multiplied by the FFTSize, in current version of the code, } else if ( fUseHistogramFieldShape ) { mf::LogInfo("SignalShapingServiceDUNE") << " using the field response provided from a .root file " ; int fNPlanes = 3; // constructor decides if initialized value is a path or an environment variable std::string fname; cet::search_path sp("FW_SEARCH_PATH"); sp.find_file( pset.get<std::string>("FieldResponseFname"), fname ); std::string histoname = pset.get<std::string>("FieldResponseHistoName"); std::unique_ptr<TFile> fin(new TFile(fname.c_str(), "READ")); if ( !fin->IsOpen() ) throw art::Exception( art::errors::NotFound ) << "Could not find the field response file " << fname << "!" << std::endl; std::string iPlane[3] = { "U", "V", "Y" }; for ( int i = 0; i < fNPlanes; i++ ) { TString iHistoName = Form( "%s_%s", histoname.c_str(), iPlane[i].c_str()); TH1F *temp = (TH1F*) fin->Get( iHistoName ); if ( !temp ) throw art::Exception( art::errors::NotFound ) << "Could not find the field response histogram " << iHistoName << std::endl; if ( temp->GetNbinsX() > fNFieldBins ) throw art::Exception( art::errors::InvalidNumber ) << "FieldBins should always be larger than or equal to the number of the bins in the input histogram!" << std::endl; fFieldResponseHist[i] = new TH1F( iHistoName, iHistoName, temp->GetNbinsX(), temp->GetBinLowEdge(1), temp->GetBinLowEdge( temp->GetNbinsX() + 1) ); temp->Copy(*fFieldResponseHist[i]); fFieldResponseHist[i]->SetDirectory(0); } fin->Close(); } } //---------------------------------------------------------------------- // Accessor for single-plane signal shaper. const util::SignalShaping& util::SignalShapingServiceDUNE::SignalShaping(unsigned int channel) const { if(!fInit) init(); // Figure out plane type. art::ServiceHandle<geo::Geometry> geom; //geo::SigType_t sigtype = geom->SignalType(channel); // we need to distinguis between the U and V planes geo::View_t view = geom->View(channel); // Return appropriate shaper. if(view == geo::kU) return fIndUSignalShaping; else if (view == geo::kV) return fIndVSignalShaping; else if(view == geo::kZ) return fColSignalShaping; else throw cet::exception("SignalShapingServiceDUNE")<< "can't determine" << " View\n"; return fColSignalShaping; } //-----Give Gain Settings to SimWire-----//jyoti double util::SignalShapingServiceDUNE::GetASICGain(unsigned int const channel) const { art::ServiceHandle<geo::Geometry> geom; //geo::SigType_t sigtype = geom->SignalType(channel); // we need to distinguis between the U and V planes geo::View_t view = geom->View(channel); double gain = 0; if(view == geo::kU) gain = fASICGainInMVPerFC.at(0); else if(view == geo::kV) gain = fASICGainInMVPerFC.at(1); else if(view == geo::kZ) gain = fASICGainInMVPerFC.at(2); else throw cet::exception("SignalShapingServiceDUNE")<< "can't determine" << " View\n"; return gain; } //-----Give Shaping time to SimWire-----//jyoti double util::SignalShapingServiceDUNE::GetShapingTime(unsigned int const channel) const { art::ServiceHandle<geo::Geometry> geom; //geo::SigType_t sigtype = geom->SignalType(channel); // we need to distinguis between the U and V planes geo::View_t view = geom->View(channel); double shaping_time = 0; if(view == geo::kU) shaping_time = fShapeTimeConst.at(0); else if(view == geo::kV) shaping_time = fShapeTimeConst.at(1); else if(view == geo::kZ) shaping_time = fShapeTimeConst.at(2); else throw cet::exception("SignalShapingServiceDUNE")<< "can't determine" << " View\n"; return shaping_time; } double util::SignalShapingServiceDUNE::GetRawNoise(unsigned int const channel) const { unsigned int plane; art::ServiceHandle<geo::Geometry> geom; //geo::SigType_t sigtype = geom->SignalType(channel); // we need to distinguis between the U and V planes geo::View_t view = geom->View(channel); if(view == geo::kU) plane = 0; else if(view == geo::kV) plane = 1; else if(view == geo::kZ) plane = 2; else throw cet::exception("SignalShapingServiceDUNE")<< "can't determine" << " View\n"; double shapingtime = fShapeTimeConst.at(plane); double gain = fASICGainInMVPerFC.at(plane); int temp; if (shapingtime == 0.5){ temp = 0; }else if (shapingtime == 1.0){ temp = 1; }else if (shapingtime == 2.0){ temp = 2; }else{ temp = 3; } double rawNoise; auto tempNoise = fNoiseFactVec.at(plane); rawNoise = tempNoise.at(temp); rawNoise *= gain/4.7; return rawNoise; } double util::SignalShapingServiceDUNE::GetDeconNoise(unsigned int const channel) const { unsigned int plane; art::ServiceHandle<geo::Geometry> geom; //geo::SigType_t sigtype = geom->SignalType(channel); // we need to distinguis between the U and V planes geo::View_t view = geom->View(channel); if(view == geo::kU) plane = 0; else if(view == geo::kV) plane = 1; else if(view == geo::kZ) plane = 2; else throw cet::exception("SignalShapingServiceDUNE")<< "can't determine" << " View\n"; double shapingtime = fShapeTimeConst.at(plane); int temp; if (shapingtime == 0.5){ temp = 0; }else if (shapingtime == 1.0){ temp = 1; }else if (shapingtime == 2.0){ temp = 2; }else{ temp = 3; } auto tempNoise = fNoiseFactVec.at(plane); double deconNoise = tempNoise.at(temp); deconNoise = deconNoise /4096.*2000./4.7 *6.241*1000/fDeconNorm; return deconNoise; } //---------------------------------------------------------------------- // Initialization method. // Here we do initialization that can't be done in the constructor. // All public methods should ensure that this method is called as necessary. void util::SignalShapingServiceDUNE::init() { if(!fInit) { fInit = true; // Do microboone-specific configuration of SignalShaping by providing // microboone response and filter functions. // Calculate field and electronics response functions. SetFieldResponse(); SetElectResponse(fShapeTimeConst.at(2),fASICGainInMVPerFC.at(2)); // Configure convolution kernels. fColSignalShaping.AddResponseFunction(fColFieldResponse); fColSignalShaping.AddResponseFunction(fElectResponse); fColSignalShaping.save_response(); fColSignalShaping.set_normflag(false); //fColSignalShaping.SetPeakResponseTime(0.); SetElectResponse(fShapeTimeConst.at(0),fASICGainInMVPerFC.at(0)); fIndUSignalShaping.AddResponseFunction(fIndUFieldResponse); fIndUSignalShaping.AddResponseFunction(fElectResponse); fIndUSignalShaping.save_response(); fIndUSignalShaping.set_normflag(false); //fIndUSignalShaping.SetPeakResponseTime(0.); SetElectResponse(fShapeTimeConst.at(1),fASICGainInMVPerFC.at(1)); fIndVSignalShaping.AddResponseFunction(fIndVFieldResponse); fIndVSignalShaping.AddResponseFunction(fElectResponse); fIndVSignalShaping.save_response(); fIndVSignalShaping.set_normflag(false); //fIndVSignalShaping.SetPeakResponseTime(0.); SetResponseSampling(); // Calculate filter functions. SetFilters(); // Configure deconvolution kernels. fColSignalShaping.AddFilterFunction(fColFilter); fColSignalShaping.CalculateDeconvKernel(); fIndUSignalShaping.AddFilterFunction(fIndUFilter); fIndUSignalShaping.CalculateDeconvKernel(); fIndVSignalShaping.AddFilterFunction(fIndVFilter); fIndVSignalShaping.CalculateDeconvKernel(); } } //---------------------------------------------------------------------- // Calculate microboone field response. void util::SignalShapingServiceDUNE::SetFieldResponse() { // Get services. art::ServiceHandle<geo::Geometry> geo; auto const *detprop = lar::providerFrom<detinfo::DetectorPropertiesService>(); // Get plane pitch. double xyz1[3] = {0.}; double xyz2[3] = {0.}; double xyzl[3] = {0.}; // should always have at least 2 planes geo->Plane(0).LocalToWorld(xyzl, xyz1); geo->Plane(1).LocalToWorld(xyzl, xyz2); // this assumes all planes are equidistant from each other, // probably not a bad assumption double pitch = xyz2[0] - xyz1[0]; ///in cm fColFieldResponse.resize(fNFieldBins, 0.); fIndUFieldResponse.resize(fNFieldBins, 0.); fIndVFieldResponse.resize(fNFieldBins, 0.); // set the response for the collection plane first // the first entry is 0 double driftvelocity=detprop->DriftVelocity()/1000.; int nbinc = TMath::Nint(fCol3DCorrection*(std::abs(pitch))/(driftvelocity*detprop->SamplingRate())); ///number of bins //KP double integral = 0; //////////////////////////////////////////////////// if(fUseFunctionFieldShape) { art::ServiceHandle<util::LArFFT> fft; int signalSize = fft->FFTSize(); std::vector<double> ramp(signalSize); // TComplex kernBin; // int size = signalSize/2; // int bin=0; //std::vector<TComplex> freqSig(size+1); std::vector<double> bipolar(signalSize); fColFieldResponse.resize(signalSize, 0.); fIndUFieldResponse.resize(signalSize, 0.); fIndVFieldResponse.resize(signalSize, 0.); // Hardcoding. Bad. Temporary hopefully. fIndUFieldFunc->SetParameter(4,fIndUFieldFunc->GetParameter(4)*signalSize); fIndVFieldFunc->SetParameter(4,fIndVFieldFunc->GetParameter(4)*signalSize); //double integral = 0.; for(int i = 0; i < signalSize; i++) { ramp[i]=fColFieldFunc->Eval(i); fColFieldResponse[i]=ramp[i]; integral += fColFieldResponse[i]; // rampc->Fill(i,ramp[i]); bipolar[i]=fIndUFieldFunc->Eval(i); fIndUFieldResponse[i]=bipolar[i]; bipolar[i]=fIndVFieldFunc->Eval(i); fIndVFieldResponse[i]=bipolar[i]; // bipol->Fill(i,bipolar[i]); } for(int i = 0; i < signalSize; ++i){ fColFieldResponse[i] *= fColFieldRespAmp/integral; } //this might be not necessary if the function definition is not defined in the middle of the signal range fft->ShiftData(fIndUFieldResponse,signalSize/2.0); } else if ( fUseHistogramFieldShape ) { // Ticks in nanosecond // Calculate the normalization of the collection plane for ( int ibin = 1; ibin <= fFieldResponseHist[2]->GetNbinsX(); ibin++ ) integral += fFieldResponseHist[2]->GetBinContent( ibin ); // Induction plane for ( int ibin = 1; ibin <= fFieldResponseHist[0]->GetNbinsX(); ibin++ ) fIndUFieldResponse[ibin-1] = fIndUFieldRespAmp*fFieldResponseHist[0]->GetBinContent( ibin )/integral; for ( int ibin = 1; ibin <= fFieldResponseHist[1]->GetNbinsX(); ibin++ ) fIndVFieldResponse[ibin-1] = fIndVFieldRespAmp*fFieldResponseHist[1]->GetBinContent( ibin )/integral; for ( int ibin = 1; ibin <= fFieldResponseHist[2]->GetNbinsX(); ibin++ ) fColFieldResponse[ibin-1] = fColFieldRespAmp*fFieldResponseHist[2]->GetBinContent( ibin )/integral; }else { ////////////////////////////////////////////////// mf::LogInfo("SignalShapingServiceDUNE") << " using the old field shape "; double integral = 0.; for(int i = 1; i < nbinc; ++i){ fColFieldResponse[i] = fColFieldResponse[i-1] + 1.0; integral += fColFieldResponse[i]; } for(int i = 0; i < nbinc; ++i){ fColFieldResponse[i] *= fColFieldRespAmp/integral; } // now the induction plane int nbini = TMath::Nint(fInd3DCorrection*(fabs(pitch))/(driftvelocity*detprop->SamplingRate()));//KP for(int i = 0; i < nbini; ++i){ fIndUFieldResponse[i] = fIndUFieldRespAmp/(1.*nbini); fIndUFieldResponse[nbini+i] = -fIndUFieldRespAmp/(1.*nbini); } for(int i = 0; i < nbini; ++i){ fIndVFieldResponse[i] = fIndVFieldRespAmp/(1.*nbini); fIndVFieldResponse[nbini+i] = -fIndVFieldRespAmp/(1.*nbini); } } return; } void util::SignalShapingServiceDUNE::SetElectResponse(double shapingtime, double gain) { // Get services. art::ServiceHandle<geo::Geometry> geo; art::ServiceHandle<util::LArFFT> fft; LOG_DEBUG("SignalShapingDUNE") << "Setting DUNE electronics response function..."; int nticks = fft->FFTSize(); fElectResponse.resize(nticks, 0.); std::vector<double> time(nticks,0.); //Gain and shaping time variables from fcl file: double Ao = 1.0; double To = shapingtime; //peaking time // this is actually sampling time, in ns // mf::LogInfo("SignalShapingDUNE") << "Check sampling intervals: " // << fSampleRate << " ns" // << "Check number of samples: " << fNTicks; // The following sets the microboone electronics response function in // time-space. Function comes from BNL SPICE simulation of DUNE35t // electronics. SPICE gives the electronics transfer function in // frequency-space. The inverse laplace transform of that function // (in time-space) was calculated in Mathematica and is what is being // used below. Parameters Ao and To are cumulative gain/timing parameters // from the full (ASIC->Intermediate amp->Receiver->ADC) electronics chain. // They have been adjusted to make the SPICE simulation to match the // actual electronics response. Default params are Ao=1.4, To=0.5us. double max = 0; for(size_t i = 0; i < fElectResponse.size(); ++i){ //convert time to microseconds, to match fElectResponse[i] definition time[i] = (1.*i)*fInputFieldRespSamplingPeriod *1e-3; fElectResponse[i] = 4.31054*exp(-2.94809*time[i]/To)*Ao - 2.6202*exp(-2.82833*time[i]/To)*cos(1.19361*time[i]/To)*Ao -2.6202*exp(-2.82833*time[i]/To)*cos(1.19361*time[i]/To)*cos(2.38722*time[i]/To)*Ao +0.464924*exp(-2.40318*time[i]/To)*cos(2.5928*time[i]/To)*Ao +0.464924*exp(-2.40318*time[i]/To)*cos(2.5928*time[i]/To)*cos(5.18561*time[i]/To)*Ao +0.762456*exp(-2.82833*time[i]/To)*sin(1.19361*time[i]/To)*Ao -0.762456*exp(-2.82833*time[i]/To)*cos(2.38722*time[i]/To)*sin(1.19361*time[i]/To)*Ao +0.762456*exp(-2.82833*time[i]/To)*cos(1.19361*time[i]/To)*sin(2.38722*time[i]/To)*Ao -2.6202*exp(-2.82833*time[i]/To)*sin(1.19361*time[i]/To)*sin(2.38722*time[i]/To)*Ao -0.327684*exp(-2.40318*time[i]/To)*sin(2.5928*time[i]/To)*Ao + +0.327684*exp(-2.40318*time[i]/To)*cos(5.18561*time[i]/To)*sin(2.5928*time[i]/To)*Ao -0.327684*exp(-2.40318*time[i]/To)*cos(2.5928*time[i]/To)*sin(5.18561*time[i]/To)*Ao +0.464924*exp(-2.40318*time[i]/To)*sin(2.5928*time[i]/To)*sin(5.18561*time[i]/To)*Ao; if(fElectResponse[i] > max) max = fElectResponse[i]; }// end loop over time buckets LOG_DEBUG("SignalShapingDUNE") << " Done."; //normalize fElectResponse[i], before the convolution for(auto& element : fElectResponse){ element /= max; element *= fADCPerPCAtLowestASICGain * 1.60217657e-7; element *= gain / 4.7; } return; } //---------------------------------------------------------------------- // Calculate microboone filter functions. void util::SignalShapingServiceDUNE::SetFilters() { // Get services. auto const *detprop = lar::providerFrom<detinfo::DetectorPropertiesService>(); art::ServiceHandle<util::LArFFT> fft; double ts = detprop->SamplingRate(); int n = fft->FFTSize() / 2; // Calculate collection filter. fColFilter.resize(n+1); fIndUFilter.resize(n+1); fIndVFilter.resize(n+1); if(!fGetFilterFromHisto) { fColFilterFunc->SetRange(0, double(n)); for(int i=0; i<=n; ++i) { double freq = 500. * i / (ts * n); // Cycles / microsecond. double f = fColFilterFunc->Eval(freq); fColFilter[i] = TComplex(f, 0.); } // Calculate induction filter. fIndUFilterFunc->SetRange(0, double(n)); for(int i=0; i<=n; ++i) { double freq = 500. * i / (ts * n); // Cycles / microsecond. double f = fIndUFilterFunc->Eval(freq); fIndUFilter[i] = TComplex(f, 0.); } fIndVFilterFunc->SetRange(0, double(n)); for(int i=0; i<=n; ++i) { double freq = 500. * i / (ts * n); // Cycles / microsecond. double f = fIndVFilterFunc->Eval(freq); fIndVFilter[i] = TComplex(f, 0.); } } else { for(int i=0; i<=n; ++i) { double f = fFilterHist[2]->GetBinContent(i); // hardcoded plane numbers. Bad. To change later. fColFilter[i] = TComplex(f, 0.); double g = fFilterHist[1]->GetBinContent(i); fIndVFilter[i] = TComplex(g, 0.); double h = fFilterHist[0]->GetBinContent(i); fIndUFilter[i] = TComplex(h, 0.); } } //fIndUSignalShaping.AddFilterFunction(fIndFilter); //fIndVSignalShaping.AddFilterFunction(fIndVFilter); //fColSignalShaping.AddFilterFunction(fColFilter); } //---------------------------------------------------------------------- // Sample microboone response (the convoluted field and electronic // response), will probably add the filter later void util::SignalShapingServiceDUNE::SetResponseSampling() { // Get services art::ServiceHandle<geo::Geometry> geo; auto const *detprop = lar::providerFrom<detinfo::DetectorPropertiesService>(); art::ServiceHandle<util::LArFFT> fft; // Operation permitted only if output of rebinning has a larger bin size if( fInputFieldRespSamplingPeriod > detprop->SamplingRate() ) throw cet::exception(__FUNCTION__) << "\033[93m" << "Invalid operation: cannot rebin to a more finely binned vector!" << "\033[00m" << std::endl; int nticks = fft->FFTSize(); std::vector<double> SamplingTime( nticks, 0. ); for ( int itime = 0; itime < nticks; itime++ ) { SamplingTime[itime] = (1.*itime) * detprop->SamplingRate(); /// VELOCITY-OUT ... comment out kDVel usage here //SamplingTime[itime] = (1.*itime) * detprop->SamplingRate() / kDVel; } // Sampling for ( int iplane = 0; iplane < 3; iplane++ ) { const std::vector<double>* pResp; switch ( iplane ) { case 0: pResp = &(fIndUSignalShaping.Response_save()); break; case 1: pResp = &(fIndVSignalShaping.Response_save()); break; default: pResp = &(fColSignalShaping.Response_save()); break; } std::vector<double> SamplingResp(nticks , 0. ); int nticks_input = pResp->size(); std::vector<double> InputTime(nticks_input, 0. ); for ( int itime = 0; itime < nticks_input; itime++ ) { InputTime[itime] = (1.*itime) * fInputFieldRespSamplingPeriod; } /* Much more sophisticated approach using a linear (trapezoidal) interpolation Current default! */ int SamplingCount = 0; for ( int itime = 0; itime < nticks; itime++ ) { int low = -1, up = -1; for ( int jtime = 0; jtime < nticks_input; jtime++ ) { if ( InputTime[jtime] == SamplingTime[itime] ) { SamplingResp[itime] = (*pResp)[jtime]; /// VELOCITY-OUT ... comment out kDVel usage here //SamplingResp[itime] = kDVel * (*pResp)[jtime]; SamplingCount++; break; } else if ( InputTime[jtime] > SamplingTime[itime] ) { low = jtime - 1; up = jtime; SamplingResp[itime] = (*pResp)[low] + ( SamplingTime[itime] - InputTime[low] ) * ( (*pResp)[up] - (*pResp)[low] ) / ( InputTime[up] - InputTime[low] ); /// VELOCITY-OUT ... comment out kDVel usage here //SamplingResp[itime] *= kDVel; SamplingCount++; break; } else { SamplingResp[itime] = 0.; } } // for ( int jtime = 0; jtime < nticks; jtime++ ) } // for ( int itime = 0; itime < nticks; itime++ ) SamplingResp.resize( SamplingCount, 0.); switch ( iplane ) { case 0: fIndUSignalShaping.AddResponseFunction( SamplingResp, true ); break; case 1: fIndVSignalShaping.AddResponseFunction( SamplingResp, true ); break; default: fColSignalShaping.AddResponseFunction( SamplingResp, true ); break; } } // for ( int iplane = 0; iplane < fNPlanes; iplane++ ) return; } int util::SignalShapingServiceDUNE::FieldResponseTOffset(unsigned int const channel) const { art::ServiceHandle<geo::Geometry> geom; //geo::SigType_t sigtype = geom->SignalType(channel); // we need to distinguis between the U and V planes geo::View_t view = geom->View(channel); double time_offset = 0; if(view == geo::kU) time_offset = fFieldResponseTOffset.at(0) + fCalibResponseTOffset.at(0); else if(view == geo::kV) time_offset = fFieldResponseTOffset.at(1) + fCalibResponseTOffset.at(1); else if(view == geo::kZ) time_offset = fFieldResponseTOffset.at(2) + fCalibResponseTOffset.at(2); else throw cet::exception("SignalShapingServiceDUNEt")<< "can't determine" << " View\n"; auto tpc_clock = lar::providerFrom<detinfo::DetectorClocksService>()->TPCClock(); return tpc_clock.Ticks(time_offset/1.e3); } namespace util { DEFINE_ART_SERVICE(SignalShapingServiceDUNE) }
b6c8e8d799a1856a53e7c7addf05938708a0052c
4855d40bdc73131c09cf544aed76bb2761d86e47
/src/core/renderer.h
135896921b620c1a4506e8d44dbf73900d250835
[]
no_license
cedricKode/Rayone
a511fe3516c604684c41b5593788fde98d18827a
505a91018782c213c07f17d641016314b49efe48
refs/heads/master
2023-05-28T02:40:25.521765
2016-09-19T20:51:11
2016-09-19T20:51:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
570
h
// core/renderer.h #ifndef PT_CORE_RENDERER_H #define PT_CORE_RENDERER_H #include "pathtracer.h" #include <vector> // Forward declaration (shouldn't have to do this) class Shape; struct Intersection; // Render class declaration // Provide shading and intersecting methods for the scene class Renderer { public: Renderer(std::vector<Shape *> s) : scene(s) {} ~Renderer() {} Vec Radiance(const Ray &r, int depth, unsigned short *Xi, int E = 1) const; Intersection Intersect(const Ray &r) const; std::vector<Shape *> scene; }; #endif // PT_CORE_RENDERER_H
0dad58a45fcb768e8550df6e4ca45418b0b08f7c
420192c20bdab532bf5566b0df192fc161ed3664
/fiveormore/FiveOrMore.cpp
6f56f4c715d5b76d8bb036773ac46099cb92db98
[]
no_license
elmehdilaagad/Platform-Games
d53825a13eed80264145a3fee77ce1bb53c2003b
ca67e768bc95f611a3942a377b674bb8649b8cb4
refs/heads/master
2021-01-10T12:34:52.082330
2016-01-15T13:06:07
2016-01-15T13:06:07
47,838,895
0
0
null
null
null
null
UTF-8
C++
false
false
3,810
cpp
#include <iostream> #include "FiveOrMore.hpp" #include "Plateau_five.hpp" #include <stdlib.h> #include <map> int score = 0; FiveOrMore::FiveOrMore(){ this->nbColor = 5; plateau = new Plateau_five(5); } int FiveOrMore::getCouleurs(){ return nbColor; } int FiveOrMore::fin(){ for(int i = 0; i < plateau->getNbLignes() ; i++){ for(int j = 0; j <plateau->getNbCols(); j++){ if(plateau->getPlateau()[i][j] == -1) return -1; // pas fini } } return 0; } //choisi 3 point et 3 couleurs aléatoirement et enregistre les points void FiveOrMore::choix_coordonnees(){ int x,y,c; int flag = 1; srand (time(NULL)); cout << "COUP ORDI" << endl; while(flag == 1){ for(int i = 0; i < 3; i++){ x = rand()%plateau->getNbCols(); // colonnes y = rand()%plateau->getNbLignes(); // lignes c = rand()%this->getCouleurs(); // couleurs // cout <<"x : " << x <<" y : " << y <<" c : " << c << endl; if(plateau->getPlateau()[x][y] != -1) flag = 1; else{ plateau->getPlateau()[x][y] = c; flag = 0; } } } } /* demande a l'utilisateur de choisir le point à déplacer et son nouvelle emplacement */ void FiveOrMore::choix_utilisateurs(){ int flag = 1; int flag2 = 1; int x,y,new_x,new_y; while(flag == 1){ cout << "Choisissez la ligne du point à déplacer : " << endl; cin >> x; cout << "Choisissez la colonne du point à déplacer : " << endl; cin >> y; if(plateau->getPlateau()[x][y] == -1){ cout << "Les coordonées choisi ne sont pas bon" << endl; flag = 1; }else flag = 0; } if(flag == 0){ while(flag2 == 1){ cout << "Choisissez la ligne de l'empacement du nouveau point : " << endl; cin >> new_x; cout << "Choisissez la colonne de l'emplacement du nouveau point: " << endl; cin >> new_y; if(plateau->getPlateau()[new_x][new_y] != -1){ cout << "Il y a une grille a cet emplacement " << endl; cout << "RECOMMENCEZ" << endl; flag2 = 1; }else{ plateau->getPlateau()[new_x][new_y] = plateau->getPlateau()[x][y]; plateau->getPlateau()[x][y] = -1; flag2 = 0; } } } } bool FiveOrMore::horizontal(int j){ map<int, int> coord; map<int,int>::iterator im; int compt = 1; for(int i = 0; i < plateau->getNbCols(); i++){ if(plateau->getPlateau()[i][j] == -1) return false; if(plateau->getPlateau()[i][j] == plateau->getPlateau()[i][j+1]){ compt++; coord[i]= j; // cout << "compt " << compt << endl; } if(compt == 5 || compt > 5){ coord[i+1] = j; for(im = coord.begin(); im != coord.end(); im++){ plateau->getPlateau()[(*im).first][(*im).second] = -1; } score = compt*2; cout << "Vous avez un score de : " << score << endl; return true; } } return false; } bool FiveOrMore::vertical(int j){ map<int, int> coord; map<int,int>::iterator im; int compt = 1; for(int i = 0; i < plateau->getNbLignes(); i++){ if(plateau->getPlateau()[i][j] == -1) return false; if(plateau->getPlateau()[i][j] == plateau->getPlateau()[i+1][j]){ compt++; coord[i]= j; // cout << "compt " << compt << endl; } if(compt == 5 || compt > 5){ coord[i+1] = j; for(im = coord.begin(); im != coord.end(); im++){ plateau->getPlateau()[(*im).first][(*im).second] = -1; } score = compt*2; cout << "Vous avez un score de : " << score << endl; return true; } } return false; } void FiveOrMore::start(){ while(fin() != 0){ choix_coordonnees(); plateau->affiche(); choix_utilisateurs(); cout << "Joueur " << endl; plateau->affiche(); for(int i = 0 ; i < plateau->getNbCols(); i++){ vertical(i); } } }
f2f31b96366a485f17fef3d12856a4461b062ec1
39ad116dab0ba316a6e7f737a031a0f853685d41
/795/a.cpp
db95426429329cd904d301d95531f9317166e5db
[]
no_license
Abunyawa/contests
e0f9d157ce93d3fc5fbff0e3e576f15286272c98
9923df8f167e8091e23f890b01368a3a8f61e452
refs/heads/master
2023-05-31T14:20:31.983437
2023-05-11T14:19:58
2023-05-11T14:19:58
251,015,695
10
0
null
null
null
null
UTF-8
C++
false
false
984
cpp
// chrono::system_clock::now().time_since_epoch().count() #include <bits/stdc++.h> #define pb push_back #define eb emplace_back #define mp make_pair #define fi first #define se second #define all(x) (x).begin(), (x).end() #define sz(x) (int)(x).size() #define rep(i, a, b) for (int i = (a); i < (b); ++i) #define debug(x) cerr << #x << " = " << x << endl using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<ll> vl; void yes(){ cout<<"YES"<<'\n'; } void no(){ cout<<"NO"<<'\n'; } void solve() { int n; cin>>n; vl a(n); int ctr1= 0; int ctr2=0; for(int i=0;i<n;i++){ cin>>a[i]; if(a[i]%2==0){ ctr1++; }else{ ctr2++; } } cout<<min(ctr1,ctr2)<<'\n'; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int tt = 1; cin>>tt; while (tt--) { solve(); } return 0; }
c568acb785f1689dd3c684dd457fa083abc529af
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/ds/security/services/smartcrd/tools/sctest/sctest/test7.cpp
608de6d8ddd3c9c7a043057b072cc17146f73091
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,783
cpp
/*++ Copyright (C) Microsoft Corporation, 2000 Module Name: Test7 Abstract: Test7 implementation. Interactive Test verifying bug Author: Eric Perlin (ericperl) 06/22/2000 Environment: Win32 Notes: ?Notes? --*/ #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include "Test4.h" #include <stdlib.h> #include "LogSCard.h" const LPCTSTR szMyReadersName = _T("My New Reader Name"); const LPCTSTR szMyReadersKey = _T("SOFTWARE\\Microsoft\\Cryptography\\Calais\\Readers"); class CTest7 : public CTestItem { public: CTest7() : CTestItem(FALSE, FALSE, _T("SCardIntroduceReader API regression"), _T("Regression tests")) { } DWORD Run(); }; CTest7 Test7; extern CTest4 Test4; DWORD CTest7::Run() { LONG lRes; SCARDCONTEXT hSCCtx = NULL; LPTSTR pmszReaders = NULL; LPTSTR pReader; LPSCARD_READERSTATE rgReaderStates = NULL; LPBYTE lpbyAttr = NULL; DWORD cch = SCARD_AUTOALLOCATE; DWORD dwReaderCount, i; SCARDHANDLE hCardHandle = NULL; HKEY hMyReadersKey = NULL; HKEY hMyNewReaderKey = NULL; __try { lRes = Test4.Run(); if (FAILED(lRes)) { __leave; } // Initial cleanup in case of previous aborted tests lRes = RegOpenKeyEx( HKEY_CURRENT_USER, szMyReadersKey, 0, KEY_ALL_ACCESS, &hMyReadersKey); if (ERROR_SUCCESS == lRes) { // The key exists, delete MyReaderName RegDeleteKey(hMyReadersKey, szMyReadersName); RegCloseKey(hMyReadersKey); hMyReadersKey = NULL; } lRes = RegOpenKeyEx( HKEY_LOCAL_MACHINE, szMyReadersKey, 0, KEY_ALL_ACCESS, &hMyReadersKey); if (ERROR_SUCCESS == lRes) { // The key exists, delete MyReaderName LONG lTemp = RegDeleteKey(hMyReadersKey, szMyReadersName); RegCloseKey(hMyReadersKey); hMyReadersKey = NULL; } else { PLOGCONTEXT pLogCtx = LogStart(); LogString(pLogCtx, _T("WARNING: The resulting key couldn't be opened with all access:\n HKCU\\"), szMyReadersKey); LogStop(pLogCtx, FALSE); } lRes = LogSCardEstablishContext( SCARD_SCOPE_USER, NULL, NULL, &hSCCtx, SCARD_S_SUCCESS ); if (FAILED(lRes)) { __leave; } // Retrieve the list the readers. lRes = LogSCardListReaders( hSCCtx, g_szReaderGroups, (LPTSTR)&pmszReaders, &cch, SCARD_S_SUCCESS ); if (FAILED(lRes)) { __leave; } // Display the list of readers pReader = pmszReaders; dwReaderCount = 0; while ( (TCHAR)'\0' != *pReader ) { // Advance to the next value. pReader = pReader + _tcslen(pReader) + 1; dwReaderCount++; } if (dwReaderCount == 0) { LogThisOnly(_T("Reader count is zero!!!, terminating!\n"), FALSE); lRes = SCARD_F_UNKNOWN_ERROR; // Shouldn't happen __leave; } rgReaderStates = (LPSCARD_READERSTATE)HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(SCARD_READERSTATE) * dwReaderCount ); if (rgReaderStates == NULL) { LogThisOnly(_T("Allocating the array of SCARD_READERSTATE failed, terminating!\n"), FALSE); lRes = ERROR_OUTOFMEMORY; __leave; } // Setup the SCARD_READERSTATE array pReader = pmszReaders; cch = 0; while ( '\0' != *pReader ) { rgReaderStates[cch].szReader = pReader; rgReaderStates[cch].dwCurrentState = SCARD_STATE_UNAWARE; // Advance to the next value. pReader = pReader + _tcslen(pReader) + 1; cch++; } lRes = LogSCardLocateCards( hSCCtx, _T("SCWUnnamed\0"), rgReaderStates, cch, SCARD_S_SUCCESS ); if (FAILED(lRes)) { __leave; } for (i=0 ; i<dwReaderCount ; i++) { if ((rgReaderStates[i].dwEventState & SCARD_STATE_PRESENT) && !(rgReaderStates[i].dwEventState & SCARD_STATE_EXCLUSIVE)) { DWORD dwProtocol; lRes = LogSCardConnect( hSCCtx, rgReaderStates[i].szReader, SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1, &hCardHandle, &dwProtocol, SCARD_S_SUCCESS); if (FAILED(lRes)) { __leave; } cch = SCARD_AUTOALLOCATE; lpbyAttr = NULL; lRes = LogSCardGetAttrib( hCardHandle, SCARD_ATTR_DEVICE_SYSTEM_NAME, (LPBYTE)(&lpbyAttr), &cch, SCARD_S_SUCCESS ); if (FAILED(lRes)) { __leave; } // Add the reader name. lRes = LogSCardIntroduceReader( hSCCtx, szMyReadersName, (LPCTSTR)lpbyAttr, SCARD_S_SUCCESS ); if (FAILED(lRes)) { __leave; } lRes = RegOpenKeyEx( HKEY_CURRENT_USER, szMyReadersKey, 0, KEY_READ, &hMyReadersKey); if (ERROR_SUCCESS == lRes) { lRes = RegOpenKeyEx( hMyReadersKey, szMyReadersName, 0, KEY_READ, &hMyNewReaderKey); if (ERROR_SUCCESS == lRes) { PLOGCONTEXT pLogCtx = LogVerification(_T("Registry verification"), TRUE); LogStop(pLogCtx, TRUE); } else { lRes = -1; PLOGCONTEXT pLogCtx = LogVerification(_T("Registry verification"), FALSE); LogString(pLogCtx, _T(" The resulting key couldn't be found:\n HKCU\\")); LogString(pLogCtx, szMyReadersKey); LogString(pLogCtx, _T("\\"), szMyReadersName); LogStop(pLogCtx, FALSE); } } else { lRes = -1; PLOGCONTEXT pLogCtx = LogVerification(_T("Registry verification"), FALSE); LogString(pLogCtx, _T(" The resulting key couldn't be found:\n HKCU\\"), szMyReadersKey); LogStop(pLogCtx, FALSE); } // Test Cleanup lRes = LogSCardForgetReader( hSCCtx, szMyReadersName, SCARD_S_SUCCESS ); break; } } if (i == dwReaderCount) { lRes = -1; PLOGCONTEXT pLogCtx = LogVerification(_T("Card presence verification"), FALSE); LogString(pLogCtx, _T(" A card is required and none could be found in any reader!\n")); LogStop(pLogCtx, FALSE); } lRes = -2; // Invalid error } __finally { if (lRes == 0) { LogThisOnly(_T("Test7: an exception occurred!"), FALSE); lRes = -1; } Test4.Cleanup(); if (NULL != hMyReadersKey) { RegCloseKey(hMyReadersKey); } if (NULL != hMyNewReaderKey) { RegCloseKey(hMyNewReaderKey); } if (NULL != lpbyAttr) { LogSCardFreeMemory( hSCCtx, (LPCVOID)lpbyAttr, SCARD_S_SUCCESS ); } if (NULL != hCardHandle) { LogSCardDisconnect( hCardHandle, SCARD_LEAVE_CARD, SCARD_S_SUCCESS ); } if (NULL != hSCCtx) { LogSCardReleaseContext( hSCCtx, SCARD_S_SUCCESS ); } } if (-2 == lRes) { lRes = 0; } return lRes; }
41f0f738222e2b80ee86a231e1e212a9c43efa6b
7e1d23550795cf6cf71b007bd7ffd319f517dd6e
/Includes/aniTemplate/io_5.cc
5f599fa77ae88e83df7e38634eabc02454f34dc4
[ "LicenseRef-scancode-philippe-de-muyter", "Apache-2.0", "CC-BY-4.0" ]
permissive
pandevim/Code-Archive
ea65e70b4a92ebd167d44fecbc62e9277149fdae
f347aa17ef3f43d6b5a3ce95f9be25d2a6cb6965
refs/heads/master
2021-07-25T02:41:23.182512
2021-04-17T14:01:24
2021-04-17T14:01:24
124,125,630
0
1
null
null
null
null
UTF-8
C++
false
false
225
cc
#ifdef JUDGE #include <fstream> std::ifstream cin("input.txt"); std::ofstream cout("output.txt"); #else #include <iostream> using std::cin; using std::cout; #endif int main() { int a, b; cin >> a >> b; return 0; }
3fd77af6b8276307c8cbbe21c7b395d5ab687952
2bfddaf9c0ceb7bf46931f80ce84a829672b0343
/tests/xtd.tunit.unit_tests/src/xtd/tunit/tests/valid_is_not_null_weak_ptr_failed_tests.cpp
e2f502c4af1f072252dfb7d0e805e2a479b21782
[ "MIT" ]
permissive
gammasoft71/xtd
c6790170d770e3f581b0f1b628c4a09fea913730
ecd52f0519996b96025b196060280b602b41acac
refs/heads/master
2023-08-19T09:48:09.581246
2023-08-16T20:52:11
2023-08-16T20:52:11
170,525,609
609
53
MIT
2023-05-06T03:49:33
2019-02-13T14:54:22
C++
UTF-8
C++
false
false
989
cpp
#include <xtd/tunit/valid.h> #include <xtd/tunit/test_class_attribute.h> #include <xtd/tunit/test_method_attribute.h> #include "../../../assert_unit_tests/assert_unit_tests.h" #include <memory> namespace xtd::tunit::tests { class test_class_(valid_is_not_null_weak_ptr_failed_tests) { public: void test_method_(test_case_failed) { std::weak_ptr<int> p; xtd::tunit::assert::is_not_null(p); } }; } void test_(valid_is_not_null_weak_ptr_failed_tests, test_output) { auto [output, result] = run_test_("valid_is_not_null_weak_ptr_failed_tests.*"); assert_value_("Start 1 test from 1 test case\n" " FAILED valid_is_not_null_weak_ptr_failed_tests.test_case_failed\n" " Expected: not null\n" " But was: null\n" "End 1 test from 1 test case ran.\n", output); } void test_(valid_is_not_null_weak_ptr_failed_tests, test_result) { auto [output, result] = run_test_("valid_is_not_null_weak_ptr_failed_tests.*"); assert_value_(1, result); }
d727a229a3bf51596feb08524949e605396155e4
cf8ddfc720bf6451c4ef4fa01684327431db1919
/SDK/ARKSurvivalEvolved_LootItemSet_SupplyDrop_Level45_StatsOnly_functions.cpp
28a951e90216a2e007a9569b8c396fcca2b96a65
[ "MIT" ]
permissive
git-Charlie/ARK-SDK
75337684b11e7b9f668da1f15e8054052a3b600f
c38ca9925309516b2093ad8c3a70ed9489e1d573
refs/heads/master
2023-06-20T06:30:33.550123
2021-07-11T13:41:45
2021-07-11T13:41:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,269
cpp
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_LootItemSet_SupplyDrop_Level45_StatsOnly_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function LootItemSet_SupplyDrop_Level45_StatsOnly.LootItemSet_SupplyDrop_Level45_StatsOnly_C.ExecuteUbergraph_LootItemSet_SupplyDrop_Level45_StatsOnly // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void ULootItemSet_SupplyDrop_Level45_StatsOnly_C::ExecuteUbergraph_LootItemSet_SupplyDrop_Level45_StatsOnly(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function LootItemSet_SupplyDrop_Level45_StatsOnly.LootItemSet_SupplyDrop_Level45_StatsOnly_C.ExecuteUbergraph_LootItemSet_SupplyDrop_Level45_StatsOnly"); ULootItemSet_SupplyDrop_Level45_StatsOnly_C_ExecuteUbergraph_LootItemSet_SupplyDrop_Level45_StatsOnly_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
952751deff9ea39a897a9e7ea210fc961ff223d4
dfe01f7d991bcae7bfdb84f77d2b1697c9b9e061
/ATS/N-Queens.cpp
9c0c9489478cd5a0ed1f679a608eee5d0dd4ac34
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
reiniru/DSA
3cd3782a9c870b888622de5add680469384d63f8
a8f50721f1fb22d503100f9edf2ba50ce9a53ede
refs/heads/master
2021-06-19T06:26:40.639348
2017-06-10T14:59:28
2017-06-10T14:59:28
25,690,039
0
0
null
null
null
null
UTF-8
C++
false
false
1,297
cpp
#include <iostream> #include "N-Queens.h" NQueens::NQueens(int size) { m_size = size; m_vector = new int[m_size]; for (int i = 0; i < m_size; i++) m_vector[i] = 0; } NQueens::~NQueens() { delete[] m_vector; } bool NQueens::Verify(int k) { for (int i = 0; i < k; i++) if (m_vector[i] == m_vector[k] || m_vector[i] == m_vector[k] - (k - i) || m_vector[i] == m_vector[k] + (k - i)) return true; return false; } bool NQueens::Start() { bool success = false, b = false; int k = 1; m_vector[k] = 1; do { if (Verify(k)) { do { if (m_vector[k] < m_size-1) { b = true; m_vector[k]++; } else { b = false; k--; } } while (!b || k == 0); } else if (k == m_size-1) return success = true; else { k++; m_vector[k] = 1; } } while (!success || k== 0); return success; } void NQueens::Print() { int column = 0; std::cout << "La soluzione e' la seguente (" << m_size << " queens in " << m_size*m_size << " cells) : " << std::endl; for (int column = 0; column < m_size; column++) { for (int row = 0; row < m_size; row++) { if (row % m_size == 0) { std::cout << std::endl; } if (m_vector[column] == row) std::cout << "Q "; else std::cout << "- "; } } }
81c8a234be27f1c0128cafb389e3c922185f770d
5cba2458f5497f743b95627d20738bf008ab1ed7
/ESP32/lib/GoogleHome/GoogleHome.cpp
9388abc89d25bd8feb7b4a15247b69c749c7383b
[ "MIT" ]
permissive
Shivar90/GoogleHomeNode
5c71bf2980cc601fb0c6d55101346c5bd278a954
41c11d81c221171bd1381efa88e0395be54aeca6
refs/heads/master
2023-06-12T23:59:45.894274
2021-07-04T08:09:00
2021-07-04T08:09:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,974
cpp
#include <GoogleHome.h> bool GoogleHome::Initialize(void (*event_queue_method)(const CustomEvents &), bool verbose) { isVerbose = verbose; queueEvent = event_queue_method; } bool GoogleHome::TryConnect(std::string deviceName) { //const IPAddress ip = IPAddress(192, 168, 1, 108); //= "192.168.1.108"; this->deviceName = deviceName; if (Connected) return true; if (isVerbose) printf("Connecting to a Google Home Speaker: %s \r\n", deviceName.c_str()); if (googleHomeNotifier.device(deviceName.c_str(), "en") != true) { if (isVerbose) printf("Failed to connect to the Google Home Speaker. Error: %s\r\n", googleHomeNotifier.getLastError()); return false; } else { Connected = true; if (isVerbose) printf("Found the Google Home Speaker. %s (%s:%d).\r\n", deviceName.c_str(), googleHomeNotifier.getIPAddress() .toString() .c_str(), googleHomeNotifier.getPort()); char buffer[200]; sprintf(buffer, "Home monitoring system is initialized.\r\n", deviceName.c_str()); if (!googleHomeNotifier.notify(buffer)) { if (isVerbose) printf("Google Home notify error: %s\r\n", googleHomeNotifier.getLastError()); Connected = false; } } if (Connected) queueEvent(CustomEvents::EVENT_GOOGLE_HOME_CONNECTED); return Connected; } const char *GoogleHome::resolveLanguage(Languages lang) { switch (lang) { case Languages::English: return (const char *)"en"; case Languages::Deutsch: return (const char *)"de"; case Languages::Francais: return (const char *)"fr"; default: return (const char *)"en"; } } bool GoogleHome::notify(std::string deviceName, std::string message, Languages language) { if (!TryConnect(deviceName)) return false; googleHomeNotifier.setLanguage(resolveLanguage(language)); if (!googleHomeNotifier.notify(message.c_str())) { if (isVerbose) printf("Google Home notify error: %s\r\n", googleHomeNotifier.getLastError()); return false; } return true; } bool GoogleHome::NofityPhrase(std::string phrase, Languages language) { return notify(this->deviceName, phrase, language); } bool GoogleHome::NotifyTemperature(int temperature, Languages language) { char buffer[200]; byte index = rand() % 3; switch (language) { case Languages::English: sprintf(buffer, Temperature_EN[index], temperature); break; case Languages::Deutsch: sprintf(buffer, Temperature_DE[index], temperature); break; case Languages::Francais: sprintf(buffer, Temperature_FR[index], temperature); break; default: break; } return notify(this->deviceName, buffer, language); } bool GoogleHome::NotifyTemperatureSummary(int average, int min, int max, Languages language) { char buffer[200]; byte index = 0; switch (language) { case Languages::English: sprintf(buffer, Temperature_Summary_EN[index], average, min, max); break; case Languages::Deutsch: sprintf(buffer, Temperature_Summary_DE[index], average, min, max); break; case Languages::Francais: sprintf(buffer, Temperature_Summary_FR[index], average, min, max); break; default: break; } return notify(this->deviceName, buffer, language); } bool GoogleHome::NotifyHumidity(int humidity, Languages language) { char buffer[200]; byte index = rand() % 3; switch (language) { case Languages::English: sprintf(buffer, HUMIDITY_EN[index], humidity); break; case Languages::Deutsch: sprintf(buffer, HUMIDITY_DE[index], humidity); break; case Languages::Francais: sprintf(buffer, HUMIDITY_FR[index], humidity); break; default: break; } return notify(this->deviceName, buffer, language); } bool GoogleHome::NotifyHumiditySummary(int average, int min, int max, Languages language) { char buffer[200]; byte index = 0; switch (language) { case Languages::English: sprintf(buffer, Humidity_Summary_EN[index], average, min, max); break; case Languages::Deutsch: sprintf(buffer, Humidity_Summary_DE[index], average, min, max); break; case Languages::Francais: sprintf(buffer, Humidity_Summary_FR[index], average, min, max); break; default: break; } return notify(this->deviceName, buffer, language); } bool GoogleHome::NotifyPressure(float pressure, Languages language) { char buffer[200]; sprintf(buffer, "The current temperature level is %2.1f atm", pressure); return notify(this->deviceName, buffer, language); }
9f8a8e5b4773297dfa67c053a70712d712883927
2f903b910cd534e83bf59d68b53850cf4d4984a0
/FileWriter.h
3a7eec95d54e0619df2aa46b0a3dd00b50c8a0d1
[]
no_license
FlyingInTheSky77/Brute-Force
286614e186fbe3e3f56156861c08403433c8acf4
cd3a8ba801dcdd1a36bdf580729607616292def9
refs/heads/master
2023-07-31T15:57:16.445787
2021-09-14T16:12:42
2021-09-14T16:12:42
288,410,773
0
0
null
2021-09-14T12:09:16
2020-08-18T09:21:38
C++
UTF-8
C++
false
false
190
h
#pragma once #include "IDataWriter.h" class FileWriter : public IDataWriter { public: virtual void WriteData(const std::string& filePath, const std::vector<unsigned char>& buf); };
53a84c0b311de458e9a9927de5d43d69d5b35ee2
d85c52b1b28cf2aedaf925bdcf8876ead2d39d26
/src/Editor/ImageEditor/ImageWindow/ImageWindow.cpp
10465c58bc5cf0773fe8ff6daacd2dbcde51c7dc
[ "MIT" ]
permissive
nicholasammann/elba
65c053c7d79bd67d09eb5df2356183605c9b9a18
8d7a8ae7c8b55b87ee7dcd02aaea1b175e6dd8ce
refs/heads/stable
2021-04-27T03:53:35.753179
2019-08-08T01:56:53
2019-08-08T01:56:53
122,722,831
1
0
MIT
2019-08-08T01:56:54
2018-02-24T09:02:43
C++
UTF-8
C++
false
false
5,142
cpp
#include <gl/glew.h> #include <qpainter.h> #include <qopenglpaintdevice.h> #include <qevent.h> #include "Elba/Core/CoreModule.hpp" #include "Elba/Core/Components/CS370/ResizeHandler.hpp" #include "Elba/Core/Components/CS370/ImageOperationHandler.hpp" #include "Elba/Core/Components/MAT362/GammaController.hpp" #include "Elba/Engine.hpp" #include "Elba/Graphics/OpenGL/OpenGLModule.hpp" #include "Elba/Graphics/OpenGL/OpenGLMesh.hpp" #include "Elba/Graphics/OpenGL/OpenGLSubmesh.hpp" #include "Elba/Graphics/OpenGL/OpenGLTexture.hpp" #include "Editor/ImageEditor/ImageEditor.hpp" #include "Editor/ImageEditor/ImageWindow/ImageWindow.hpp" #include "Elba/Utilities/Utils.hpp" namespace Editor { ImageWindow::ImageWindow(ImageEditor* editor, QWindow* parent) : QWindow(parent) , mEditor(editor) , mAnimating(false) , mContext(nullptr) , mDevice(nullptr) { glewExperimental = GL_TRUE; // Cache graphics module for easy use in render fn Elba::Engine* engine = mEditor->GetEngine(); Elba::GraphicsModule* graphicsModule = engine->GetGraphicsModule(); mGraphicsModule = graphicsModule; // Tell the window we're using OpenGL setSurfaceType(QWindow::OpenGLSurface); } ImageWindow::~ImageWindow() { } void ImageWindow::Render(QPainter* painter) { Q_UNUSED(painter); } void ImageWindow::Render() { if (!mDevice) { mDevice = new QOpenGLPaintDevice(); } const qreal retinaScale = devicePixelRatio(); int screenWidth = retinaScale * width(); int screenHeight = retinaScale * height(); glViewport(0, 0, screenWidth, screenHeight); mGraphicsModule->Render(screenWidth, screenHeight); mDevice->setSize(size()); } void ImageWindow::Initialize() { glEnable(GL_DEPTH_TEST); GLenum err = glewInit(); Elba::OpenGLModule* glModule = dynamic_cast<Elba::OpenGLModule*>(mGraphicsModule); if (glModule) { glModule->InitializePostProcessing(); Elba::OpenGLPostProcess* postProcess = glModule->GetPostProcess(); glModule->SetUseFramebuffer(true); } Elba::ResizeEvent resize; resize.oldSize = resize.newSize = glm::vec2(width(), height()); mGraphicsModule->OnResize(resize); } void ImageWindow::SetAnimating(bool animating) { mAnimating = animating; if (mAnimating) { RenderLater(); } } void ImageWindow::RenderLater() { requestUpdate(); } void ImageWindow::RenderNow() { if (!isExposed()) { return; } bool needsInitialize = false; if (!mContext) { mContext = new QOpenGLContext(this); mContext->setFormat(requestedFormat()); mContext->create(); needsInitialize = true; } mContext->makeCurrent(this); if (needsInitialize) { initializeOpenGLFunctions(); Initialize(); } Render(); mContext->swapBuffers(this); if (mAnimating) { RenderLater(); } if (needsInitialize) { // Test Level Elba::CoreModule* core = mEditor->GetEngine()->GetCoreModule(); Elba::Level* level = core->GetGameLevel(); Elba::Object* object = level->CreateChild(); Elba::Transform* transform = object->AddComponent<Elba::Transform>(); transform->SetWorldTranslation(glm::vec3(0.0f, 0.0f, -10.0f)); transform->SetWorldRotation(glm::quat(glm::vec3(glm::radians(90.0f), 0.0f, 0.0f))); transform->SetWorldScale(glm::vec3(size().width(), 1.0f, size().height())); Elba::Model* model = object->AddComponent<Elba::Model>(); model->LoadMesh("quad.fbx"); model->LoadShader("textured"); object->AddComponent<Elba::ImageOperationHandler>(); Elba::OpenGLMesh* mesh = static_cast<Elba::OpenGLMesh*>(model->GetMesh()); std::vector<Elba::OpenGLSubmesh>& submeshes = mesh->GetSubmeshes(); std::string assetsDir = Elba::Utils::GetAssetsDirectory(); std::string texturePath = assetsDir + "Textures/Test_images/apple-20.ppm"; // add and init ResizeHandler so it receives the TextureChange event Elba::ResizeHandler* resizeHandler = object->AddComponent<Elba::ResizeHandler>(); resizeHandler->Initialize(); // Load the texture for (auto it = submeshes.begin(); it != submeshes.end(); it++) { Elba::OpenGLTexture* texture = new Elba::OpenGLTexture(texturePath, Elba::OpenGLTexture::FileType::ppm); it->LoadTexture(texture); } auto gam = object->AddComponent<Elba::GammaController>(); gam->Initialize(); //////////////////////// } } bool ImageWindow::event(QEvent* event) { switch (event->type()) { case QEvent::UpdateRequest: { RenderNow(); return true; } case QEvent::Resize: { QResizeEvent* realEvent = static_cast<QResizeEvent*>(event); Elba::ResizeEvent resize; resize.oldSize = glm::vec2(realEvent->oldSize().width(), realEvent->oldSize().height()); resize.newSize = glm::vec2(realEvent->size().width(), realEvent->size().height()); mGraphicsModule->OnResize(resize); return QWindow::event(event); } default: { return QWindow::event(event); } } } void ImageWindow::exposeEvent(QExposeEvent* event) { Q_UNUSED(event); if (isExposed()) { RenderNow(); } } } // End of Editor namespace
13df6b1b9c0bf38de23f7d9559a1a336684c984a
6e09d72177402b133921a0cc611d4fbeabcf3aed
/Cpp/opencvTest/opencvTest/day01.cpp
647e01e61100128eb448c5ec84e1307687d7f263
[]
no_license
aravinda-kumar/Code
4f91617c79569cccb7bbf517a3699d16fa7e1377
eccdee6fe73237e2982b128a04813c854e4cfd4d
refs/heads/master
2020-05-01T10:31:20.940519
2019-03-24T05:09:01
2019-03-24T05:09:01
177,422,267
1
0
null
2019-03-24T13:59:14
2019-03-24T13:59:14
null
GB18030
C++
false
false
932
cpp
//#include <opencv2/opencv.hpp> //#include <iostream> // //using namespace std; //using namespace cv; // //int main() //{ // //从指定路径下读出图片,并且返回一个Mat对象 // Mat img = imread("D:\\个人文档\\1_学校\\课程\\图像处理\\lena.png"); // // //判断文件是否为空 // if (img.empty()) // { // cout << "can not find the image" << endl; // return -1; // } // // //创建一个窗口,显示原图像 // namedWindow("原图像", CV_WINDOW_AUTOSIZE); // imshow("原图像", img); // // //定义Mat对象,并将原图转换成灰度图 // Mat outImage; // cvtColor(img, outImage, COLOR_RGB2GRAY); // // //创建另一个窗口,显示灰度图像 // namedWindow("输出图像", WINDOW_AUTOSIZE); // imshow("输出图像", outImage); // // //保存生成的灰度图像 // imwrite("D:\\个人文档\\1_学校\\课程\\图像处理\\lenagray.png", outImage); // // waitKey(0); // return 0; //}
87417e9121608cea8a33d7a368c0c71c09b8d210
214dbcc732e0f6a49336164c793bd4af4754a6f7
/Algorithmics/Problems from various contests/reduceri.cpp
663bd8bd08a612254b92733320fc360e1f85cbe8
[]
no_license
IrinaMBejan/Personal-work-contests
f878c25507a8bfdab3f7af8d55b780d7632efecb
4ab2841244a55d074d25e721aefa56431e508c43
refs/heads/master
2021-01-20T08:24:47.492233
2017-05-03T12:22:26
2017-05-03T12:22:26
90,142,452
1
0
null
null
null
null
UTF-8
C++
false
false
899
cpp
#include <fstream> #include <cmath> #define Nmax 105 using namespace std; ifstream fin("reduceri.in"); ofstream fout("reduceri.out"); int A[Nmax][Nmax]; int v[Nmax]; int N; void Citire(); void DetSubpro(); void Afisare(); int Cost(int i, int j); int main() { Citire(); DetSubpro(); Afisare(); return 0; } void Citire() { int i; fin>>N; for(i=1; i<=N; i++) fin>>v[i]; } void DetSubpro() { int i,k,j,maxim; for(i=1;i<=N;i++) A[i][i]=v[i]; for(j=1;j<=N;j++) for(i=1;i+j<=N;i++) { //fout<<i<<" "<<i+j<<'\n'; maxim=Cost(i,i+j); for(k=i;k<i+j;k++) if(A[i][k]+A[k+1][i+j]>maxim) maxim=A[i][k]+A[k+1][i+j]; A[i][i+j]=maxim; } } void Afisare() { fout<<A[1][N]<<'\n'; } int Cost(int i, int j) { return abs(v[i]-v[j])*(j-i+1); }
9f85b7b8beaf2e816ea81a6a939c7f0a6b154af9
6c57b1f26dabd8bb24a41471ced5e0d1ac30735b
/BB/src/Sensor/SensorDataHelpers.cpp
6865fca80fe054c6c08a21ae7dbb1b9f437d20d4
[]
no_license
hadzim/bb
555bb50465fbd604c56c755cdee2cce796118322
a6f43a9780753242e5e9f2af804c5233af4a920e
refs/heads/master
2021-01-21T04:54:53.835407
2016-06-06T06:31:55
2016-06-06T06:31:55
17,916,029
0
0
null
null
null
null
UTF-8
C++
false
false
1,798
cpp
/* * SensorData.cpp * * Created on: 18.3.2014 * Author: JV */ #include "BB/Sensor/SensorDataHelpers.h" namespace BB { namespace SensorDataHelpers { TBS::BB::Services::Data::IDataDistributor::SensorDataReceivedArg sensorData2EventArg( const SensorData & s) { TBS::BB::Services::Data::IDataDistributor::SensorDataReceivedArg a; a.sensorDate = SensorData::date2string(s.getDate()); a.sensorName = s.getName(); a.sensorRawName = s.getRawName(); a.sensorStatus = (int) s.getSensorStatus(); a.sensorType = s.getType(); a.sensorUnit = s.getUnit(); a.sensorValue = s.getValue(); a.sensorTextValue = s.getTextValue(); return a; } SensorData eventArg2SensorData( const TBS::BB::Services::Data::IDataDistributor::SensorDataReceivedArg & a) { return SensorData(a.sensorType, a.sensorName, a.sensorRawName, a.sensorUnit, SensorData::string2date(a.sensorDate), (SensorData::Status) a.sensorStatus, a.sensorValue, a.sensorTextValue); } void sendData(TBS::BB::Services::Data::IDataCollector & collector, const SensorData & s) { collector.SendSensorData(s.getType(), s.getName(), s.getRawName(), s.getUnit(), BB::SensorData::date2string(s.getDate()), s.getSensorStatus(), s.getValue(), s.getTextValue()); } std::string sensorID(const std::string & sensorType, const std::string & sensorName) { return "<" + sensorType + "::" + sensorName + ">"; } std::string sensorID(const SensorData & s) { return sensorID(s.getType(), s.getName()); } std::string sensorID(const TBS::BB::WebUI::SensorInfo & i){ return sensorID(i.sensorType, i.sensorName); } std::string sensorRawID(const TBS::BB::WebUI::SensorInfo & i){ return sensorID(i.sensorType, i.sensorRawName); } std::string sensorRawID(const SensorData & s){ return sensorID(s.getType(), s.getRawName()); } } }
edfdb8c09c2280eec1bb4762f0a77cd8e9204ea1
5d62b79ec4640384a86081527f3c39ecb85e5598
/src/map.cpp
fd0fec812128e0377daea9be58bc34044374e2e4
[]
no_license
murilao/Otxserver-Global
c2b34cceea21c356aee10c2b420ab83637693e23
15d1c182edd6fd53a3cb746b078e270783b65237
refs/heads/master
2021-01-18T09:54:39.392553
2016-09-13T05:31:40
2016-09-13T05:31:40
68,126,748
0
1
null
2016-09-13T16:34:17
2016-09-13T16:34:16
null
UTF-8
C++
false
false
26,783
cpp
/** * The Forgotten Server - a free and open-source MMORPG server emulator * Copyright (C) 2016 Mark Samman <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "otpch.h" #include "iomap.h" #include "iomapserialize.h" #include "combat.h" #include "creature.h" #include "game.h" extern Game g_game; bool Map::loadMap(const std::string& identifier, bool loadHouses) { IOMap loader; if (!loader.loadMap(this, identifier)) { std::cout << "[Fatal - Map::loadMap] " << loader.getLastErrorString() << std::endl; return false; } if (!IOMap::loadSpawns(this)) { std::cout << "[Warning - Map::loadMap] Failed to load spawn data." << std::endl; } if (loadHouses) { if (!IOMap::loadHouses(this)) { std::cout << "[Warning - Map::loadMap] Failed to load house data." << std::endl; } IOMapSerialize::loadHouseInfo(); IOMapSerialize::loadHouseItems(this); } return true; } bool Map::save() { bool saved = false; for (uint32_t tries = 0; tries < 3; tries++) { if (IOMapSerialize::saveHouseInfo()) { saved = true; break; } } if (!saved) { return false; } saved = false; for (uint32_t tries = 0; tries < 3; tries++) { if (IOMapSerialize::saveHouseItems()) { saved = true; break; } } return saved; } Tile* Map::getTile(uint16_t x, uint16_t y, uint8_t z) const { if (z >= MAP_MAX_LAYERS) { return nullptr; } const QTreeLeafNode* leaf = QTreeNode::getLeafStatic<const QTreeLeafNode*, const QTreeNode*>(&root, x, y); if (!leaf) { return nullptr; } const Floor* floor = leaf->getFloor(z); if (!floor) { return nullptr; } return floor->tiles[x & FLOOR_MASK][y & FLOOR_MASK]; } void Map::setTile(uint16_t x, uint16_t y, uint8_t z, Tile* newTile) { if (z >= MAP_MAX_LAYERS) { std::cout << "ERROR: Attempt to set tile on invalid coordinate " << Position(x, y, z) << "!" << std::endl; return; } QTreeLeafNode::newLeaf = false; QTreeLeafNode* leaf = root.createLeaf(x, y, 15); if (QTreeLeafNode::newLeaf) { //update north QTreeLeafNode* northLeaf = root.getLeaf(x, y - FLOOR_SIZE); if (northLeaf) { northLeaf->leafS = leaf; } //update west leaf QTreeLeafNode* westLeaf = root.getLeaf(x - FLOOR_SIZE, y); if (westLeaf) { westLeaf->leafE = leaf; } //update south QTreeLeafNode* southLeaf = root.getLeaf(x, y + FLOOR_SIZE); if (southLeaf) { leaf->leafS = southLeaf; } //update east QTreeLeafNode* eastLeaf = root.getLeaf(x + FLOOR_SIZE, y); if (eastLeaf) { leaf->leafE = eastLeaf; } } Floor* floor = leaf->createFloor(z); uint32_t offsetX = x & FLOOR_MASK; uint32_t offsetY = y & FLOOR_MASK; Tile*& tile = floor->tiles[offsetX][offsetY]; if (tile) { TileItemVector* items = newTile->getItemList(); if (items) { for (auto it = items->rbegin(), end = items->rend(); it != end; ++it) { tile->addThing(*it); } items->clear(); } Item* ground = newTile->getGround(); if (ground) { tile->addThing(ground); newTile->setGround(nullptr); } delete newTile; } else { tile = newTile; } } bool Map::placeCreature(const Position& centerPos, Creature* creature, bool extendedPos/* = false*/, bool forceLogin/* = false*/) { bool foundTile; bool placeInPZ; Tile* tile = getTile(centerPos.x, centerPos.y, centerPos.z); if (tile) { placeInPZ = tile->hasFlag(TILESTATE_PROTECTIONZONE); ReturnValue ret = tile->queryAdd(0, *creature, 1, FLAG_IGNOREBLOCKITEM); foundTile = forceLogin || ret == RETURNVALUE_NOERROR || ret == RETURNVALUE_PLAYERISNOTINVITED; } else { placeInPZ = false; foundTile = false; } if (!foundTile) { static std::vector<std::pair<int32_t, int32_t>> extendedRelList { {0, -2}, {-1, -1}, {0, -1}, {1, -1}, {-2, 0}, {-1, 0}, {1, 0}, {2, 0}, {-1, 1}, {0, 1}, {1, 1}, {0, 2} }; static std::vector<std::pair<int32_t, int32_t>> normalRelList { {-1, -1}, {0, -1}, {1, -1}, {-1, 0}, {1, 0}, {-1, 1}, {0, 1}, {1, 1} }; std::vector<std::pair<int32_t, int32_t>>& relList = (extendedPos ? extendedRelList : normalRelList); if (extendedPos) { std::shuffle(relList.begin(), relList.begin() + 4, getRandomGenerator()); std::shuffle(relList.begin() + 4, relList.end(), getRandomGenerator()); } else { std::shuffle(relList.begin(), relList.end(), getRandomGenerator()); } for (const auto& it : relList) { Position tryPos(centerPos.x + it.first, centerPos.y + it.second, centerPos.z); tile = getTile(tryPos.x, tryPos.y, tryPos.z); if (!tile || (placeInPZ && !tile->hasFlag(TILESTATE_PROTECTIONZONE))) { continue; } if (tile->queryAdd(0, *creature, 1, 0) == RETURNVALUE_NOERROR) { if (!extendedPos || isSightClear(centerPos, tryPos, false)) { foundTile = true; break; } } } if (!foundTile) { return false; } } int32_t index = 0; uint32_t flags = 0; Item* toItem = nullptr; Cylinder* toCylinder = tile->queryDestination(index, *creature, &toItem, flags); toCylinder->internalAddThing(creature); const Position& dest = toCylinder->getPosition(); getQTNode(dest.x, dest.y)->addCreature(creature); return true; } void Map::moveCreature(Creature& creature, Tile& newTile, bool forceTeleport/* = false*/) { Tile& oldTile = *creature.getTile(); Position oldPos = oldTile.getPosition(); Position newPos = newTile.getPosition(); bool teleport = forceTeleport || !newTile.getGround() || !Position::areInRange<1, 1, 0>(oldPos, newPos); SpectatorVec list; getSpectators(list, oldPos, true); getSpectators(list, newPos, true); std::vector<int32_t> oldStackPosVector; for (Creature* spectator : list) { if (Player* tmpPlayer = spectator->getPlayer()) { if (tmpPlayer->canSeeCreature(&creature)) { oldStackPosVector.push_back(oldTile.getClientIndexOfCreature(tmpPlayer, &creature)); } else { oldStackPosVector.push_back(-1); } } } //remove the creature oldTile.removeThing(&creature, 0); QTreeLeafNode* leaf = getQTNode(oldPos.x, oldPos.y); QTreeLeafNode* new_leaf = getQTNode(newPos.x, newPos.y); // Switch the node ownership if (leaf != new_leaf) { leaf->removeCreature(&creature); new_leaf->addCreature(&creature); } //add the creature newTile.addThing(&creature); if (!teleport) { if (oldPos.y > newPos.y) { creature.setDirection(DIRECTION_NORTH); } else if (oldPos.y < newPos.y) { creature.setDirection(DIRECTION_SOUTH); } if (oldPos.x < newPos.x) { creature.setDirection(DIRECTION_EAST); } else if (oldPos.x > newPos.x) { creature.setDirection(DIRECTION_WEST); } } //send to client size_t i = 0; for (Creature* spectator : list) { if (Player* tmpPlayer = spectator->getPlayer()) { //Use the correct stackpos int32_t stackpos = oldStackPosVector[i++]; if (stackpos != -1) { tmpPlayer->sendCreatureMove(&creature, newPos, newTile.getStackposOfCreature(tmpPlayer, &creature), oldPos, stackpos, teleport); } } } //event method for (Creature* spectator : list) { spectator->onCreatureMove(&creature, &newTile, newPos, &oldTile, oldPos, teleport); } oldTile.postRemoveNotification(&creature, &newTile, 0); newTile.postAddNotification(&creature, &oldTile, 0); } void Map::getSpectatorsInternal(SpectatorVec& list, const Position& centerPos, int32_t minRangeX, int32_t maxRangeX, int32_t minRangeY, int32_t maxRangeY, int32_t minRangeZ, int32_t maxRangeZ, bool onlyPlayers) const { int_fast16_t min_y = centerPos.y + minRangeY; int_fast16_t min_x = centerPos.x + minRangeX; int_fast16_t max_y = centerPos.y + maxRangeY; int_fast16_t max_x = centerPos.x + maxRangeX; int32_t minoffset = centerPos.getZ() - maxRangeZ; uint16_t x1 = std::min<uint32_t>(0xFFFF, std::max<int32_t>(0, (min_x + minoffset))); uint16_t y1 = std::min<uint32_t>(0xFFFF, std::max<int32_t>(0, (min_y + minoffset))); int32_t maxoffset = centerPos.getZ() - minRangeZ; uint16_t x2 = std::min<uint32_t>(0xFFFF, std::max<int32_t>(0, (max_x + maxoffset))); uint16_t y2 = std::min<uint32_t>(0xFFFF, std::max<int32_t>(0, (max_y + maxoffset))); int32_t startx1 = x1 - (x1 % FLOOR_SIZE); int32_t starty1 = y1 - (y1 % FLOOR_SIZE); int32_t endx2 = x2 - (x2 % FLOOR_SIZE); int32_t endy2 = y2 - (y2 % FLOOR_SIZE); const QTreeLeafNode* startLeaf = QTreeNode::getLeafStatic<const QTreeLeafNode*, const QTreeNode*>(&root, startx1, starty1); const QTreeLeafNode* leafS = startLeaf; const QTreeLeafNode* leafE; for (int_fast32_t ny = starty1; ny <= endy2; ny += FLOOR_SIZE) { leafE = leafS; for (int_fast32_t nx = startx1; nx <= endx2; nx += FLOOR_SIZE) { if (leafE) { const CreatureVector& node_list = (onlyPlayers ? leafE->player_list : leafE->creature_list); for (Creature* creature : node_list) { const Position& cpos = creature->getPosition(); if (minRangeZ > cpos.z || maxRangeZ < cpos.z) { continue; } int_fast16_t offsetZ = Position::getOffsetZ(centerPos, cpos); if ((min_y + offsetZ) > cpos.y || (max_y + offsetZ) < cpos.y || (min_x + offsetZ) > cpos.x || (max_x + offsetZ) < cpos.x) { continue; } list.insert(creature); } leafE = leafE->leafE; } else { leafE = QTreeNode::getLeafStatic<const QTreeLeafNode*, const QTreeNode*>(&root, nx + FLOOR_SIZE, ny); } } if (leafS) { leafS = leafS->leafS; } else { leafS = QTreeNode::getLeafStatic<const QTreeLeafNode*, const QTreeNode*>(&root, startx1, ny + FLOOR_SIZE); } } } void Map::getSpectators(SpectatorVec& list, const Position& centerPos, bool multifloor /*= false*/, bool onlyPlayers /*= false*/, int32_t minRangeX /*= 0*/, int32_t maxRangeX /*= 0*/, int32_t minRangeY /*= 0*/, int32_t maxRangeY /*= 0*/) { if (centerPos.z >= MAP_MAX_LAYERS) { return; } bool foundCache = false; bool cacheResult = false; minRangeX = (minRangeX == 0 ? -maxViewportX : -minRangeX); maxRangeX = (maxRangeX == 0 ? maxViewportX : maxRangeX); minRangeY = (minRangeY == 0 ? -maxViewportY : -minRangeY); maxRangeY = (maxRangeY == 0 ? maxViewportY : maxRangeY); if (minRangeX == -maxViewportX && maxRangeX == maxViewportX && minRangeY == -maxViewportY && maxRangeY == maxViewportY && multifloor) { if (onlyPlayers) { auto it = playersSpectatorCache.find(centerPos); if (it != playersSpectatorCache.end()) { if (!list.empty()) { const SpectatorVec& cachedList = it->second; list.insert(cachedList.begin(), cachedList.end()); } else { list = it->second; } foundCache = true; } } if (!foundCache) { auto it = spectatorCache.find(centerPos); if (it != spectatorCache.end()) { if (!onlyPlayers) { if (!list.empty()) { const SpectatorVec& cachedList = it->second; list.insert(cachedList.begin(), cachedList.end()); } else { list = it->second; } } else { const SpectatorVec& cachedList = it->second; for (Creature* spectator : cachedList) { if (spectator->getPlayer()) { list.insert(spectator); } } } foundCache = true; } else { cacheResult = true; } } } if (!foundCache) { int32_t minRangeZ; int32_t maxRangeZ; if (multifloor) { if (centerPos.z > 7) { //underground //8->15 minRangeZ = std::max<int32_t>(centerPos.getZ() - 2, 0); maxRangeZ = std::min<int32_t>(centerPos.getZ() + 2, MAP_MAX_LAYERS - 1); } else if (centerPos.z == 6) { minRangeZ = 0; maxRangeZ = 8; } else if (centerPos.z == 7) { minRangeZ = 0; maxRangeZ = 9; } else { minRangeZ = 0; maxRangeZ = 7; } } else { minRangeZ = centerPos.z; maxRangeZ = centerPos.z; } getSpectatorsInternal(list, centerPos, minRangeX, maxRangeX, minRangeY, maxRangeY, minRangeZ, maxRangeZ, onlyPlayers); if (cacheResult) { if (onlyPlayers) { playersSpectatorCache[centerPos] = list; } else { spectatorCache[centerPos] = list; } } } } void Map::clearSpectatorCache() { spectatorCache.clear(); playersSpectatorCache.clear(); } bool Map::canThrowObjectTo(const Position& fromPos, const Position& toPos, bool checkLineOfSight /*= true*/, int32_t rangex /*= Map::maxClientViewportX*/, int32_t rangey /*= Map::maxClientViewportY*/, Creature* creature /*=false*/) const { //z checks //underground 8->15 //ground level and above 7->0 if ((fromPos.z >= 8 && toPos.z < 8) || (toPos.z >= 8 && fromPos.z < 8)) { return false; } int32_t deltaz = Position::getDistanceZ(fromPos, toPos); if (deltaz > 2) { return false; } if ((Position::getDistanceX(fromPos, toPos) - deltaz) > rangex) { return false; } //distance checks if ((Position::getDistanceY(fromPos, toPos) - deltaz) > rangey) { return false; } if (!checkLineOfSight) { return true; } return isSightClear(fromPos, toPos, false, creature); } bool Map::checkSightLine(const Position& fromPos, const Position& toPos, Creature* caster) const { if (fromPos == toPos) { return true; } Position start(fromPos.z > toPos.z ? toPos : fromPos); Position destination(fromPos.z > toPos.z ? fromPos : toPos); const int8_t mx = start.x < destination.x ? 1 : start.x == destination.x ? 0 : -1; const int8_t my = start.y < destination.y ? 1 : start.y == destination.y ? 0 : -1; int32_t A = Position::getOffsetY(destination, start); int32_t B = Position::getOffsetX(start, destination); int32_t C = -(A * destination.x + B * destination.y); while (start.x != destination.x || start.y != destination.y) { int32_t move_hor = std::abs(A * (start.x + mx) + B * (start.y) + C); int32_t move_ver = std::abs(A * (start.x) + B * (start.y + my) + C); int32_t move_cross = std::abs(A * (start.x + mx) + B * (start.y + my) + C); if (start.y != destination.y && (start.x == destination.x || move_hor > move_ver || move_hor > move_cross)) { start.y += my; } if (start.x != destination.x && (start.y == destination.y || move_ver > move_hor || move_ver > move_cross)) { start.x += mx; } const Tile* tile = getTile(start.x, start.y, start.z); if (tile && tile->hasProperty(CONST_PROP_BLOCKPROJECTILE, caster)) { return false; } } // now we need to perform a jump between floors to see if everything is clear (literally) while (start.z != destination.z) { const Tile* tile = getTile(start.x, start.y, start.z); if (tile && tile->getThingCount() > 0) { return false; } start.z++; } return true; } bool Map::isSightClear(const Position& fromPos, const Position& toPos, bool floorCheck, Creature* caster) const { if (floorCheck && fromPos.z != toPos.z) { return false; } // Cast two converging rays and see if either yields a result. return checkSightLine(fromPos, toPos, caster) || checkSightLine(toPos, fromPos, caster); } const Tile* Map::canWalkTo(const Creature& creature, const Position& pos) const { int32_t walkCache = creature.getWalkCache(pos); if (walkCache == 0) { return nullptr; } else if (walkCache == 1) { return getTile(pos.x, pos.y, pos.z); } //used for non-cached tiles Tile* tile = getTile(pos.x, pos.y, pos.z); if (creature.getTile() != tile) { if (!tile || tile->queryAdd(0, creature, 1, FLAG_PATHFINDING | FLAG_IGNOREFIELDDAMAGE) != RETURNVALUE_NOERROR) { return nullptr; } } return tile; } bool Map::getPathMatching(const Creature& creature, std::forward_list<Direction>& dirList, const FrozenPathingConditionCall& pathCondition, const FindPathParams& fpp) const { Position pos = creature.getPosition(); Position endPos; AStarNodes nodes(pos.x, pos.y); int32_t bestMatch = 0; static int_fast32_t dirNeighbors[8][5][2] = { {{-1, 0}, {0, 1}, {1, 0}, {1, 1}, {-1, 1}}, {{-1, 0}, {0, 1}, {0, -1}, {-1, -1}, {-1, 1}}, {{-1, 0}, {1, 0}, {0, -1}, {-1, -1}, {1, -1}}, {{0, 1}, {1, 0}, {0, -1}, {1, -1}, {1, 1}}, {{1, 0}, {0, -1}, {-1, -1}, {1, -1}, {1, 1}}, {{-1, 0}, {0, -1}, {-1, -1}, {1, -1}, {-1, 1}}, {{0, 1}, {1, 0}, {1, -1}, {1, 1}, {-1, 1}}, {{-1, 0}, {0, 1}, {-1, -1}, {1, 1}, {-1, 1}} }; static int_fast32_t allNeighbors[8][2] = { {-1, 0}, {0, 1}, {1, 0}, {0, -1}, {-1, -1}, {1, -1}, {1, 1}, {-1, 1} }; const Position startPos = pos; AStarNode* found = nullptr; while (fpp.maxSearchDist != 0 || nodes.getClosedNodes() < 100) { AStarNode* n = nodes.getBestNode(); if (!n) { if (found) { break; } return false; } const int_fast32_t x = n->x; const int_fast32_t y = n->y; pos.x = x; pos.y = y; if (pathCondition(startPos, pos, fpp, bestMatch)) { found = n; endPos = pos; if (bestMatch == 0) { break; } } uint_fast32_t dirCount; int_fast32_t* neighbors; if (n->parent) { const int_fast32_t offset_x = n->parent->x - x; const int_fast32_t offset_y = n->parent->y - y; if (offset_y == 0) { if (offset_x == -1) { neighbors = *dirNeighbors[DIRECTION_WEST]; } else { neighbors = *dirNeighbors[DIRECTION_EAST]; } } else if (!fpp.allowDiagonal || offset_x == 0) { if (offset_y == -1) { neighbors = *dirNeighbors[DIRECTION_NORTH]; } else { neighbors = *dirNeighbors[DIRECTION_SOUTH]; } } else if (offset_y == -1) { if (offset_x == -1) { neighbors = *dirNeighbors[DIRECTION_NORTHWEST]; } else { neighbors = *dirNeighbors[DIRECTION_NORTHEAST]; } } else if (offset_x == -1) { neighbors = *dirNeighbors[DIRECTION_SOUTHWEST]; } else { neighbors = *dirNeighbors[DIRECTION_SOUTHEAST]; } dirCount = fpp.allowDiagonal ? 5 : 3; } else { dirCount = 8; neighbors = *allNeighbors; } const int_fast32_t f = n->f; for (uint_fast32_t i = 0; i < dirCount; ++i) { pos.x = x + *neighbors++; pos.y = y + *neighbors++; if (fpp.maxSearchDist != 0 && (Position::getDistanceX(startPos, pos) > fpp.maxSearchDist || Position::getDistanceY(startPos, pos) > fpp.maxSearchDist)) { continue; } if (fpp.keepDistance && !pathCondition.isInRange(startPos, pos, fpp)) { continue; } const Tile* tile; AStarNode* neighborNode = nodes.getNodeByPosition(pos.x, pos.y); if (neighborNode) { tile = getTile(pos.x, pos.y, pos.z); } else { tile = canWalkTo(creature, pos); if (!tile) { continue; } } //The cost (g) for this neighbor const int_fast32_t cost = AStarNodes::getMapWalkCost(n, pos); const int_fast32_t extraCost = AStarNodes::getTileWalkCost(creature, tile); const int_fast32_t newf = f + cost + extraCost; if (neighborNode) { if (neighborNode->f <= newf) { //The node on the closed/open list is cheaper than this one continue; } neighborNode->f = newf; neighborNode->parent = n; nodes.openNode(neighborNode); } else { //Does not exist in the open/closed list, create a new node neighborNode = nodes.createOpenNode(n, pos.x, pos.y, newf); if (!neighborNode) { if (found) { break; } return false; } } } nodes.closeNode(n); } if (!found) { return false; } int_fast32_t prevx = endPos.x; int_fast32_t prevy = endPos.y; found = found->parent; while (found) { pos.x = found->x; pos.y = found->y; int_fast32_t dx = pos.getX() - prevx; int_fast32_t dy = pos.getY() - prevy; prevx = pos.x; prevy = pos.y; if (dx == 1 && dy == 1) { dirList.push_front(DIRECTION_NORTHWEST); } else if (dx == -1 && dy == 1) { dirList.push_front(DIRECTION_NORTHEAST); } else if (dx == 1 && dy == -1) { dirList.push_front(DIRECTION_SOUTHWEST); } else if (dx == -1 && dy == -1) { dirList.push_front(DIRECTION_SOUTHEAST); } else if (dx == 1) { dirList.push_front(DIRECTION_WEST); } else if (dx == -1) { dirList.push_front(DIRECTION_EAST); } else if (dy == 1) { dirList.push_front(DIRECTION_NORTH); } else if (dy == -1) { dirList.push_front(DIRECTION_SOUTH); } found = found->parent; } return true; } // AStarNodes AStarNodes::AStarNodes(uint32_t x, uint32_t y) : nodes(), openNodes() { curNode = 1; closedNodes = 0; openNodes[0] = true; AStarNode& startNode = nodes[0]; startNode.parent = nullptr; startNode.x = x; startNode.y = y; startNode.f = 0; nodeTable[(x << 16) | y] = nodes; } AStarNode* AStarNodes::createOpenNode(AStarNode* parent, uint32_t x, uint32_t y, int_fast32_t f) { if (curNode >= MAX_NODES) { return nullptr; } size_t retNode = curNode++; openNodes[retNode] = true; AStarNode* node = nodes + retNode; nodeTable[(x << 16) | y] = node; node->parent = parent; node->x = x; node->y = y; node->f = f; return node; } AStarNode* AStarNodes::getBestNode() { if (curNode == 0) { return nullptr; } int32_t best_node_f = std::numeric_limits<int32_t>::max(); int32_t best_node = -1; for (size_t i = 0; i < curNode; i++) { if (openNodes[i] && nodes[i].f < best_node_f) { best_node_f = nodes[i].f; best_node = i; } } if (best_node >= 0) { return nodes + best_node; } return nullptr; } void AStarNodes::closeNode(AStarNode* node) { size_t index = node - nodes; assert(index < MAX_NODES); openNodes[index] = false; ++closedNodes; } void AStarNodes::openNode(AStarNode* node) { size_t index = node - nodes; assert(index < MAX_NODES); if (!openNodes[index]) { openNodes[index] = true; --closedNodes; } } int_fast32_t AStarNodes::getClosedNodes() const { return closedNodes; } AStarNode* AStarNodes::getNodeByPosition(uint32_t x, uint32_t y) { auto it = nodeTable.find((x << 16) | y); if (it == nodeTable.end()) { return nullptr; } return it->second; } int_fast32_t AStarNodes::getMapWalkCost(AStarNode* node, const Position& neighborPos) { if (std::abs(node->x - neighborPos.x) == std::abs(node->y - neighborPos.y)) { //diagonal movement extra cost return MAP_DIAGONALWALKCOST; } return MAP_NORMALWALKCOST; } int_fast32_t AStarNodes::getTileWalkCost(const Creature& creature, const Tile* tile) { int_fast32_t cost = 0; if (tile->getTopVisibleCreature(&creature) != nullptr) { //destroy creature cost cost += MAP_NORMALWALKCOST * 3; } if (const MagicField* field = tile->getFieldItem()) { CombatType_t combatType = field->getCombatType(); if (!creature.isImmune(combatType) && !creature.hasCondition(Combat::DamageToConditionType(combatType))) { cost += MAP_NORMALWALKCOST * 18; } } return cost; } // Floor Floor::~Floor() { for (uint32_t i = 0; i < FLOOR_SIZE; ++i) { for (uint32_t j = 0; j < FLOOR_SIZE; ++j) { delete tiles[i][j]; } } } // QTreeNode QTreeNode::QTreeNode() { leaf = false; child[0] = nullptr; child[1] = nullptr; child[2] = nullptr; child[3] = nullptr; } QTreeNode::~QTreeNode() { delete child[0]; delete child[1]; delete child[2]; delete child[3]; } QTreeLeafNode* QTreeNode::getLeaf(uint32_t x, uint32_t y) { if (leaf) { return static_cast<QTreeLeafNode*>(this); } QTreeNode* node = child[((x & 0x8000) >> 15) | ((y & 0x8000) >> 14)]; if (!node) { return nullptr; } return node->getLeaf(x << 1, y << 1); } QTreeLeafNode* QTreeNode::createLeaf(uint32_t x, uint32_t y, uint32_t level) { if (!isLeaf()) { uint32_t index = ((x & 0x8000) >> 15) | ((y & 0x8000) >> 14); if (!child[index]) { if (level != FLOOR_BITS) { child[index] = new QTreeNode(); } else { child[index] = new QTreeLeafNode(); QTreeLeafNode::newLeaf = true; } } return child[index]->createLeaf(x * 2, y * 2, level - 1); } return static_cast<QTreeLeafNode*>(this); } // QTreeLeafNode bool QTreeLeafNode::newLeaf = false; QTreeLeafNode::QTreeLeafNode() { for (uint32_t i = 0; i < MAP_MAX_LAYERS; ++i) { array[i] = nullptr; } leaf = true; leafS = nullptr; leafE = nullptr; } QTreeLeafNode::~QTreeLeafNode() { for (uint32_t i = 0; i < MAP_MAX_LAYERS; ++i) { delete array[i]; } } Floor* QTreeLeafNode::createFloor(uint32_t z) { if (!array[z]) { array[z] = new Floor(); } return array[z]; } void QTreeLeafNode::addCreature(Creature* c) { creature_list.push_back(c); if (c->getPlayer()) { player_list.push_back(c); } } void QTreeLeafNode::removeCreature(Creature* c) { CreatureVector::iterator iter = std::find(creature_list.begin(), creature_list.end(), c); assert(iter != creature_list.end()); *iter = creature_list.back(); creature_list.pop_back(); if (c->getPlayer()) { iter = std::find(player_list.begin(), player_list.end(), c); assert(iter != player_list.end()); *iter = player_list.back(); player_list.pop_back(); } } uint32_t Map::clean() const { uint64_t start = OTSYS_TIME(); size_t count = 0, tiles = 0; if (g_game.getGameState() == GAME_STATE_NORMAL) { g_game.setGameState(GAME_STATE_MAINTAIN); } std::vector<const QTreeNode*> nodes { &root }; std::vector<Item*> toRemove; do { const QTreeNode* node = nodes.back(); nodes.pop_back(); if (node->isLeaf()) { const QTreeLeafNode* leafNode = static_cast<const QTreeLeafNode*>(node); for (uint8_t z = 0; z < MAP_MAX_LAYERS; ++z) { Floor* floor = leafNode->getFloor(z); if (!floor) { continue; } for (size_t x = 0; x < FLOOR_SIZE; ++x) { for (size_t y = 0; y < FLOOR_SIZE; ++y) { Tile* tile = floor->tiles[x][y]; if (!tile || tile->hasFlag(TILESTATE_PROTECTIONZONE)) { continue; } TileItemVector* itemList = tile->getItemList(); if (!itemList) { continue; } ++tiles; for (Item* item : *itemList) { if (item->isCleanable()) { toRemove.push_back(item); } } for (Item* item : toRemove) { g_game.internalRemoveItem(item, -1); } count += toRemove.size(); toRemove.clear(); } } } } else { for (size_t i = 0; i < 4; ++i) { QTreeNode* childNode = node->child[i]; if (childNode) { nodes.push_back(childNode); } } } } while (!nodes.empty()); if (g_game.getGameState() == GAME_STATE_MAINTAIN) { g_game.setGameState(GAME_STATE_NORMAL); } std::cout << "> CLEAN: Removed " << count << " item" << (count != 1 ? "s" : "") << " from " << tiles << " tile" << (tiles != 1 ? "s" : "") << " in " << (OTSYS_TIME() - start) / (1000.) << " seconds." << std::endl; return count; }
46a5ee1958f4006c6417c512878adfba00a0d403
af990b2d28c7a83c8642d89cd56609c8103047b8
/Linguagem C e C++/Flood Fill Segmentation/flood.cpp
759c4a68d7bd9874913650bc54311bb8f0b871ce
[]
no_license
vzanoon/Processamento-Digital-de-Imagens
154613d1475b9f77bb42998d14753248be5d5e3a
83b88d9d999f390e41b768f212ec76970d0e33ce
refs/heads/master
2020-06-05T01:07:44.428058
2019-06-18T15:34:18
2019-06-18T15:34:18
192,261,055
0
0
null
null
null
null
UTF-8
C++
false
false
10,708
cpp
/************************************************************************************************************************ Universidade Federal de Santa Catarina (UFSC) Departamento de Computação (DEC) Disciplina: Processamento Digital de Imagens e Visão Computacional Docente: Antônio Sobieranski Discente: Vinícius Rodrigues Zanon - 15102833 Objetivos: Implementação do Algoritmo Flood Fill Segmentation iterativo, sem o uso da recursividade. O algoritmo, implementa uma pilha de execução para obter maior controle do que está sendo de fato inspecionado. Possui característica de busca iterativa nas direções up, down, right e left. Além do mais, para cada região encontrada é atribuído uma cor randômica pertencente ao RGB, para caracterizar ou identificar a região destacada. A regra de similaridade é baseada na distância euclidiana entre os pontos RGB e limitada por um threshold passado como parâmetro. Obs.: Algoritmo aqui desenvolvido é uma versão adaptada do código disponibilizado pelo professor Antônio Sobieranski no semestre passado. ***********************************************************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <vector> #include <iostream> using namespace std; class Color { public: unsigned char m_r,m_g,m_b; Color(unsigned char r, unsigned char g, unsigned char b) : m_r(r), m_g(g), m_b(b) {}; }; class Point{ public: int m_x, m_y; Point(int x, int y) : m_x(x), m_y(y) {}; }; class Flood{ private: unsigned int* m_indexMap; unsigned char* m_data; unsigned int m_W, m_H; unsigned int m_numberOfRegions; // Funcao que percorre iterativamente a imagem nas direcoes (UP, DOWN, LEFT, RIGHT) int validatePosition(unsigned int x, unsigned int y, float threshold){ //Movendo para cima if(y > 0){ if(m_indexMap[(y-1)*m_W+x] == 0){ int actual = y*m_W*3+x*3; int next = (y-1)*m_W*3+x*3; int r_actual = m_data[actual+0]; int r_next = m_data[next+0]; int g_actual = m_data[actual+1]; int g_next = m_data[next+1]; int b_actual = m_data[actual+2]; int b_next = m_data[next+2]; float dist = float(pow((r_actual-r_next),2) + pow((g_actual-g_next),2) + pow((b_actual-b_next),2)); dist = float (sqrt(dist)); if(dist < threshold) return 1; } } //Movendo para esquerda if(x > 0){ if(m_indexMap[y*m_W+(x-1)] == 0){ int actual = y*m_W*3+x*3; int next = y*m_W*3+(x-1)*3; int r_actual = m_data[actual+0]; int r_next = m_data[next+0]; int g_actual = m_data[actual+1]; int g_next = m_data[next+1]; int b_actual = m_data[actual+2]; int b_next = m_data[next+2]; float dist = float (pow((r_actual-r_next),2) + pow((b_actual-b_next),2) + pow((g_actual-g_next),2)); dist = sqrt(dist); if(dist < threshold) return 2; } } // Movendo para baixo if(y < m_H-1){ if(m_indexMap[(y+1)*m_W+x] == 0){ int actual = y*m_W*3+x*3; int next = (y+1)*m_W*3+x*3; int r_actual = m_data[actual+0]; int r_next = m_data[next+0]; int g_actual = m_data[actual+1]; int g_next = m_data[next+1]; int b_actual = m_data[actual+2]; int b_next = m_data[next+2]; float dist = float (pow((r_actual-r_next),2) + pow((b_actual-b_next),2) + pow((g_actual-g_next),2)); dist = sqrt(dist); if(dist < threshold) return 3; } } //Movendo para direita if(x < m_W-1){ if(m_indexMap[y*m_W+x+1] == 0){ int actual = y*m_W*3+x*3; int next = y*m_W*3+(x+1)*3; int r_actual = m_data[actual+0]; int r_next = m_data[next+0]; int g_actual = m_data[actual+1]; int g_next = m_data[next+1]; int b_actual = m_data[actual+2]; int b_next = m_data[next+2]; float dist = float (pow((r_actual-r_next),2) + pow((b_actual-b_next),2) + pow((g_actual-g_next),2)); dist = sqrt(dist); if(dist < threshold) return 4; } } return 0; } public: //Construtor Flood(){ m_data = NULL; m_indexMap = NULL; m_W = 0; m_H = 0; m_numberOfRegions = 0; } //Destrutor ~Flood(){ if(m_data) free(m_data); if(m_indexMap) free(m_indexMap); }; // Configura Imagem (tamanho e alocacao/liberacao de memoria) void SetData(unsigned char* data, unsigned int W, unsigned int H){ if(m_data) free(m_data); m_data = data; m_W = W; m_H = H; if(m_indexMap) free(m_indexMap); m_indexMap= new unsigned int[m_W*m_H]; } // Funcao que controla a pilha de execucao conforme a busca direcionada void ExtractPartition(unsigned int x, unsigned int y, float threshold, unsigned int index){ vector< Point > stack; stack.push_back( Point(x,y) ); unsigned int indexToMark = index; m_indexMap[y*m_W+x] = indexToMark; m_numberOfRegions++; while(stack.size() > 0){ int pos = validatePosition(x,y,threshold); if(pos == 1){ m_indexMap[(y-1)*m_W+x-0] = indexToMark; y--; stack.push_back(Point(x,y)); } if(pos == 2){ m_indexMap[(y-0)*m_W+x-1] = indexToMark; x--; stack.push_back(Point(x,y)); } if(pos == 3){ m_indexMap[(y+1)*m_W+x+0] = indexToMark; y++; stack.push_back(Point(x,y)); } if(pos == 4){ m_indexMap[(y+0)*m_W+x+1] = indexToMark; x++; stack.push_back(Point(x,y)); } if(pos == 0){ x = stack.at(stack.size()-1).m_x; y = stack.at(stack.size()-1).m_y; stack.pop_back(); } } } // Funcao que realiza o FloodFill unsigned char* FloodFill(){ unsigned char* result = new unsigned char[m_W*m_H*3]; std::vector<Color> rndcolors; for(unsigned int i = 0; i < m_numberOfRegions; i++){ rndcolors.push_back(Color(rand()%256,rand()%256,rand()%256)); } for(unsigned int i=0; i<m_H; i++){ for(unsigned int j=0; j<m_W; j++){ unsigned int index = (i*m_W*3+j*3); if(m_indexMap[index/3] > 0){ result[index+0] = rndcolors.at(m_indexMap[index/3]-1).m_r; result[index+1] = rndcolors.at(m_indexMap[index/3]-1).m_g; result[index+2] = rndcolors.at(m_indexMap[index/3]-1).m_b; } else{ result[index+0] = 255; result[index+1] = 0; result[index+2] = 0; } } } return result; } // Verificacao a existencia de index bool isAvailable(unsigned int i, unsigned int j){ if(m_indexMap[i*m_W+j] > 0) return false; return true; } unsigned int getNumberOfRegions() const{ return m_numberOfRegions; }; }; unsigned char* readPPM(const char* filename, unsigned int &W, unsigned int &H); bool savePPM(const char* filename, unsigned char* data, unsigned int W, unsigned int H); int main(int argc, const char* argv[]){ if(argc != 3){ cout << "Erro! Entrada deveria ser <exec inputfile.pgm threshold>" << endl; return 1; } unsigned int W, H=W=0; unsigned char* data=readPPM(argv[1], W,H); if(data==NULL){ cout << "Erro! Arquivo nao encontrado!" << endl; return 2; } Flood segmentator; segmentator.SetData(data, W, H); unsigned int k=0; for(unsigned int i=0; i<H; i++){ for(unsigned int j=0; j<W; j++){ if(segmentator.isAvailable(i,j)){ segmentator.ExtractPartition(j,i, atoi(argv[2]), ++k); } } } unsigned char* result1 = segmentator.FloodFill(); savePPM("FloodFill.ppm", result1, W, H); system("pause"); return 0; } unsigned char* readPPM(const char* filename, unsigned int &W, unsigned int &H){ cout << "Reading image : " << filename << endl; char type[2]; FILE* fp = fopen(filename, "r"); if(!fp) return NULL; fscanf(fp, "%c", &type[0]); fscanf(fp, "%c", &type[1]); cout << "Type : " << type << endl; W=H=0; fscanf(fp, "%d %d 255", &W, &H); cout << "Image Dimensions: W: " << W << ", H: " << H << endl; unsigned char* data; data = new unsigned char[W*H*3]; for(unsigned int i=0; i<W*H*3; i++){ fscanf(fp, "%d ", &data[i]); } fclose(fp); return data; } bool savePPM(const char* filename, unsigned char* data, unsigned int W, unsigned int H){ cout << "Saving image : " << filename << endl; FILE* fp = fopen(filename, "w"); if(!fp) return false; fprintf(fp, "P3\n"); fprintf(fp, "%d %d 255\n", W, H); for(unsigned int i=0; i<W*H*3; i++){ fprintf(fp, "%d ", data[i]); } fclose(fp); return true; }
bb26282a2447a9ef47c1d3e4adf0b40825ac83d0
a15f8dfce3172227c7f47e8b072d6a18a3931eb3
/C++/p11/search.cxx
80b394f08b7890a5d78adec25393d17141ddb8df
[]
no_license
mwalkerhg/C
fa31a7c41db37ed319e4bc0c47ad2166de1adeb2
42bfe3e951558fb5bcdcecd82a5e590e2f702eca
refs/heads/master
2020-04-20T23:44:57.280903
2019-02-05T02:09:08
2019-02-05T02:09:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,167
cxx
#include "search.h" void QuickSortHelper(int idList[],int start,int end); int partition(int idList[], int start, int end); // Constructor search::search(ifstream& inFile) { for(int i = 0; i < tableSize; i++) inFile >> idList[i]; for(int i = 0; i < hashTableSize; i++) hashList[i] = -1; } void search::PrintArray(ofstream& outFile) { for(int i = 0; i < hashTableSize; i++) outFile << hashList[i] << endl; } // Sequential Search void search::seqSearch(ofstream& outFile, int data, float& num) { int count = 0; for(int i = 0; i < tableSize; i++) { count++; if(data == idList[i]) break; } outFile << data << " " << count << endl; num += count; } // Quick Sort void search::QuickSort() { int start = 0; int end = tableSize; QuickSortHelper(idList, start, end); } void QuickSortHelper(int idList[],int start,int end) { if(start >= end)return; int pIndex = partition(idList,start,end); QuickSortHelper(idList,start,pIndex - 1); QuickSortHelper(idList,pIndex + 1, end); } int partition(int idList[], int start, int end) { int pivot = idList[end]; int pIndex = start; for(int i = start; i <= (end - 1); i++) { if(idList[i]<= pivot) { int temp = idList[i]; idList[i] = idList[pIndex]; idList[pIndex] = temp; pIndex = pIndex +1; } } int temp = idList[pIndex]; idList[pIndex] = idList[end]; idList[end] = temp; return pIndex; } void search::binSearch(ofstream& outFile, int data, float& num) { int first = 0; int last = tableSize -1; int middle = 0; bool found = false; int count = 0; while(last >= first && !found) { middle = (first + last) /2; if(data < idList[middle]) { last = middle - 1; count ++; } else if (data > idList[middle]) { first = middle + 1; count ++; } else { found = true; count++; } } outFile << data << " " << count << endl; num += count; } void search::hashSort(int data) { int key = data % 37; for(int i = 0; i < hashTableSize; i++) { if(hashList[key] == -1) { hashList[key] = data; break; } else key++; } } void search::hashSearch(ofstream& outFile, int data, float& num) { int key = data % 37; int count = 1; for(int i = 0; i < hashTableSize; i++) { if(hashList[key] == data) { outFile << hashList[key] << " " << count << endl; num += count; break; } else { count++; key++; } } } void search::doubHashSort(int data) { int key = data % 37; int col = 0; for(int i = 0; i < hashTableSize; i++) { if(hashList[key] == -1) { hashList[key] = data; break; } else col++; key += ((col*((data%36)+1))%37); } } void search::doubHashSearch(ofstream& outFile, int data, float& num) { int key = data % 37; int count = 1; int col = 0; for(int i = 0; i < hashTableSize; i++) { if(hashList[key] == data) { outFile << hashList[key] << " " << count << endl; num += count; break; } else count++; col++; key += ((col*((data%36)+1))%37); } }
7a789c7f72e4c3114ebdfce9c3a4a6338c350449
24ca80b22c854e85049944fcdc203d96805153e7
/src/universe/vehicle/PackedVehicle.h
3a351d7d0a558ee4e46a3d93a635499e2cc48dc7
[ "BSD-3-Clause", "MIT" ]
permissive
Ghimli/new-ospgl
0b0c8d4c3cc8e422d2160709bfcadf373b79dd3d
31bd84e52d954683671211ff16ce8702bdb87312
refs/heads/master
2022-10-04T21:10:23.953046
2020-06-08T20:42:03
2020-06-08T20:42:03
268,630,072
0
0
NOASSERTION
2020-06-01T20:53:51
2020-06-01T20:53:50
null
UTF-8
C++
false
false
1,053
h
#pragma once #include "../CartesianState.h" #pragma warning(push, 0) #include <btBulletDynamicsCommon.h> #pragma warning(pop) #include <physics/glm/BulletGlmCompat.h> class Vehicle; class PackedVehicle { private: // NOTE: Everything is given relative to root, // except the angular velocity which should // be assumed to "be" at the COM of the vehicle // (To avoid false translation) // (Note: The angular velocity of the COM and the root // part are the same as the whole thing is a rigidbody, // but during calculations the origin of rotation is the // COM and not the root part) WorldState root_state; btTransform root_transform; // Center of mass relative to the root part btVector3 com; public: Vehicle* vehicle; void set_world_state(WorldState n_state); WorldState get_world_state() { return root_state; } PackedVehicle(Vehicle* v); btTransform get_root_transform(){ return root_transform; } WorldState get_root_state(){ return root_state; } btVector3 get_com_root_relative(){ return com; } void calculate_com(); };
e658e89704bb344cd7620f94439b8e53a8a4be97
fad4fa89045a1b7a13162ceed1193427787fd329
/Root/SampleCOMServer/SampleFreeThreadedClass.h
4352eafda3657301e285c3eec4e77c4473b0bb39
[]
no_license
tom-englert/COMRegistryBrowser
00023333a573c6b69c277d96a05ce3634c5aee3e
6e4136cdb8621d90a3bb30c0e86cd977dc6fb255
refs/heads/master
2023-05-04T01:05:21.977690
2023-04-11T11:51:50
2023-04-11T11:51:50
87,649,964
2
1
null
null
null
null
UTF-8
C++
false
false
1,421
h
// SampleFreeThreadedClass.h : Declaration of the CSampleFreeThreadedClass #pragma once #include "resource.h" // main symbols #include "SampleCOMServer_i.h" using namespace ATL; // CSampleFreeThreadedClass class ATL_NO_VTABLE CSampleFreeThreadedClass : public CComObjectRootEx<CComMultiThreadModel>, public CComCoClass<CSampleFreeThreadedClass, &CLSID_SampleFreeThreadedClass>, public IDispatchImpl<ISampleFreeThreadedClass, &IID_ISampleFreeThreadedClass, &LIBID_SampleCOMServerLib, /*wMajor =*/ 1, /*wMinor =*/ 0>, public IDispatchImpl<ISampleTestInterface, &__uuidof(ISampleTestInterface), &LIBID_SampleCOMServerLib, /* wMajor = */ 1, /* wMinor = */ 0> { public: CSampleFreeThreadedClass() { } DECLARE_REGISTRY_RESOURCEID(IDR_SAMPLEFREETHREADEDCLASS) BEGIN_COM_MAP(CSampleFreeThreadedClass) COM_INTERFACE_ENTRY(ISampleFreeThreadedClass) COM_INTERFACE_ENTRY2(IDispatch, ISampleTestInterface) COM_INTERFACE_ENTRY(ISampleTestInterface) END_COM_MAP() DECLARE_PROTECT_FINAL_CONSTRUCT() HRESULT FinalConstruct() { return S_OK; } void FinalRelease() { } public: STDMETHOD(Test)(void); // ISampleTestInterface Methods public: STDMETHOD(TestInterface)() { // Add your function implementation here. return E_NOTIMPL; } }; OBJECT_ENTRY_AUTO(__uuidof(SampleFreeThreadedClass), CSampleFreeThreadedClass)
0f22fc2f7b64f62e574a6794d0f20b737f6c8492
193cacbe89f5b2ef2208ef075dedc1871464f5f4
/src/tools/src/cachedresultvault.cpp
2cbfdc19f478f72132b027ddc275883e4498a478
[ "MIT" ]
permissive
sssong81/coincenter
6c867fc39d9b096bafb71a9cb41295ed76dd29f5
5f46b89af3a10c4a85a1fe6d3cbda950b7b3c949
refs/heads/master
2023-04-22T21:43:08.753950
2021-05-05T06:53:20
2021-05-06T13:40:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
696
cpp
#include "cachedresultvault.hpp" #include "cct_exception.hpp" namespace cct { void CachedResultVault::registerCachedResult(CachedResultBase &cacheResult) { _cachedResults.push_back(std::addressof(cacheResult)); } void CachedResultVault::freezeAll() { if (_allFrozen) { throw exception("unfreezeAll should be called after one freezeAll"); } for (CachedResultBase *p : _cachedResults) { p->freeze(); } _allFrozen = true; } void CachedResultVault::unfreezeAll() { if (!_allFrozen) { throw exception("unfreezeAll should be called after one freezeAll"); } for (CachedResultBase *p : _cachedResults) { p->unfreeze(); } _allFrozen = false; } } // namespace cct
92c44dd23d81cf11461f7b1d5ae49818de08f152
9d851f5315bce6e24c8adcf6d2d2b834f288d2b2
/chipyard/tools/chisel3/test_run_dir/MixedVecRegTester/2020030621351711598188151737613660/VMixedVecRegTester__ALLsup.cpp
526ef31e8334085dc9408a8160e6e9ea651ff762
[ "BSD-3-Clause" ]
permissive
ajis01/systolicMM
b9830b4b00cb7f68d49fb039a5a53c04dcaf3e60
d444d0b8cae525501911e8d3c8ad76dac7fb445c
refs/heads/master
2021-08-17T22:54:34.204694
2020-03-18T03:31:59
2020-03-18T03:31:59
247,648,431
0
1
null
2021-03-29T22:26:24
2020-03-16T08:27:34
C++
UTF-8
C++
false
false
220
cpp
// DESCRIPTION: Generated by verilator_includer via makefile #define VL_INCLUDE_OPT include #include "VMixedVecRegTester__Trace.cpp" #include "VMixedVecRegTester__Syms.cpp" #include "VMixedVecRegTester__Trace__Slow.cpp"
9623c12530e1811452cac9268ae88b77f2144f70
d3136fd87c0af4c408ce87aecdf492cb8a5e8e43
/sbpl_collision_checking/include/sbpl_collision_checking/voxel_operations.h
511927a8ffb2015bf4c0d1300d10cabc41ef9711
[]
no_license
dyouakim/smpl
a87fc88f33c4c5ab1448e5b58d6cdcd46fc187c8
83d251f445dce684aa132e7361c6c15dcda3c574
refs/heads/master
2021-01-19T18:39:52.997665
2019-02-28T16:18:46
2019-02-28T16:18:46
101,150,440
1
0
null
2017-08-23T07:21:17
2017-08-23T07:21:17
null
UTF-8
C++
false
false
6,461
h
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2016, Andrew Dornbush // 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 OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////////////////////////// /// \author Andrew Dornbush #ifndef sbpl_collision_voxel_operations_h #define sbpl_collision_voxel_operations_h // standard includes #include <vector> // system includes #include <Eigen/Dense> #include <geometric_shapes/shapes.h> #include <geometry_msgs/Pose.h> #include <moveit_msgs/CollisionObject.h> #include <sbpl_collision_checking/types.h> #include <shape_msgs/Mesh.h> #include <shape_msgs/Plane.h> #include <shape_msgs/SolidPrimitive.h> namespace sbpl { namespace collision { /// \name Aggregate Types ///@{ bool VoxelizeObject( const Object& object, double res, const Eigen::Vector3d& go, std::vector<std::vector<Eigen::Vector3d>>& all_voxels); bool VoxelizeCollisionObject( const moveit_msgs::CollisionObject& object, double res, const Eigen::Vector3d& go, std::vector<std::vector<Eigen::Vector3d>>& all_voxels); bool VoxelizeObject( const Object& object, double res, const Eigen::Vector3d& go, const Eigen::Vector3d& gmin, const Eigen::Vector3d& gmax, std::vector<std::vector<Eigen::Vector3d>>& all_voxels); bool VoxelizeCollisionObject( const moveit_msgs::CollisionObject& object, double res, const Eigen::Vector3d& go, const Eigen::Vector3d& gmin, const Eigen::Vector3d& gmax, std::vector<std::vector<Eigen::Vector3d>>& all_voxels); ///@} /// \name geometric_shapes::Shape Voxelization ///@{ // These functions must only append voxels to the output vector bool VoxelizeShape( const shapes::Shape& shape, const Eigen::Affine3d& pose, double res, const Eigen::Vector3d& go, std::vector<Eigen::Vector3d>& voxels); bool VoxelizeShape( const shapes::Shape& shape, const Eigen::Affine3d& pose, double res, const Eigen::Vector3d& go, const Eigen::Vector3d& gmin, const Eigen::Vector3d& gmax, std::vector<Eigen::Vector3d>& voxels); bool VoxelizeSphere( const shapes::Sphere& sphere, const Eigen::Affine3d& pose, double res, const Eigen::Vector3d& go, std::vector<Eigen::Vector3d>& voxels); bool VoxelizeCylinder( const shapes::Cylinder& cylinder, const Eigen::Affine3d& pose, double res, const Eigen::Vector3d& go, std::vector<Eigen::Vector3d>& voxels); bool VoxelizeCone( const shapes::Cone& cone, const Eigen::Affine3d& pose, double res, const Eigen::Vector3d& go, std::vector<Eigen::Vector3d>& voxels); bool VoxelizeBox( const shapes::Box& box, const Eigen::Affine3d& pose, double res, const Eigen::Vector3d& go, std::vector<Eigen::Vector3d>& voxels); bool VoxelizePlane( const shapes::Plane& plane, const Eigen::Affine3d& pose, double res, const Eigen::Vector3d& go, const Eigen::Vector3d& gmin, const Eigen::Vector3d& gmax, std::vector<Eigen::Vector3d>& voxels); bool VoxelizeMesh( const shapes::Mesh& mesh, const Eigen::Affine3d& pose, double res, const Eigen::Vector3d& go, std::vector<Eigen::Vector3d>& voxels); bool VoxelizeOcTree( const shapes::OcTree& octree, const Eigen::Affine3d& pose, double res, const Eigen::Vector3d& go, std::vector<Eigen::Vector3d>& voxels); ///@} /// \name shape_msgs Voxelization ///@{ bool VoxelizeSolidPrimitive( const shape_msgs::SolidPrimitive& prim, const geometry_msgs::Pose& pose, double res, const Eigen::Vector3d& go, std::vector<Eigen::Vector3d>& voxels); bool VoxelizeBox( const shape_msgs::SolidPrimitive& box, const geometry_msgs::Pose& pose, double res, const Eigen::Vector3d& go, std::vector<Eigen::Vector3d>& voxels); bool VoxelizeSphere( const shape_msgs::SolidPrimitive& sphere, const geometry_msgs::Pose& pose, double res, const Eigen::Vector3d& go, std::vector<Eigen::Vector3d>& voxels); bool VoxelizeCylinder( const shape_msgs::SolidPrimitive& cylinder, const geometry_msgs::Pose& pose, double res, const Eigen::Vector3d& go, std::vector<Eigen::Vector3d>& voxels); bool VoxelizeCone( const shape_msgs::SolidPrimitive& cone, const geometry_msgs::Pose& pose, double res, const Eigen::Vector3d& go, std::vector<Eigen::Vector3d>& voxels); bool VoxelizeMesh( const shape_msgs::Mesh& mesh, const geometry_msgs::Pose& pose, double res, const Eigen::Vector3d& go, std::vector<Eigen::Vector3d>& voxels); bool VoxelizePlane( const shape_msgs::Plane& plane, const geometry_msgs::Pose& pose, double res, const Eigen::Vector3d& go, const Eigen::Vector3d& gmin, const Eigen::Vector3d& gmax, std::vector<Eigen::Vector3d>& voxels); ///@} } // namespace collision } // namespace sbpl #endif
0de5afa0c1d448472d563fe5a65f8c09d75fe2bf
cc95b782330ed397090c4c45521faf9bc24350a4
/faculty.h
3e9f8964c2f076f709f02b82395b08c0594b2081
[]
no_license
ehh2h/HashTableLab
76320e493a0122d625e1ff0a445646fa5059f7ac
d98d342072a2b7749e1247c4c39521f90f47c825
refs/heads/master
2021-03-12T19:25:15.607558
2015-02-27T13:39:40
2015-02-27T13:39:40
31,420,495
0
0
null
null
null
null
UTF-8
C++
false
false
905
h
// File: faculty.h // Programmer: Eric Howard // Description: Faculty Object Header File #ifndef FACULTY_H #define FACULTY_H #include <string> #include "person.h" #include <iomanip> using namespace std; class Faculty : public Person { public: Faculty(){} ; // default constructor Faculty(string newName, int newID, string newEmail, int newYear, string newMajor, string newTitle, string newDepartment, string newTenured) : Person(newName, newID, newEmail){ department = newDepartment; tenured = newTenured; }; ~Faculty(){}; // default desctructor void print(); string getDepartment(); // get current faculty year void setDepartment(string newDepartment); // set current faculty year string getTenured(); // get current faculty major void setTenured(string newTenured); // set current faculty major private: string department,tenured; }; #endif
420e737644ba27e0b8b5d9ce65bc7c4e1b53919c
4a0915625aab3f601a1ef7ce6e89758d657fb44e
/tools/mclinker/unittests/StaticResolverTest.cpp
75ff0182851994fc0396521d1e71a017b6a42172
[ "NCSA" ]
permissive
GuzTech/NyuziToolchain
5d0dcaca9e8a435b915d7bdf63cecbdcfb9e7a23
bec8ae23d3a348b8b9a7ed2b9217f6315d97d592
refs/heads/master
2021-01-17T23:22:49.685684
2015-04-11T20:46:22
2015-04-11T20:46:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,919
cpp
//===- implTest.cpp -------------------------------------------------------===// // // The MCLinker Project // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "StaticResolverTest.h" #include <mcld/Support/TargetSelect.h> #include <mcld/LD/StaticResolver.h> #include <mcld/LD/ResolveInfo.h> #include <mcld/LinkerConfig.h> #include <mcld/Support/FileSystem.h> using namespace mcld; using namespace mcldtest; //===----------------------------------------------------------------------===// // StaticResolverTest //===----------------------------------------------------------------------===// // Constructor can do set-up work for all test here. StaticResolverTest::StaticResolverTest() : m_pResolver(NULL), m_pConfig(NULL) { // create testee. modify it if need m_pResolver = new StaticResolver(); m_pConfig = new LinkerConfig("arm-none-linux-gnueabi"); } // Destructor can do clean-up work that doesn't throw exceptions here. StaticResolverTest::~StaticResolverTest() { delete m_pResolver; delete m_pConfig; } // SetUp() will be called immediately before each test. void StaticResolverTest::SetUp() { } // TearDown() will be called immediately after each test. void StaticResolverTest::TearDown() { } //==========================================================================// // Testcases // TEST_F(StaticResolverTest, MDEF) { ResolveInfo* old_sym = ResolveInfo::Create("abc"); ResolveInfo* new_sym = ResolveInfo::Create("abc"); new_sym->setDesc(ResolveInfo::Define); old_sym->setDesc(ResolveInfo::Define); ASSERT_TRUE(mcld::ResolveInfo::Define == new_sym->desc()); ASSERT_TRUE(mcld::ResolveInfo::Define == old_sym->desc()); ASSERT_TRUE(mcld::ResolveInfo::define_flag == new_sym->info()); ASSERT_TRUE(mcld::ResolveInfo::define_flag == old_sym->info()); bool override = true; bool result = m_pResolver->resolve(*old_sym, *new_sym, override, 0x0); ASSERT_TRUE(result); ASSERT_FALSE(override); } TEST_F(StaticResolverTest, DynDefAfterDynUndef) { ResolveInfo* old_sym = ResolveInfo::Create("abc"); ResolveInfo* new_sym = ResolveInfo::Create("abc"); new_sym->setBinding(ResolveInfo::Global); old_sym->setBinding(ResolveInfo::Global); new_sym->setDesc(ResolveInfo::Undefined); old_sym->setDesc(ResolveInfo::Define); new_sym->setSource(true); old_sym->setSource(true); new_sym->setSize(0); old_sym->setSize(1); ASSERT_TRUE(mcld::ResolveInfo::Global == new_sym->binding()); ASSERT_TRUE(mcld::ResolveInfo::Global == old_sym->binding()); ASSERT_TRUE(mcld::ResolveInfo::Undefined == new_sym->desc()); ASSERT_TRUE(mcld::ResolveInfo::Define == old_sym->desc()); bool override = false; bool result = m_pResolver->resolve(*old_sym, *new_sym, override, 0x0); ASSERT_TRUE(result); ASSERT_FALSE(override); ASSERT_TRUE(1 == old_sym->size()); } TEST_F(StaticResolverTest, DynDefAfterDynDef) { ResolveInfo* old_sym = ResolveInfo::Create("abc"); ResolveInfo* new_sym = ResolveInfo::Create("abc"); new_sym->setBinding(ResolveInfo::Global); old_sym->setBinding(ResolveInfo::Global); new_sym->setDesc(ResolveInfo::Define); old_sym->setDesc(ResolveInfo::Define); new_sym->setSource(true); old_sym->setSource(true); new_sym->setSize(0); old_sym->setSize(1); ASSERT_TRUE(mcld::ResolveInfo::Global == new_sym->binding()); ASSERT_TRUE(mcld::ResolveInfo::Global == old_sym->binding()); ASSERT_TRUE(mcld::ResolveInfo::Define == new_sym->desc()); ASSERT_TRUE(mcld::ResolveInfo::Define == old_sym->desc()); bool override = false; bool result = m_pResolver->resolve(*old_sym, *new_sym, override, 0x0); ASSERT_TRUE(result); ASSERT_FALSE(override); ASSERT_TRUE(1 == old_sym->size()); } TEST_F(StaticResolverTest, DynUndefAfterDynUndef) { ResolveInfo* old_sym = ResolveInfo::Create("abc"); ResolveInfo* new_sym = ResolveInfo::Create("abc"); new_sym->setBinding(ResolveInfo::Global); old_sym->setBinding(ResolveInfo::Global); new_sym->setDesc(ResolveInfo::Undefined); old_sym->setDesc(ResolveInfo::Undefined); new_sym->setSource(true); old_sym->setSource(true); new_sym->setSize(0); old_sym->setSize(1); ASSERT_TRUE(mcld::ResolveInfo::Global == new_sym->binding()); ASSERT_TRUE(mcld::ResolveInfo::Global == old_sym->binding()); ASSERT_TRUE(mcld::ResolveInfo::Undefined == new_sym->desc()); ASSERT_TRUE(mcld::ResolveInfo::Undefined == old_sym->desc()); bool override = false; bool result = m_pResolver->resolve(*old_sym, *new_sym, override, 0x0); ASSERT_TRUE(result); ASSERT_FALSE(override); ASSERT_TRUE(1 == old_sym->size()); } TEST_F(StaticResolverTest, OverrideWeakByGlobal) { ResolveInfo* old_sym = ResolveInfo::Create("abc"); ResolveInfo* new_sym = ResolveInfo::Create("abc"); new_sym->setBinding(ResolveInfo::Global); old_sym->setBinding(ResolveInfo::Weak); new_sym->setSize(0); old_sym->setSize(1); ASSERT_TRUE(mcld::ResolveInfo::Global == new_sym->binding()); ASSERT_TRUE(mcld::ResolveInfo::Weak == old_sym->binding()); ASSERT_TRUE(mcld::ResolveInfo::global_flag == new_sym->info()); ASSERT_TRUE(mcld::ResolveInfo::weak_flag == old_sym->info()); bool override = false; bool result = m_pResolver->resolve(*old_sym, *new_sym, override, 0x0); ASSERT_TRUE(result); ASSERT_TRUE(override); ASSERT_TRUE(0 == old_sym->size()); } TEST_F(StaticResolverTest, DynWeakAfterDynDef) { ResolveInfo* old_sym = ResolveInfo::Create("abc"); ResolveInfo* new_sym = ResolveInfo::Create("abc"); old_sym->setBinding(ResolveInfo::Weak); new_sym->setBinding(ResolveInfo::Global); new_sym->setSource(true); old_sym->setSource(true); old_sym->setDesc(ResolveInfo::Define); new_sym->setDesc(ResolveInfo::Define); new_sym->setSize(0); old_sym->setSize(1); ASSERT_TRUE(mcld::ResolveInfo::Weak == old_sym->binding()); ASSERT_TRUE(mcld::ResolveInfo::Global == new_sym->binding()); ASSERT_TRUE(mcld::ResolveInfo::Define == old_sym->desc()); ASSERT_TRUE(mcld::ResolveInfo::Define == new_sym->desc()); bool override = false; bool result = m_pResolver->resolve(*old_sym, *new_sym, override, 0x0); ASSERT_TRUE(result); ASSERT_FALSE(override); ASSERT_TRUE(1 == old_sym->size()); } TEST_F(StaticResolverTest, MarkByBiggerCommon) { ResolveInfo* old_sym = ResolveInfo::Create("abc"); ResolveInfo* new_sym = ResolveInfo::Create("abc"); new_sym->setDesc(ResolveInfo::Common); old_sym->setDesc(ResolveInfo::Common); new_sym->setSize(999); old_sym->setSize(0); ASSERT_TRUE(mcld::ResolveInfo::Common == new_sym->desc()); ASSERT_TRUE(mcld::ResolveInfo::Common == old_sym->desc()); ASSERT_TRUE(mcld::ResolveInfo::common_flag == new_sym->info()); ASSERT_TRUE(mcld::ResolveInfo::common_flag == old_sym->info()); bool override = true; bool result = m_pResolver->resolve(*old_sym, *new_sym, override, 0x0); ASSERT_TRUE(result); ASSERT_FALSE(override); ASSERT_TRUE(999 == old_sym->size()); } TEST_F(StaticResolverTest, OverrideByBiggerCommon) { ResolveInfo* old_sym = ResolveInfo::Create("abc"); ResolveInfo* new_sym = ResolveInfo::Create("abc"); new_sym->setDesc(ResolveInfo::Common); old_sym->setDesc(ResolveInfo::Common); old_sym->setBinding(ResolveInfo::Weak); new_sym->setSize(999); old_sym->setSize(0); ASSERT_TRUE(ResolveInfo::Common == new_sym->desc()); ASSERT_TRUE(ResolveInfo::Common == old_sym->desc()); ASSERT_TRUE(ResolveInfo::Weak == old_sym->binding()); ASSERT_TRUE(ResolveInfo::common_flag == new_sym->info()); ASSERT_TRUE((ResolveInfo::weak_flag | ResolveInfo::common_flag) == old_sym->info()); bool override = false; bool result = m_pResolver->resolve(*old_sym, *new_sym, override, 0x0); ASSERT_TRUE(result); ASSERT_TRUE(override); ASSERT_TRUE(999 == old_sym->size()); } TEST_F(StaticResolverTest, OverrideCommonByDefine) { ResolveInfo* old_sym = ResolveInfo::Create("abc"); ResolveInfo* new_sym = ResolveInfo::Create("abc"); old_sym->setDesc(ResolveInfo::Common); old_sym->setSize(0); new_sym->setDesc(ResolveInfo::Define); new_sym->setSize(999); ASSERT_TRUE(ResolveInfo::Define == new_sym->desc()); ASSERT_TRUE(ResolveInfo::Common == old_sym->desc()); ASSERT_TRUE(ResolveInfo::define_flag == new_sym->info()); ASSERT_TRUE(ResolveInfo::common_flag == old_sym->info()); bool override = false; bool result = m_pResolver->resolve(*old_sym, *new_sym, override, 0x0); ASSERT_TRUE(result); ASSERT_TRUE(override); ASSERT_TRUE(999 == old_sym->size()); } TEST_F(StaticResolverTest, SetUpDesc) { ResolveInfo* sym = ResolveInfo::Create("abc"); sym->setIsSymbol(true); // ASSERT_FALSE( sym->isSymbol() ); ASSERT_TRUE(sym->isSymbol()); ASSERT_TRUE(sym->isGlobal()); ASSERT_FALSE(sym->isWeak()); ASSERT_FALSE(sym->isLocal()); ASSERT_FALSE(sym->isDefine()); ASSERT_TRUE(sym->isUndef()); ASSERT_FALSE(sym->isDyn()); ASSERT_FALSE(sym->isCommon()); ASSERT_FALSE(sym->isIndirect()); ASSERT_TRUE(ResolveInfo::NoType == sym->type()); ASSERT_TRUE(0 == sym->desc()); ASSERT_TRUE(0 == sym->binding()); ASSERT_TRUE(0 == sym->other()); sym->setIsSymbol(false); ASSERT_FALSE(sym->isSymbol()); // ASSERT_TRUE( sym->isSymbol() ); ASSERT_TRUE(sym->isGlobal()); ASSERT_FALSE(sym->isWeak()); ASSERT_FALSE(sym->isLocal()); ASSERT_FALSE(sym->isDefine()); ASSERT_TRUE(sym->isUndef()); ASSERT_FALSE(sym->isDyn()); ASSERT_FALSE(sym->isCommon()); ASSERT_FALSE(sym->isIndirect()); ASSERT_TRUE(ResolveInfo::NoType == sym->type()); ASSERT_TRUE(0 == sym->desc()); ASSERT_TRUE(0 == sym->binding()); ASSERT_TRUE(0 == sym->other()); sym->setDesc(ResolveInfo::Define); ASSERT_FALSE(sym->isSymbol()); // ASSERT_TRUE( sym->isSymbol() ); ASSERT_TRUE(sym->isGlobal()); ASSERT_FALSE(sym->isWeak()); ASSERT_FALSE(sym->isLocal()); ASSERT_TRUE(sym->isDefine()); ASSERT_FALSE(sym->isUndef()); ASSERT_FALSE(sym->isDyn()); ASSERT_FALSE(sym->isCommon()); ASSERT_FALSE(sym->isIndirect()); ASSERT_TRUE(ResolveInfo::NoType == sym->type()); ASSERT_TRUE(ResolveInfo::Define == sym->desc()); ASSERT_TRUE(0 == sym->binding()); ASSERT_TRUE(0 == sym->other()); sym->setDesc(ResolveInfo::Common); ASSERT_FALSE(sym->isSymbol()); // ASSERT_TRUE( sym->isSymbol() ); ASSERT_TRUE(sym->isGlobal()); ASSERT_FALSE(sym->isWeak()); ASSERT_FALSE(sym->isLocal()); ASSERT_FALSE(sym->isDyn()); ASSERT_FALSE(sym->isDefine()); ASSERT_FALSE(sym->isUndef()); ASSERT_TRUE(sym->isCommon()); ASSERT_FALSE(sym->isIndirect()); ASSERT_TRUE(ResolveInfo::NoType == sym->type()); ASSERT_TRUE(ResolveInfo::Common == sym->desc()); ASSERT_TRUE(0 == sym->binding()); ASSERT_TRUE(0 == sym->other()); sym->setDesc(ResolveInfo::Indirect); ASSERT_FALSE(sym->isSymbol()); ASSERT_TRUE(sym->isGlobal()); ASSERT_FALSE(sym->isWeak()); ASSERT_FALSE(sym->isLocal()); ASSERT_FALSE(sym->isDyn()); ASSERT_FALSE(sym->isDefine()); ASSERT_FALSE(sym->isUndef()); ASSERT_FALSE(sym->isCommon()); ASSERT_TRUE(sym->isIndirect()); ASSERT_TRUE(ResolveInfo::NoType == sym->type()); ASSERT_TRUE(ResolveInfo::Indirect == sym->desc()); ASSERT_TRUE(0 == sym->binding()); ASSERT_TRUE(0 == sym->other()); sym->setDesc(ResolveInfo::Undefined); ASSERT_FALSE(sym->isSymbol()); ASSERT_TRUE(sym->isGlobal()); ASSERT_FALSE(sym->isWeak()); ASSERT_FALSE(sym->isLocal()); ASSERT_FALSE(sym->isDyn()); ASSERT_TRUE(sym->isUndef()); ASSERT_FALSE(sym->isDefine()); ASSERT_FALSE(sym->isCommon()); ASSERT_FALSE(sym->isIndirect()); ASSERT_TRUE(ResolveInfo::NoType == sym->type()); ASSERT_TRUE(0 == sym->desc()); ASSERT_TRUE(0 == sym->binding()); ASSERT_TRUE(0 == sym->other()); } TEST_F(StaticResolverTest, SetUpBinding) { ResolveInfo* sym = ResolveInfo::Create("abc"); sym->setIsSymbol(true); // ASSERT_FALSE( sym->isSymbol() ); ASSERT_TRUE(sym->isSymbol()); ASSERT_TRUE(sym->isGlobal()); ASSERT_FALSE(sym->isWeak()); ASSERT_FALSE(sym->isLocal()); ASSERT_FALSE(sym->isDefine()); ASSERT_TRUE(sym->isUndef()); ASSERT_FALSE(sym->isDyn()); ASSERT_FALSE(sym->isCommon()); ASSERT_FALSE(sym->isIndirect()); ASSERT_TRUE(ResolveInfo::NoType == sym->type()); ASSERT_TRUE(0 == sym->desc()); ASSERT_TRUE(0 == sym->binding()); ASSERT_TRUE(0 == sym->other()); sym->setBinding(ResolveInfo::Global); ASSERT_TRUE(sym->isSymbol()); ASSERT_TRUE(sym->isGlobal()); ASSERT_FALSE(sym->isWeak()); ASSERT_FALSE(sym->isLocal()); ASSERT_FALSE(sym->isDefine()); ASSERT_TRUE(sym->isUndef()); ASSERT_FALSE(sym->isDyn()); ASSERT_FALSE(sym->isCommon()); ASSERT_FALSE(sym->isIndirect()); ASSERT_TRUE(ResolveInfo::NoType == sym->type()); ASSERT_TRUE(0 == sym->desc()); ASSERT_TRUE(ResolveInfo::Global == sym->binding()); ASSERT_TRUE(0 == sym->other()); sym->setBinding(ResolveInfo::Weak); ASSERT_TRUE(sym->isSymbol()); ASSERT_FALSE(sym->isGlobal()); ASSERT_TRUE(sym->isWeak()); ASSERT_FALSE(sym->isLocal()); ASSERT_FALSE(sym->isDyn()); ASSERT_FALSE(sym->isDefine()); ASSERT_TRUE(sym->isUndef()); ASSERT_FALSE(sym->isCommon()); ASSERT_FALSE(sym->isIndirect()); ASSERT_TRUE(ResolveInfo::NoType == sym->type()); ASSERT_TRUE(0 == sym->desc()); ASSERT_TRUE(ResolveInfo::Weak == sym->binding()); ASSERT_TRUE(0 == sym->other()); sym->setBinding(ResolveInfo::Local); ASSERT_TRUE(sym->isSymbol()); ASSERT_FALSE(sym->isGlobal()); ASSERT_FALSE(sym->isWeak()); ASSERT_TRUE(sym->isLocal()); ASSERT_FALSE(sym->isDyn()); ASSERT_FALSE(sym->isDefine()); ASSERT_TRUE(sym->isUndef()); ASSERT_FALSE(sym->isCommon()); ASSERT_FALSE(sym->isIndirect()); ASSERT_TRUE(ResolveInfo::NoType == sym->type()); ASSERT_TRUE(0 == sym->desc()); ASSERT_TRUE(ResolveInfo::Local == sym->binding()); ASSERT_TRUE(0 == sym->other()); }
6b16b3dff14412caa5d91c5905ab3581f56181c7
165be8367f5753b03fae11430b1c3ebf48aa834a
/tools/converter/source/tensorflow/ReshapeTf.cpp
20b88e4ae24affd1ac319300dcbfb911a98a8230
[ "Apache-2.0" ]
permissive
alibaba/MNN
f21b31e3c62d9ba1070c2e4e931fd9220611307c
c442ff39ec9a6a99c28bddd465d8074a7b5c1cca
refs/heads/master
2023-09-01T18:26:42.533902
2023-08-22T11:16:44
2023-08-22T11:16:44
181,436,799
8,383
1,789
null
2023-09-07T02:01:43
2019-04-15T07:40:18
C++
UTF-8
C++
false
false
2,055
cpp
// // ReshapeTf.cpp // MNNConverter // // Created by MNN on 2019/01/31. // Copyright © 2018, Alibaba Group Holding Limited // #include <string.h> #include "TfUtils.hpp" #include "tfOpConverter.hpp" #include "graph.pb.h" DECLARE_OP_CONVERTER(ReshapeTf); MNN::OpType ReshapeTf::opType() { return MNN::OpType_Reshape; } MNN::OpParameter ReshapeTf::type() { return MNN::OpParameter_Reshape; } void ReshapeTf::run(MNN::OpT *dstOp, TmpNode *srcNode) { auto reshape = new MNN::ReshapeT; dstOp->main.value = reshape; #ifdef TF_CONVERT_ORIGIN TmpNode *shapeNode = tempGraph->_getTmpNode(srcNode->inEdges[1]); if (shapeNode->opType != "Const") { return; } // Const Shape tensorflow::AttrValue value; if (find_attr_value(shapeNode->tfNode, "value", value)) { MNN::DataType dataType = (MNN::DataType)value.tensor().dtype(); CHECK(dataType == MNN::DataType_DT_INT32) << "Shape Dtype ERROR" << srcNode->opName; reshape->dimType = MNN::MNN_DATA_FORMAT_NHWC; const int repeatedSize = value.tensor().int_val_size(); // firstly get value from repeated field if (repeatedSize != 0) { reshape->dims.resize(repeatedSize); for (int i = 0; i < repeatedSize; ++i) { reshape->dims[i] = value.tensor().int_val(i); } } else if (!value.tensor().tensor_content().empty()) // int32 { const int *data = reinterpret_cast<const int *>(value.tensor().tensor_content().c_str()); int size = value.tensor().tensor_content().size() / sizeof(int); CHECK(size > 1) << "Shape Data ERROR!!! ===> " << srcNode->opName; reshape->dims.resize(size); for (int i = 0; i < size; ++i) { reshape->dims[i] = data[i]; } } else { // only one int value reshape->dims.resize(1); reshape->dims[0] = value.tensor().int_val(0); } } #endif } REGISTER_CONVERTER(ReshapeTf, Reshape);
d0cb7991f493c88d967e3978a3ec7c8c47f1040c
ead0f3f313bdd574545794b0c372eca6bbca9830
/10824네수.cpp
ea04a6ed2f9beea49c2828895e7238dfd75f2f44
[]
no_license
tomcruse/algorithm
fe237ea40d6c29add4b124b84f8714f846a8e385
3029b7ea498c9b63c145f5d5bda26dfd7a17a447
refs/heads/master
2021-06-23T00:23:38.983751
2017-08-19T17:14:56
2017-08-19T17:14:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
191
cpp
#include<iostream> #include<string> using namespace std; string a, b, c, d; int main() { cin >> a >> b >> c >> d; a += b; c += d; cout << atoll(a.c_str()) + atoll(c.c_str()); return 0; }
894c9c26757baf69f2d0fc2dc5bc1f34eadeed15
3467402c3dded0971082168a8338ddd4c9dfcc8b
/SpatialGDK/Source/SpatialGDK/Public/SpatialView/CommandRequest.h
5be645f2ef5aea00f73ce15321dd5840c13f1cd8
[ "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-proprietary-license", "MIT" ]
permissive
UDKMan/UnrealGDK
5885c9e4f69d604ca8da1920312f486b0e354ee5
925bba1ab2ab4ba1ed33758624478910ef5e2ecf
refs/heads/release
2023-03-29T22:20:34.309168
2021-02-01T23:32:49
2021-02-01T23:32:49
352,110,511
1
0
MIT
2021-03-27T15:41:58
2021-03-27T15:41:58
null
UTF-8
C++
false
false
1,742
h
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved #pragma once #include "Templates/UniquePtr.h" #include <improbable/c_schema.h> #include <improbable/c_worker.h> namespace SpatialGDK { struct CommandRequestDeleter { void operator()(Schema_CommandRequest* CommandRequest) const noexcept { if (CommandRequest != nullptr) { Schema_DestroyCommandRequest(CommandRequest); } } }; using OwningCommandRequestPtr = TUniquePtr<Schema_CommandRequest, CommandRequestDeleter>; // An RAII wrapper for component data. class CommandRequest { public: // Creates a new component data. explicit CommandRequest(Worker_ComponentId ComponentId, Worker_CommandIndex CommandIndex); // Takes ownership of component data. explicit CommandRequest(OwningCommandRequestPtr Data, Worker_ComponentId ComponentId, Worker_CommandIndex CommandIndex); ~CommandRequest() = default; // Moveable, not copyable. CommandRequest(const CommandRequest&) = delete; CommandRequest(CommandRequest&&) = default; CommandRequest& operator=(const CommandRequest&) = delete; CommandRequest& operator=(CommandRequest&&) = default; static CommandRequest CreateCopy(const Schema_CommandRequest* Data, Worker_ComponentId ComponentId, Worker_CommandIndex CommandIndex); // Creates a copy of the command request. CommandRequest DeepCopy() const; // Releases ownership of the command request. Schema_CommandRequest* Release() &&; Schema_Object* GetRequestObject() const; Schema_CommandRequest* GetUnderlying() const; Worker_ComponentId GetComponentId() const; Worker_CommandIndex GetCommandIndex() const; private: Worker_ComponentId ComponentId; Worker_CommandIndex CommandIndex; OwningCommandRequestPtr Data; }; } // namespace SpatialGDK
1f784a9a444778c43418b48fb024e36a9de64ddf
356313b292c3d0f11991b27f70a635a05749377a
/P4/practicas.cc
a082da7608a55a49978468e518c1e05c62ad0ac0
[]
no_license
Oscarntnz/IG
30d6bdecbe7fd1440a5cd2e571d9c30ac771e2dc
bbc0ad6da068bc12f170002fa4f39417f5bdd456
refs/heads/master
2023-03-29T05:59:05.385901
2021-01-11T16:17:18
2021-01-11T16:17:18
311,619,181
0
0
null
null
null
null
UTF-8
C++
false
false
4,686
cc
//************************************************************************** // Prácticas // // F.J. melero // // GPL //************************************************************************** #include "aux.h" // includes de OpenGL, windows, y librería std de C++ #include "escena.h" // variable que contiene un puntero a la escena Escena *escena = nullptr ; //*************************************************************************** // Funcion principal que redibuja la escena // // el evento manda a la funcion: // nuevo ancho // nuevo alto //*************************************************************************** void draw_scene(void) { if ( escena != nullptr ) escena->dibujar(); glutSwapBuffers(); } //*************************************************************************** // Funcion llamada cuando se produce un cambio en el tamaño de la ventana // // el evento manda a la funcion: // nuevo ancho // nuevo alto //*************************************************************************** void change_window_size( int newWidth, int newHeight ) { if ( escena != nullptr ) escena->redimensionar(newWidth,newHeight); glutPostRedisplay(); } //*************************************************************************** // Funcion llamada cuando se produce aprieta una tecla normal // // el evento manda a la funcion: // codigo de la tecla // posicion x del raton // posicion y del raton //*************************************************************************** void normal_keys( unsigned char tecla, int x, int y ) { int salir = 0; if ( escena!= nullptr ) salir = escena->teclaPulsada( tecla, x, y ); if ( salir ) { delete escena; escena = nullptr ; exit(0); } else glutPostRedisplay(); } //*************************************************************************** // Funcion llamada cuando se produce aprieta una tecla especial // // el evento manda a la funcion: // codigo de la tecla // posicion x del raton // posicion y del raton //*************************************************************************** void special_keys( int tecla, int x, int y ) { if (escena!=NULL) escena->teclaEspecial( tecla, x, y ); glutPostRedisplay(); } void funcion_idle() { if(escena != nullptr) escena->animarModeloJerarquico(); glutPostRedisplay(); } //*************************************************************************** // Programa principal // // Se encarga de iniciar la ventana, asignar las funciones e comenzar el // bucle de eventos //*************************************************************************** int main( int argc, char **argv ) { using namespace std ; // crear la escena (un puntero a la misma) escena = new Escena(); // Incialización de GLUT // se llama a la inicialización de glut glutInit( &argc, argv ); // se indica las caracteristicas que se desean para la visualización con OpenGL glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); // variables que determninan la posicion y tamaño de la ventana X const int UI_window_pos_x = 50, UI_window_pos_y = 50, UI_window_width = 500, UI_window_height = 500; // posicion de la esquina inferior izquierdad de la ventana glutInitWindowPosition(UI_window_pos_x,UI_window_pos_y); // tamaño de la ventana (ancho y alto) glutInitWindowSize(UI_window_width,UI_window_height); // llamada para crear la ventana, indicando el titulo // SUSTITUIR EL NOMBRE DEL ALUMNO glutCreateWindow("Practicas IG: Oscar Antunez Martinaitis"); // asignación de la funcion llamada "dibujar" al evento de dibujo glutDisplayFunc( draw_scene ); // asignación de la funcion llamada "cambiar_tamanio_ventana" al evento correspondiente glutReshapeFunc( change_window_size ); // asignación de la funcion llamada "tecla_normal" al evento correspondiente glutKeyboardFunc( normal_keys ); // asignación de la funcion llamada "tecla_Especial" al evento correspondiente glutSpecialFunc( special_keys ); glutIdleFunc(funcion_idle); // inicialización de librería GLEW (solo en Linux) #ifdef LINUX const GLenum codigoError = glewInit(); if ( codigoError != GLEW_OK ) // comprobar posibles errores { cout << "Imposible inicializar ’GLEW’, mensaje recibido: " << glewGetErrorString(codigoError) << endl ; exit(1) ; } #endif // funcion de inicialización de la escena (necesita que esté la ventana creada) escena->inicializar( UI_window_width, UI_window_height ); // ejecutar del bucle de eventos glutMainLoop(); return 0; }
ca12567e410e4a4cf2c634bcf276b1d844eca951
9375410cd0ca861302f3c7deee2bd59a324e732e
/main1.cc
5c6ae0ae4c5b5eff750fb0f9b1f03d0aebf530cc
[]
no_license
xizighq/HelloWorld
27bdc42b2ba4382c98fc8222e657cafe9677dae5
8ebd6e42da7841589f864423d4c676d8349aeda8
refs/heads/main
2023-02-11T15:18:33.246105
2021-01-05T07:11:16
2021-01-05T07:11:16
326,676,356
0
0
null
null
null
null
UTF-8
C++
false
false
102
cc
#include<bits/stdc++.h> using namespace std; class test{ public: private: }; int main(){ test a; }
6e4f1b30eb722f6218b8bfc5f8a0f81c35a9aefe
bb62a2b96a8ca5a2f71181e3229c89358fbeb842
/Presenter.ino
c8d0e5161e84e27fe4541631fd14a13548305a68
[]
no_license
hendrikstill/ArduinoPresent
bee0aa6d208b940d76d3260cd921656b4aff2db8
2dcde0fd6c855e495c49a4ec33c8bc5cf3500d83
refs/heads/master
2016-09-10T18:50:46.729144
2013-06-09T16:19:41
2013-06-09T16:19:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,349
ino
#include <Timer.h> #include <Event.h> const int buttonAPin = 2; // the number of the pushbutton pin const int buttonBPin = 4; // the number of the pushbutton pin const int ledPin = 13; // the number of the LED pin const int timeLED1 = 5; //Grün const int timeLED2 = 10; const int timeLED3 = 6; //Rot int time = 1; // Presentation Time in minutes long timems = 60000; long updateTime = 1000; //Update for boolean ledState = false; Timer t; int afterEvent = 0; int updateEvent = 0; int oscillateEvent = 0; int doHalfTimer = 0; int doAfterTimer = 0; int doStopGruenLedBlink = 0; int oscillateGreenEvent = 0; int oscillateRedEvent = 0; int doMinuteBeforeEndTimer = 0; int value, value2; long millisOld = 0; int periode = 2000; int displace = 500; void setup() { // initialize the serial communication: Serial.begin(19200); // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); pinMode(timeLED1, OUTPUT); pinMode(timeLED2, OUTPUT); pinMode(timeLED3, OUTPUT); // initialize the pushbutton pin as an input: pinMode(buttonAPin, INPUT); attachInterrupt(0, buttonAPressed, RISING); pinMode(buttonBPin, INPUT); attachInterrupt(1, buttonBPressed, RISING); digitalWrite(ledPin,HIGH); Serial.println("Presenter Start"); restTimer(20); } void loop() { t.update(); if (Serial.available() > 0) { // read the incoming byte: time = Serial.parseInt(); restTimer(time); } } void restTimer(int timeMinutes){ timems = (long) timeMinutes * 60000; //Reset LEDs digitalWrite(timeLED1,LOW); digitalWrite(timeLED2,LOW); digitalWrite(timeLED3,LOW); t.stop(oscillateGreenEvent); t.stop(oscillateRedEvent); //Reset Timers t.stop(doHalfTimer); t.stop(doMinuteBeforeEndTimer); t.stop(doAfterTimer); //Set Timers doHalfTimer = t.after(timems / 2, doHalf); doMinuteBeforeEndTimer = t.after(timems - (60000) , doMinuteBeforeEnd); doAfterTimer = t.after(timems, doAfter); //Set Initial Blink gruenLedBlink(); //Serial Output Serial.println("Time Resetted"); Serial.print(time); Serial.println(" Minutes"); Serial.print(timems); Serial.println(" MS"); } void buttonAPressed(){ Serial.println("Button A Pressed"); } void buttonBPressed(){ Serial.println("Button B Pressed"); } void doHalf(){ Serial.println("OMG Half Time is up"); gelbLed(); } void doMinuteBeforeEnd(){ Serial.println("OMG in one minute is time up"); rotLedBlink(); } void doAfter(){ Serial.println("OMG Time is up"); rotLed(); } void gruenLed(){ t.stop(oscillateGreenEvent); analogWrite(timeLED1,HIGH); analogWrite(timeLED3,LOW); Serial.println("LED Gruen An"); } void gruenLedBlink(){ Serial.println("LED Gruen blinken"); oscillateGreenEvent = t.oscillate(timeLED1, 100, LOW,10); } void rotLed(){ t.stop(oscillateRedEvent); analogWrite(timeLED1,0); analogWrite(timeLED3,255); Serial.println("LED Rot An"); } void gelbLed(){ analogWrite(timeLED1,128); analogWrite(timeLED3,60); Serial.println("LED Gelb An"); } void rotLedBlink(){ t.stop(oscillateGreenEvent); analogWrite(timeLED1,LOW); oscillateRedEvent = t.oscillate(timeLED3, 100, LOW,600); Serial.println("LED Rot blinken"); }
[ "hendrik@hendrik-ThinkPad-X1.(none)" ]
hendrik@hendrik-ThinkPad-X1.(none)
b478305598ff9726742df8243957b8477e11f0a1
5ea19661d40a8155fdafab5db4a5e2e5a1e17a09
/cpp/p5.cpp
ac9cad88838e11717b12388ca4b8a1eb09a6c133
[]
no_license
kgraves/euler
e6702b0941a4a467732ba06a6482e1d8623391ff
59373337e472f03dc747a12a7951cf9e98222a86
refs/heads/master
2021-05-15T01:18:12.906998
2017-03-09T03:45:03
2017-03-09T03:45:03
10,578,464
0
0
null
null
null
null
UTF-8
C++
false
false
973
cpp
#include <iostream> #include <cmath> using namespace std; int gcpf(int n) { int g=0, p=0; for (int i=2; n!=1;) { if (n%i == 0) { if (g == i) { ++p; n /= i; } else { p = 1; g = i; n /= i; } } else ++i; } return pow(g, p); } int main() { int s = 1; int t = 0; for (int i=2; i<=20; ++i) { t = gcpf(i); cout << t << endl; s *= t; //s *= gcpf(i); } cout << s << endl; /* bool s; for (long i=20; i<9999999999; i+=2) { s = true; for (long j=20; j>=20; --j) { if ((i % j) != 0) { s = false; break; } } if (s) { cout << i << endl; return 0; } } cout << "not found" << endl; */ return 0; }
759ef53aea2d467ea4032b1e2dcf9f0932c6e813
e6cb9b05376710f9a0ab8543b00420d7c604c2c2
/tests/common_test/tests/data_structures_tests/blocking_queue_tests.cpp
1b503afac737dbaef0d4c177a1a2a75f4ee4ddff
[ "MIT" ]
permissive
JulianBiancardi/Wolfenstein-Taller1
684b69fb08fc4e91faf09f82fae2f585fea10e44
28e72ce8438264919586785aa09ce9b0a5de222b
refs/heads/main
2023-04-11T07:20:20.905180
2021-04-16T18:05:19
2021-04-16T18:05:19
315,163,517
1
0
null
null
null
null
UTF-8
C++
false
false
2,419
cpp
#include "blocking_queue_tests.h" #include <utility> #include "../../main/data_structures/blocking_queue.h" #include "../../main/packets/packet.h" #include "../../main/packets/packing.h" #include "../../main/threads/thread.h" #include "../tests_setup.h" int static empty_creation_test(); int static enqueue_test(); int static dequeue_test(); int static cv_test(); void blocking_queue_tests() { begin_tests("BLOCKING QUEUE"); print_test("La cola bloqueante se crea vacía correctamente", empty_creation_test, NO_ERROR); print_test("La cola bloqueante encola correctamente", enqueue_test, NO_ERROR); print_test("La cola bloqueante desencola correctamente", dequeue_test, NO_ERROR); print_test( "La cola bloqueante es notificada correctamente cuando se encola algo, " "destrabandose", cv_test, NO_ERROR); end_tests(); } int static empty_creation_test() { BlockingQueue<int> bq; return NO_ERROR; } int static enqueue_test() { BlockingQueue<int> bq; int num = 3; int num2 = 5; bq.enqueue(num); bq.enqueue(std::move(num2)); return NO_ERROR; } int static dequeue_test() { BlockingQueue<int> bq; int res; bq.enqueue(3); bq.dequeue(res); if (res != 3) { return ERROR; } return NO_ERROR; } class TestThreadEnqueue : public Thread { private: BlockingQueue<int>& queue; BlockingQueue<Packet>& queue2; int result; void run() { unsigned char data[5]; size_t size = pack(data, "C", 2); Packet packet(size, data); queue2.enqueue(packet); } public: TestThreadEnqueue(BlockingQueue<int>& queue, BlockingQueue<Packet>& queue2) : queue(queue), queue2(queue2) {} ~TestThreadEnqueue() {} }; class TestThreadDequeue : public Thread { private: BlockingQueue<int>& queue; BlockingQueue<Packet>& queue2; Packet result; void run() { Packet a; queue2.dequeue(a); result = a; } public: TestThreadDequeue(BlockingQueue<int>& queue, BlockingQueue<Packet>& queue2) : queue(queue), queue2(queue2) {} ~TestThreadDequeue() {} Packet& get_result() { return result; } }; int static cv_test() { BlockingQueue<int> q1; BlockingQueue<Packet> q2; TestThreadEnqueue t1(q1, q2); TestThreadDequeue t2(q1, q2); t2.start(); t1.start(); Packet& result = t2.get_result(); t1.join(); t2.join(); if (result.get_type() != 2) { return ERROR; } return NO_ERROR; }
45cbfa2543a9a259c545de50e2b14cc6c7a18c30
05a65c385dc5ba32bff4e1af5f9d523a4e831449
/Source/USemLog/Private/Viz/Markers/SLVizSkeletalMeshMarker.cpp
6911cd977936917161a0c8c42dc7a31325f3b09f
[ "BSD-3-Clause" ]
permissive
robcog-iai/USemLog
5571212e9c7fba04a441a89f269f02195a3b3643
d22c3b8876bec66a667023078f370a81f7ce9d2b
refs/heads/master
2023-09-01T08:53:09.932916
2022-11-03T11:20:35
2022-11-03T11:20:35
69,003,081
9
22
BSD-3-Clause
2023-03-29T14:44:52
2016-09-23T07:59:30
C++
UTF-8
C++
false
false
15,095
cpp
// Copyright 2020, Institute for Artificial Intelligence - University of Bremen // Author: Andrei Haidu (http://haidu.eu) #include "Viz/Markers/SLVizSkeletalMeshMarker.h" #include "Viz/SLVizAssets.h" #include "Components/PoseableMeshComponent.h" #include "Components/SkeletalMeshComponent.h" #include "Materials/MaterialInstanceDynamic.h" // Constructor USLVizSkeletalMeshMarker::USLVizSkeletalMeshMarker() { PrimaryComponentTick.bCanEverTick = true; PrimaryComponentTick.bStartWithTickEnabled = false; PMCRef = nullptr; } // Called every frame, used for timeline visualizations, activated and deactivated on request void USLVizSkeletalMeshMarker::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); // Increase the passed time TimelineDeltaTime += DeltaTime; // Calculate the number of instances to draw depending on the passed time int32 NumInstancesToDraw = (TimelineDeltaTime * TimelinePoses.Num()) / TimelineDuration; // Wait if not enough time has passed if (NumInstancesToDraw == 0) { return; } // Draw all instances, or use a limit if (TimelineMaxNumInstances <= 0) { UpdateTimeline(NumInstancesToDraw); } else { UpdateTimelineWithMaxNumInstances(NumInstancesToDraw); } // Reset the elapsed time TimelineDeltaTime = 0; } // Set the visual properties of the skeletal mesh (use original materials) void USLVizSkeletalMeshMarker::SetVisual(USkeletalMesh* SkelMesh) { // Create the poseable mesh reference and the dynamic material SetPoseableMeshComponentVisual(SkelMesh); // Apply dynamic material value for (int32 MatIdx = 0; MatIdx < PMCRef->GetNumMaterials(); ++MatIdx) { PMCRef->SetMaterial(MatIdx, DynamicMaterial); } } // Set the visual properties of the skeletal mesh void USLVizSkeletalMeshMarker::SetVisual(USkeletalMesh* SkelMesh, const FLinearColor& InColor, ESLVizMaterialType InMaterialType) { // Create the poseable mesh reference and the dynamic material SetPoseableMeshComponentVisual(SkelMesh); // Set the dynamic material SetDynamicMaterial(InMaterialType); SetDynamicMaterialColor(InColor); // Apply dynamic material value for (int32 MatIdx = 0; MatIdx < PMCRef->GetNumMaterials(); ++MatIdx) { PMCRef->SetMaterial(MatIdx, DynamicMaterial); } } //// Add instances at pose //void USLVizSkeletalMeshMarker::AddInstance(const FTransform& Pose, const TMap<int32, FTransform>& BonePoses) //{ // if (!PMCRef || !PMCRef->IsValidLowLevel() || PMCRef->IsPendingKillOrUnreachable()) // { // UE_LOG(LogTemp, Warning, TEXT("%s::%d Visual is not set.."), *FString(__FUNCTION__), __LINE__); // return; // } // // UPoseableMeshComponent* PMC = CreateNewPoseableMeshInstance(); // PMC->SetWorldTransform(Pose); // // for (const auto& BonePosePair : BonePoses) // { // const FName BoneName = PMC->GetBoneName(BonePosePair.Key); // PMC->SetBoneTransformByName(BoneName, BonePosePair.Value, EBoneSpaces::WorldSpace); // } // // PMCInstances.Add(PMC); //} // Add instance with bones void USLVizSkeletalMeshMarker::AddInstance(const TPair<FTransform, TMap<int32, FTransform>>& SkeletalPose) { if (!PMCRef || !PMCRef->IsValidLowLevel() || PMCRef->IsPendingKillOrUnreachable()) { UE_LOG(LogTemp, Warning, TEXT("%s::%d Visual is not set.."), *FString(__FUNCTION__), __LINE__); return; } UPoseableMeshComponent* PMC = CreateNewPoseableMeshInstance(); PMC->SetWorldTransform(SkeletalPose.Key); for (int32 Idx = 0; Idx < 5; ++Idx) { for (const auto& BonePosePair : SkeletalPose.Value) { const FName BoneName = PMC->GetBoneName(BonePosePair.Key); PMC->SetBoneTransformByName(BoneName, BonePosePair.Value, EBoneSpaces::WorldSpace); } } PMCInstances.Add(PMC); } //// Add instances with the poses //void USLVizSkeletalMeshMarker::AddInstances(const TArray<FTransform>& Poses, const TArray<TMap<int32, FTransform>>& BonePosesArray) //{ // if (!PMCRef || !PMCRef->IsValidLowLevel() || PMCRef->IsPendingKillOrUnreachable()) // { // UE_LOG(LogTemp, Warning, TEXT("%s::%d Visual is not set.."), *FString(__FUNCTION__), __LINE__); // return; // } // // // Make sure the size of the two arrays are the same // const bool bIncludeBones = Poses.Num() == BonePosesArray.Num(); // // int32 PoseIdx = 0; // for (const auto& P : Poses) // { // UPoseableMeshComponent* PMC = CreateNewPoseableMeshInstance(); // PMC->SetWorldTransform(P); // // if (bIncludeBones) // { // for (const auto& BonePosePair : BonePosesArray[PoseIdx]) // { // const FName BoneName = PMC->GetBoneName(BonePosePair.Key); // PMC->SetBoneTransformByName(BoneName, BonePosePair.Value, EBoneSpaces::WorldSpace); // } // PoseIdx++; // } // // PMCInstances.Add(PMC); // } //} // Add instances with bone poses void USLVizSkeletalMeshMarker::AddInstances(const TArray<TPair<FTransform, TMap<int32, FTransform>>>& SkeletalPoses) { if (!PMCRef || !PMCRef->IsValidLowLevel() || PMCRef->IsPendingKillOrUnreachable()) { UE_LOG(LogTemp, Warning, TEXT("%s::%d Visual is not set.."), *FString(__FUNCTION__), __LINE__); return; } for (const auto& SkelPosePair : SkeletalPoses) { UPoseableMeshComponent* PMC = CreateNewPoseableMeshInstance(); PMC->SetWorldTransform(SkelPosePair.Key); for (int32 Idx = 0; Idx < 5; ++Idx) { for (const auto& BonePosePair : SkelPosePair.Value) { const FName BoneName = PMC->GetBoneName(BonePosePair.Key); PMC->SetBoneTransformByName(BoneName, BonePosePair.Value, EBoneSpaces::WorldSpace); } } PMCInstances.Add(PMC); } } // Add instances with timeline update void USLVizSkeletalMeshMarker::AddInstances(const TArray<TPair<FTransform, TMap<int32, FTransform>>>& SkeletalPoses, const FSLVizTimelineParams& TimelineParams) { if (!PMCRef || !PMCRef->IsValidLowLevel() || PMCRef->IsPendingKillOrUnreachable()) { UE_LOG(LogTemp, Warning, TEXT("%s::%d Visual is not set.."), *FString(__FUNCTION__), __LINE__); return; } if (TimelineParams.Duration <= 0.008f) { AddInstances(SkeletalPoses); return; } if (IsComponentTickEnabled()) { UE_LOG(LogTemp, Warning, TEXT("%s::%d A timeline is already active, reset first.."), *FString(__FUNCTION__), __LINE__); return; } // Set the timeline data TimelinePoses = SkeletalPoses; TimelineDuration = TimelineParams.Duration; TimelineMaxNumInstances = TimelineParams.MaxNumInstances; bLoopTimeline = TimelineParams.bLoop; TimelineIndex = 0; // Start timeline if (TimelineParams.UpdateRate > 0.f) { SetComponentTickInterval(TimelineParams.UpdateRate); } SetComponentTickEnabled(true); } // Unregister the component, remove it from its outer Actor's Components array and mark for pending kill void USLVizSkeletalMeshMarker::DestroyComponent(bool bPromoteChildren) { for (const auto& PMCInst : PMCInstances) { if (PMCInst && PMCInst->IsValidLowLevel() && !PMCInst->IsPendingKillOrUnreachable()) { PMCInst->DestroyComponent(); } } if (PMCRef && PMCRef->IsValidLowLevel() && !PMCRef->IsPendingKillOrUnreachable()) { PMCRef->DestroyComponent(); } Super::DestroyComponent(bPromoteChildren); } /* Begin VizMarker interface */ // Reset visuals and poses void USLVizSkeletalMeshMarker::Reset() { ResetVisuals(); ResetPoses(); } // Reset visual related data void USLVizSkeletalMeshMarker::ResetVisuals() { if (!PMCRef || !PMCRef->IsValidLowLevel() || PMCRef->IsPendingKillOrUnreachable()) { //UE_LOG(LogTemp, Warning, TEXT("%s::%d Visual is not set.."), *FString(__FUNCTION__), __LINE__); return; } PMCRef->EmptyOverrideMaterials(); } // Reset instances (poses of the visuals) void USLVizSkeletalMeshMarker::ResetPoses() { for (const auto& PMC : PMCInstances) { if (!PMC->IsPendingKillOrUnreachable()) { PMC->DestroyComponent(); } } PMCInstances.Empty(); } //// Update intial timeline iteration (create the instances) //void USLVizSkeletalMeshMarker::UpdateInitialTimeline(float DeltaTime) //{ // TimelineDeltaTime += DeltaTime; // const int32 NumTotalIstances = TimelinePoses.Num(); // int32 NumInstancesToDraw = (TimelineDeltaTime * NumTotalIstances) / TimelineDuration; // if (NumInstancesToDraw == 0) // { // return; // } // // if (TimelineIndex + NumInstancesToDraw < NumTotalIstances) // { // // Safe to draw all instances // while (NumInstancesToDraw > 0) // { // AddInstance(TimelinePoses[TimelineIndex]); // TimelineIndex++; // NumInstancesToDraw--; // } // } // else // { // // Decrease the num of instances to draw to avoid overflow // NumInstancesToDraw = NumTotalIstances - TimelineIndex; // while (NumInstancesToDraw > 0) // { // AddInstance(TimelinePoses[TimelineIndex]); // TimelineIndex++; // NumInstancesToDraw--; // } // // // Check if the timeline should be repeated or stopped // if (bLoopTimeline) // { // HideInstances(); // TimelinePoses.Empty(); // TimelineIndex = 0; // } // else // { // ClearAndStopTimeline(); // } // } //} // //// Update loop timeline (set instaces visibility) //void USLVizSkeletalMeshMarker::UpdateLoopTimeline(float DeltaTime) //{ // TimelineDeltaTime += DeltaTime; // const int32 NumTotalIstances = PMCInstances.Num(); // int32 NumInstancesToDraw = (DeltaTime * NumTotalIstances) / TimelineDuration; // if (NumInstancesToDraw == 0) // { // return; // } // // if (TimelineIndex + NumInstancesToDraw < NumTotalIstances) // { // while (NumInstancesToDraw > 0) // { // PMCInstances[TimelineIndex]->SetVisibility(true); // Instance is already created, set it to visible // TimelineIndex++; // NumInstancesToDraw--; // } // } // else // { // // Decrease the num of instances to draw to avoid overflow // NumInstancesToDraw = NumTotalIstances - TimelineIndex; // while (NumInstancesToDraw > 0) // { // PMCInstances[TimelineIndex]->SetVisibility(true); // Instance is already created, set it to visible // TimelineIndex++; // NumInstancesToDraw--; // } // // // Check if the timeline should be repeated or stopped // if (bLoopTimeline) // { // HideInstances(); // TimelineIndex = 0; // } // else // { // ClearAndStopTimeline(); // } // } //} // Set instances visibility to false void USLVizSkeletalMeshMarker::HideInstances() { for (const auto& PMC : PMCInstances) { PMC->SetVisibility(false); } } // Clear the timeline and the related members void USLVizSkeletalMeshMarker::ClearAndStopTimeline() { if (IsComponentTickEnabled()) { SetComponentTickEnabled(false); SetComponentTickInterval(-1.f); // Tick every frame by default (If less than or equal to 0 then it will tick every frame) } TimelineMaxNumInstances = INDEX_NONE; TimelineIndex = INDEX_NONE; TimelinePoses.Empty(); } // Update timeline with the given number of new instances void USLVizSkeletalMeshMarker::UpdateTimeline(int32 NumNewInstances) { // Check if the instances have already been created (number of timeline poses equals the number of intances) bool bInstancesAlreadyCreated = TimelinePoses.Num() == PMCInstances.Num(); // Check if it is safe to draw all new instances if (TimelineIndex + NumNewInstances < TimelinePoses.Num()) { // Safe to draw all instances while (NumNewInstances > 0) { bInstancesAlreadyCreated ? PMCInstances[TimelineIndex]->SetVisibility(true) : AddInstance(TimelinePoses[TimelineIndex]); TimelineIndex++; NumNewInstances--; } } else { // Reached end of the poses array, add only remaining values while (TimelinePoses.IsValidIndex(TimelineIndex)) { bInstancesAlreadyCreated ? PMCInstances[TimelineIndex]->SetVisibility(true) : AddInstance(TimelinePoses[TimelineIndex]); TimelineIndex++; } // Hide existing instances if timeline should be looped if (bLoopTimeline) { // Avoid destroying the instances HideInstances(); // TimelinePoses.Empty(); commented out since it is used to detect if the instances were created, or create explicit flag TimelineIndex = 0; } else { ClearAndStopTimeline(); } } } // Update timeline with max number of instances void USLVizSkeletalMeshMarker::UpdateTimelineWithMaxNumInstances(int32 NumNewInstances) { // Check if the instances have already been created (number of timeline poses equals the number of intances) bool bInstancesAlreadyCreated = TimelinePoses.Num() == PMCInstances.Num(); // Check if it is safe to draw all new instances if (TimelineIndex + NumNewInstances < TimelinePoses.Num()) { // Safe to draw all instances while (NumNewInstances > 0) { if (TimelineIndex < TimelineMaxNumInstances) { bInstancesAlreadyCreated ? PMCInstances[TimelineIndex]->SetVisibility(true) : AddInstance(TimelinePoses[TimelineIndex]); } else { PMCInstances[TimelineIndex-TimelineMaxNumInstances]->SetVisibility(false); bInstancesAlreadyCreated ? PMCInstances[TimelineIndex]->SetVisibility(true) : AddInstance(TimelinePoses[TimelineIndex]); } TimelineIndex++; NumNewInstances--; } } else { // Reached end of the poses array, add only remaining values while (TimelinePoses.IsValidIndex(TimelineIndex)) { if (TimelineIndex < TimelineMaxNumInstances) { bInstancesAlreadyCreated ? PMCInstances[TimelineIndex]->SetVisibility(true) : AddInstance(TimelinePoses[TimelineIndex]); bInstancesAlreadyCreated ? PMCInstances[TimelineIndex]->SetVisibility(true) : AddInstance(TimelinePoses[TimelineIndex]); } else { PMCInstances[TimelineIndex - TimelineMaxNumInstances]->SetVisibility(false); bInstancesAlreadyCreated ? PMCInstances[TimelineIndex]->SetVisibility(true) : AddInstance(TimelinePoses[TimelineIndex]); } TimelineIndex++; } // Hide existing instances if timeline should be looped if (bLoopTimeline) { // Avoid destroying the instances HideInstances(); // TimelinePoses.Empty(); commented out since it is used to detect if the instances were created, or create explicit flag TimelineIndex = 0; } else { ClearAndStopTimeline(); } } } // Set visual without the materials (avoid boilerplate code) void USLVizSkeletalMeshMarker::SetPoseableMeshComponentVisual(USkeletalMesh* SkelMesh) { // Clear any previous data Reset(); if (!PMCRef || !PMCRef->IsValidLowLevel() || PMCRef->IsPendingKillOrUnreachable()) { PMCRef = NewObject<UPoseableMeshComponent>(this); PMCRef->SetCollisionEnabled(ECollisionEnabled::NoCollision); PMCRef->bPerBoneMotionBlur = false; PMCRef->bHasMotionBlurVelocityMeshes = false; PMCRef->bSelectable = false; PMCRef->SetVisibility(false); //PMCRef->AttachToComponent(this, FAttachmentTransformRules::KeepWorldTransform); PMCRef->RegisterComponent(); } // Set the reference visual PMCRef->SetSkeletalMesh(SkelMesh); } // Create poseable mesh component instance attached and registered to this marker UPoseableMeshComponent* USLVizSkeletalMeshMarker::CreateNewPoseableMeshInstance() { UPoseableMeshComponent* NewPMC = DuplicateObject<UPoseableMeshComponent>(PMCRef, this); NewPMC->SetVisibility(true); //NewPMC->AttachToComponent(this, FAttachmentTransformRules::KeepWorldTransform); NewPMC->RegisterComponent(); return NewPMC; } /* End VizMarker interface */
2e1633f93d6a987c7c00427327636bd537a3252a
ac647c2187c141f6b5f5c646b06dfce8870825b6
/Framework-EGC-master/Source/Laboratoare/Laborator8/Laborator8.cpp
6fabe61ca2641baefd9558e3d88b897dbda3ba09
[]
no_license
florinrm/BilliardGame
971167fd77666b3ed878298d4f66a7e8ba96410a
c1af0bb0422e934ab80b509eb37be8534998bb9d
refs/heads/master
2020-04-06T12:26:10.174408
2018-12-02T18:58:50
2018-12-02T18:58:50
157,455,362
0
0
null
null
null
null
UTF-8
C++
false
false
8,166
cpp
#include "Laborator8.h" #include <vector> #include <string> #include <iostream> #include <Core/Engine.h> using namespace std; Laborator8::Laborator8() { } Laborator8::~Laborator8() { } void Laborator8::Init() { { Mesh* mesh = new Mesh("box"); mesh->LoadMesh(RESOURCE_PATH::MODELS + "Primitives", "box.obj"); meshes[mesh->GetMeshID()] = mesh; } { Mesh* mesh = new Mesh("sphere"); mesh->LoadMesh(RESOURCE_PATH::MODELS + "Primitives", "sphere.obj"); meshes[mesh->GetMeshID()] = mesh; } { Mesh* mesh = new Mesh("plane"); mesh->LoadMesh(RESOURCE_PATH::MODELS + "Primitives", "plane50.obj"); meshes[mesh->GetMeshID()] = mesh; } // Create a shader program for drawing face polygon with the color of the normal { Shader *shader = new Shader("ShaderLab8"); shader->AddShader("Source/Laboratoare/Laborator8/Shaders/VertexShader.glsl", GL_VERTEX_SHADER); shader->AddShader("Source/Laboratoare/Laborator8/Shaders/FragmentShader.glsl", GL_FRAGMENT_SHADER); shader->CreateAndLink(); shaders[shader->GetName()] = shader; } //Light & material properties { lightPosition = glm::vec3(0, 1, 1); lightDirection = glm::vec3(0, -1, 0); materialShininess = 30; materialKd = 0.5; materialKs = 0.5; cutoff_angle = 30; } } void Laborator8::FrameStart() { // clears the color buffer (using the previously set color) and depth buffer glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::ivec2 resolution = window->GetResolution(); // sets the screen area where to draw glViewport(0, 0, resolution.x, resolution.y); } void Laborator8::Update(float deltaTimeSeconds) { { glm::mat4 modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, glm::vec3(0, 1, 0)); RenderSimpleMesh(meshes["sphere"], shaders["ShaderLab8"], modelMatrix, glm::vec3(0, 0, 1)); } { glm::mat4 modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, glm::vec3(2, 0.5f, 0)); modelMatrix = glm::rotate(modelMatrix, RADIANS(60.0f), glm::vec3(1, 0, 0)); modelMatrix = glm::scale(modelMatrix, glm::vec3(0.5f)); RenderSimpleMesh(meshes["box"], shaders["ShaderLab8"], modelMatrix, glm::vec3(1, 0, 0)); } { glm::mat4 modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, glm::vec3(-2, 0.5f, 0)); modelMatrix = glm::rotate(modelMatrix, RADIANS(60.0f), glm::vec3(1, 1, 0)); RenderSimpleMesh(meshes["box"], shaders["ShaderLab8"], modelMatrix, glm::vec3(0, 0.5, 0)); } // Render ground { glm::mat4 modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, glm::vec3(0, 0.01f, 0)); modelMatrix = glm::scale(modelMatrix, glm::vec3(0.25f)); RenderSimpleMesh(meshes["plane"], shaders["ShaderLab8"], modelMatrix, glm::vec3(0.603, 0.603, 0.603)); } // Render the point light in the scene { glm::mat4 modelMatrix = glm::mat4(1); modelMatrix = glm::translate(modelMatrix, lightPosition); modelMatrix = glm::scale(modelMatrix, glm::vec3(0.1f)); RenderMesh(meshes["sphere"], shaders["Simple"], modelMatrix); } } void Laborator8::FrameEnd() { DrawCoordinatSystem(); } void Laborator8::RenderSimpleMesh(Mesh *mesh, Shader *shader, const glm::mat4 & modelMatrix, const glm::vec3 &color) { if (!mesh || !shader || !shader->GetProgramID()) return; // render an object using the specified shader and the specified position glUseProgram(shader->program); // Set shader uniforms for light & material properties // TODO: Set light position uniform int light_position = glGetUniformLocation(shader->program, "light_position"); glUniform3f(light_position, lightPosition.x, lightPosition.y, lightPosition.z); int light_direction = glGetUniformLocation(shader->program, "light_direction"); glUniform3f(light_direction, lightDirection.x, lightDirection.y, lightDirection.z); // TODO: Set eye position (camera position) uniform glm::vec3 eyePosition = GetSceneCamera()->transform->GetWorldPosition(); int eye_position = glGetUniformLocation(shader->program, "eye_position"); glUniform3f(eye_position, eyePosition.x, eyePosition.y, eyePosition.z); // TODO: Set material property uniforms (shininess, kd, ks, object color) int material_shininess = glGetUniformLocation(shader->program, "material_shininess"); glUniform1i(material_shininess, materialShininess); int material_kd = glGetUniformLocation(shader->program, "material_kd"); glUniform1f(material_kd, materialKd); int material_ks = glGetUniformLocation(shader->program, "material_ks"); glUniform1f(material_ks, materialKs); int object_color = glGetUniformLocation(shader->program, "object_color"); glUniform3f(object_color, color.r, color.g, color.b); // Bind model matrix GLint loc_model_matrix = glGetUniformLocation(shader->program, "Model"); glUniformMatrix4fv(loc_model_matrix, 1, GL_FALSE, glm::value_ptr(modelMatrix)); // Bind view matrix glm::mat4 viewMatrix = GetSceneCamera()->GetViewMatrix(); int loc_view_matrix = glGetUniformLocation(shader->program, "View"); glUniformMatrix4fv(loc_view_matrix, 1, GL_FALSE, glm::value_ptr(viewMatrix)); // Bind projection matrix glm::mat4 projectionMatrix = GetSceneCamera()->GetProjectionMatrix(); int loc_projection_matrix = glGetUniformLocation(shader->program, "Projection"); glUniformMatrix4fv(loc_projection_matrix, 1, GL_FALSE, glm::value_ptr(projectionMatrix)); int type = glGetUniformLocation(shader->program, "t"); glUniform1i(type, typeOfLight); int cut_off_angle = glGetUniformLocation(shader->program, "cut_off_angle"); glUniform1f(cut_off_angle, cutoff_angle); // Draw the object glBindVertexArray(mesh->GetBuffers()->VAO); glDrawElements(mesh->GetDrawMode(), static_cast<int>(mesh->indices.size()), GL_UNSIGNED_SHORT, 0); } // Documentation for the input functions can be found in: "/Source/Core/Window/InputController.h" or // https://github.com/UPB-Graphics/Framework-EGC/blob/master/Source/Core/Window/InputController.h void Laborator8::OnInputUpdate(float deltaTime, int mods) { float speed = 2; if (!window->MouseHold(GLFW_MOUSE_BUTTON_RIGHT)) { glm::vec3 up = glm::vec3(0, 1, 0); glm::vec3 right = GetSceneCamera()->transform->GetLocalOXVector(); glm::vec3 forward = GetSceneCamera()->transform->GetLocalOZVector(); forward = glm::normalize(glm::vec3(forward.x, 0, forward.z)); // Control light position using on W, A, S, D, E, Q if (window->KeyHold(GLFW_KEY_W)) lightPosition -= forward * deltaTime * speed; if (window->KeyHold(GLFW_KEY_A)) lightPosition -= right * deltaTime * speed; if (window->KeyHold(GLFW_KEY_S)) lightPosition += forward * deltaTime * speed; if (window->KeyHold(GLFW_KEY_D)) lightPosition += right * deltaTime * speed; if (window->KeyHold(GLFW_KEY_E)) lightPosition += up * deltaTime * speed; if (window->KeyHold(GLFW_KEY_Q)) lightPosition -= up * deltaTime * speed; if (window->KeyHold(GLFW_KEY_I)) angleOX += deltaTime * 5; if (window->KeyHold(GLFW_KEY_J)) angleOY += deltaTime * 5; if (window->KeyHold(GLFW_KEY_K)) angleOX -= deltaTime * 5; if (window->KeyHold(GLFW_KEY_L)) angleOY -= deltaTime * 5; if (window->KeyHold(GLFW_KEY_Z)) cutoff_angle += deltaTime * 20; if (window->KeyHold(GLFW_KEY_X)) cutoff_angle -= deltaTime * 20; glm::mat4 turn = glm::mat4(1); turn = glm::rotate(turn, angleOY, glm::vec3(0, 1, 0)); turn = glm::rotate(turn, angleOX, glm::vec3(1, 0, 0)); lightDirection = glm::vec3(0, -1, 0); lightDirection = glm::vec3(turn * glm::vec4(lightDirection, 0)); } } void Laborator8::OnKeyPress(int key, int mods) { // add key press event if (key == GLFW_KEY_F) typeOfLight = 1 - typeOfLight; } void Laborator8::OnKeyRelease(int key, int mods) { // add key release event } void Laborator8::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY) { // add mouse move event } void Laborator8::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods) { // add mouse button press event } void Laborator8::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods) { // add mouse button release event } void Laborator8::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY) { } void Laborator8::OnWindowResize(int width, int height) { }
a66808dab706498b7e18ddbd537fed7af83ba550
7a684242f58f96af44eac0962490c10167f4e489
/C++ Programs/Decision and Loop/C++ Program to Display Fibonacci Series.cpp
9a0e52d7f2bce99398cb0ef3d1513001bf2eef05
[]
no_license
SaifRehman99/C-Plus-Plus-Tutorials
58bdfe9244e755edebc6b32c253533faa11a227d
5ab868e5282d967110feb855e7fdd3c7801da96f
refs/heads/master
2020-03-31T18:19:58.377017
2018-12-28T17:30:09
2018-12-28T17:30:09
152,454,645
2
0
null
null
null
null
UTF-8
C++
false
false
486
cpp
#include<iostream> using namespace std ; main(){ int firstnumber=0,secondnumber=1,nextnumber=0,n; cout<<"Enter Number of Terms = "; cin>>n; for(int i=1;i<=n;i++){ if(i==1){ cout<< " "<< firstnumber ; continue; } if(i==2){ cout<<" "<<secondnumber; continue; } nextnumber=firstnumber + secondnumber; //1 // 2 // 3 firstnumber=secondnumber; //1//1 //2 secondnumber=nextnumber; //1//2 //3 cout<<" "<< nextnumber<<" "; } }
c5231698264705bd8e385103bc07f131466bd502
4d1e24c7178e77d22692d3a7bc2455a934db346c
/Template_Function.cpp
d800d72025cc7d3516bf999ee71c8be291774e2b
[ "Apache-2.0" ]
permissive
doubleZ0108/my-C-Cpp-study
259f5d9ea4c4f3956cf42ccec3397486cb4f06f3
7bf27ea2e968ca012d0e712000f4e4569b0c253c
refs/heads/master
2020-03-31T09:09:31.251709
2020-02-07T15:02:44
2020-02-07T15:02:44
152,084,842
0
0
null
null
null
null
GB18030
C++
false
false
821
cpp
#include <iostream> #include <cstdlib> using namespace std; template<class type> //这里用class也可以 void Swap(type &a, type &b) { type buf; buf = a; a = b; b = buf; } template<typename type1,typename type2, typename rttype> //这里的用法是不可以的,因为通过函数调用是不能推断出rttype的类型的 //这里想要展示的是多个模板类型的语法 rttype Max(type1 a, type2 b) { if (a > b) { return a; } else { return b; } } int main(void) { int a = 3, b = 4; Swap(a, b); //注意Swap函数的参数类型是引用,所以必须使用变量作为参数,不可以使用常数 cout << a << ' ' << b << endl; int num = 10; double buf = 15.5; cout << "max number is " << Max(num, buf) << endl; //这样是错误的 system("pause"); return 0; }
e74787c30071bdcc5212b1f63bed7782852643e5
34ae61e2b612358cf385ea356c3fa6cb6842ccbf
/Classes/Entities/Notifier.cpp
6087a2d8501f4f4480fe8a9581977b0fc3b0d396
[ "MIT" ]
permissive
dare0021/October3rd
f5dcf4542a7f5f0cebe63a365252989f8030125b
79044467616b50ed068af79e64cdbe430f585792
refs/heads/master
2020-04-04T16:18:07.263656
2016-02-03T09:56:00
2016-02-03T09:56:00
42,033,224
0
0
null
null
null
null
UTF-8
C++
false
false
14,363
cpp
#include "Notifier.h" #include "Helpers/Consts.h" #include "Helpers/StaticHelpers.h" //#define SHOW_OFFSCREEN_OBJECTS USING_NS_CC; Notifier::Notifier(std::string path, Vec2 screenSize) : O3Sprite("", true), resourceFolderPath(path), timeSinceLastOpacityUpdate(0), screenSize(screenSize) { // need to attach the prototypes to something to prevent // the garbage collector from freeing them auto prototypes = Sprite::create(); offscreenEnemyPrototype = Sprite::create(resourceFolderPath + "/offscreen/enemy-bg.png"); auto offscreenEnemyFG = Sprite::create(resourceFolderPath + "/offscreen/enemy-fg.png"); offscreenEnemyPrototype->addChild(offscreenEnemyFG); offscreenEnemyFG->setPosition(Vec2(20, 20)); prototypes->addChild(offscreenEnemyPrototype); offscreenTorpedoPrototype = Sprite::create(resourceFolderPath + "/offscreen/torpedo-bg.png"); auto offscreenTorpedoFG = Sprite::create(resourceFolderPath + "/offscreen/torpedo-fg.png"); offscreenTorpedoPrototype->addChild(offscreenTorpedoFG); offscreenTorpedoFG->setPosition(Vec2(20, 20)); prototypes->addChild(offscreenTorpedoPrototype); offscreenCMPrototype = Sprite::create(resourceFolderPath + "/offscreen/cm.png"); prototypes->addChild(offscreenCMPrototype); offscreenPingPrototype = Sprite::create(resourceFolderPath + "/offscreen/ping.png"); prototypes->addChild(offscreenPingPrototype); offscreenTubeFillingPrototype = Sprite::create(resourceFolderPath + "/offscreen/tube-filling.png"); prototypes->addChild(offscreenTubeFillingPrototype); prototypes->setVisible(false); addChild(prototypes); minimap = Sprite::create(resourceFolderPath + "/bg-big.png"); Vec2 minimapPos = screenSize/2 - MINIMAP_SIZE/2; minimapPos.y *= -1; minimap->setPosition(minimapPos); addChild(minimap); auto s = addSprite("hp bar", "centergui/hp.png"); s->setOpacity(255*.3); s->setPosition(Vec2(-212 , -0.5*GUI_BAR_HEIGHT)); s->setAnchorPoint(Vec2(0.5, 0)); s = addSprite("noise bar", "centergui/noise.png"); s->setOpacity(255*.4); s->setPosition(Vec2(225, -0.5*GUI_BAR_HEIGHT)); s->setAnchorPoint(Vec2(0.5, 0)); s = addSprite("thrust bar", "centergui/thrust.png"); s->setOpacity(255*.5); s->setPosition(Vec2(212, -0.5*GUI_BAR_HEIGHT)); s->setAnchorPoint(Vec2(0.5, 0)); s = addSprite("subsystem menu", "centergui/subsystem-menu.png"); s->setOpacity(255*.5); s->setPosition(Vec2(-85, -230)); // static sprite ergo no need to fudge with the anchor point hpText = Label::createWithTTF("72", "fonts/NanumGothic.ttf", 33); hpText->setPosition(Vec2(-220, -140)); hpText->setAnchorPoint(Vec2(1, 0.5)); hpText->setColor(Color3B(0, 255, 102)); hpText->setOpacity(255*.5); addChild(hpText); speedText = Label::createWithTTF("12 kt", "fonts/NanumGothic.ttf", 37); speedText->setPosition(Vec2(-152, -188)); speedText->setAnchorPoint(Vec2(1, 0.5)); speedText->setColor(Color3B(0, 255, 255)); speedText->setOpacity(255*.5); addChild(speedText); thrustText = Label::createWithTTF("0%", "fonts/NanumGothic.ttf", 27); thrustNormalX = 172; thrustNegativeX = 200; thrustText->setPosition(Vec2(thrustNormalX, -177)); thrustText->setAnchorPoint(Vec2(0, 0.5)); thrustText->setOpacity(255*.5); addChild(thrustText); noiseText = Label::createWithTTF("0 dB", "fonts/NanumGothic.ttf", 27); noiseText->setPosition(Vec2(235, -150)); noiseText->setAnchorPoint(Vec2(0, 0.5)); noiseText->setColor(Color3B(255, 0, 0)); noiseText->setOpacity(255*.7); addChild(noiseText); menuText = Label::createWithTTF("0: stop\n\n2: full ahead", "fonts/NanumGothicCoding.ttf", 27); menuText->setPosition(Vec2(-124, -283)); menuText->setAnchorPoint(Vec2(0, 0.5)); menuText->setOpacity(255*.5); addChild(menuText); activeMenuText = Label::createWithTTF("\n1: half ahead\n", "fonts/NanumGothicCoding.ttf", 27); activeMenuText->setPosition(Vec2(-124, -283)); activeMenuText->setAnchorPoint(Vec2(0, 0.5)); activeMenuText->setColor(Color3B(255, 0, 0)); activeMenuText->setOpacity(255*.7); addChild(activeMenuText); } /// uses the given sprite if this is not isDotNode /// uses the color if this isDotNode void Notifier::newMinimapEntry(O3Sprite* minimapSprite, Vec2 pos, float ttl, bool isDotNode, int id, std::string dotPath) { #ifndef SHOW_OFFSCREEN_OBJECTS // ignore objects outside of bounds // necessary since culling should be done off screen instead of having // the torpedo disappear magically if(pos.x < -1*GAME_SIZE.x/2 || pos.x > GAME_SIZE.x/2 || pos.y < -1*GAME_SIZE.y/2 || pos.y > GAME_SIZE.y/2) { auto kvp = minimapEntries.find(id); if(kvp != minimapEntries.end()) { kvp->second->fading = true; } return; } #endif auto kvp = minimapEntries.find(id); if(kvp == minimapEntries.end()) { if(isDotNode) { for (int i=0; i<MINIMAP_DOT_ANIM_COUNT; i++) { std::string filePath = resourceFolderPath + "/dots/" + dotPath + std::to_string(i) + ".png"; minimapSprite->addSprite(filePath, filePath); } } minimapEntries[id] = new MinimapElem(minimapSprite, ttl, isDotNode); minimap->addChild(minimapSprite); } else { // cocos2d::Node anchor is centered // cocos2d::Sprite anchor is bottom left float xrat = GAME_SIZE.x / MINIMAP_INTERNAL_SIZE.x; float yrat = GAME_SIZE.y / MINIMAP_INTERNAL_SIZE.y; auto prospectiveVal = Vec2(pos.x / xrat, pos.y / yrat) + MINIMAP_SIZE/2; int dx = kvp->second->nextPos.x - prospectiveVal.x; int dy = kvp->second->nextPos.y - prospectiveVal.y; if(dx || dy) { kvp->second->nextPos = prospectiveVal; kvp->second->dirty = true; } kvp->second->ttl = ttl; } } void Notifier::newMinimapTorpedo(Vec2 pos, int id) { auto minimapSprite = new O3Sprite("", true); newMinimapEntry(minimapSprite, pos, MINIMAP_ICON_TTL, true, id, "white/"); } /// AI player void Notifier::newMinimapSubmarine(Vec2 pos, int id) { auto minimapSprite = new O3Sprite("", true); newMinimapEntry(minimapSprite, pos, MINIMAP_ICON_TTL, true, id, "red/"); } /// the human player void Notifier::newMinimapPlayer(Vec2 pos, int id) { auto minimapSprite = new O3Sprite("", true); newMinimapEntry(minimapSprite, pos, MINIMAP_ICON_TTL, true, id, "green/"); } void Notifier::newMinimapCounterMeasure(Vec2 pos, int id) { auto minimapSprite = new O3Sprite("", true); newMinimapEntry(minimapSprite, pos, MINIMAP_ICON_TTL, true, id, "cyan/"); } void Notifier::newMinimapPing(Vec2 pos, int id) { auto minimapSprite = new O3Sprite("", true); int count = 150; int fps = 30; minimapSprite->addAnimation("idle", resourceFolderPath + "/ping", count, fps); minimapSprite->setAnimation("idle"); minimapSprite->playAnimation(); newMinimapEntry(minimapSprite, pos, count / fps, false, id, "NOSUCHPATH"); } void Notifier::newMinimapTubeFilling(Vec2 pos, int id) { auto minimapSprite = new O3Sprite("", true); newMinimapEntry(minimapSprite, pos, MINIMAP_ICON_TTL, true, id, "orange/"); } void Notifier::newOffscreenEntry(Sprite* offscreenPrototype, Vec2 pos, int id) { #ifndef SHOW_OFFSCREEN_OBJECTS // ignore objects outside of bounds // necessary since culling should be done off screen instead of having // the torpedo disappear magically if(pos.x < -1*GAME_SIZE.x/2 || pos.x > GAME_SIZE.x/2 || pos.y < -1*GAME_SIZE.y/2 || pos.y > GAME_SIZE.y/2) { auto kvp = offscreenEntries.find(id); if(kvp != offscreenEntries.end()) { removeChild(kvp->second->sprite, true); delete offscreenEntries.find(id)->second; offscreenEntries.erase(id); } return; } #endif bool createNewMinimapOffscreenNotification = false; auto oe = offscreenEntries.find(id); int currentDirection = isOffscreen(pos); int angle = (currentDirection - 1) * 45; if(oe != offscreenEntries.end()) { auto entry = oe->second; if (entry->direction != currentDirection) { removeChild(entry->sprite); delete entry; offscreenEntries.erase(id); createNewMinimapOffscreenNotification = true; } // direction didn't change, but the precise location probably did else { auto spos = entry->sprite->getPosition(); switch (currentDirection) { case 1: case 5: entry->sprite->setPosition(Vec2(pos.x, spos.y)); break; case 3: case 7: entry->sprite->setPosition(Vec2(spos.x, pos.y)); break; case 2: case 4: case 6: case 8: break; default: CCASSERT(0, "Invalid direction"); break; } } } else if(currentDirection) { createNewMinimapOffscreenNotification = true; } if (createNewMinimapOffscreenNotification) { auto offscreenSprite = StaticHelpers::duplicateSprite(offscreenPrototype); offscreenSprite->setRotation(angle); if (offscreenSprite->getChildrenCount()) { auto fg = offscreenSprite->getChildren().front(); fg->setRotation(-1 * angle); } addChild(offscreenSprite); auto spriteSize = offscreenSprite->getBoundingBox().size; auto cornerVect = (screenSize - spriteSize) / 2; switch (currentDirection) { case 1: offscreenSprite->setPosition(Vec2(pos.x, screenSize.y / 2 - spriteSize.height)); break; case 2: offscreenSprite->setPosition(cornerVect); break; case 3: offscreenSprite->setPosition(Vec2(screenSize.x / 2 - spriteSize.width, pos.y)); break; case 4: offscreenSprite->setPosition(Vec2(cornerVect.x, -1 * cornerVect.y)); break; case 5: offscreenSprite->setPosition(Vec2(pos.x, -1 * screenSize.y / 2 + spriteSize.height)); break; case 6: offscreenSprite->setPosition(-1 * cornerVect); break; case 7: offscreenSprite->setPosition(Vec2(-1 * screenSize.x / 2 + spriteSize.width, pos.y)); break; case 8: offscreenSprite->setPosition(Vec2(-1 * cornerVect.x, cornerVect.y)); break; default: CCASSERT(0, "Invalid direction"); break; } offscreenEntries[id] = new OffscreenElem(offscreenSprite, currentDirection); } } void Notifier::newOffscreenTorpedo(Vec2 pos, int id) { newOffscreenEntry(offscreenTorpedoPrototype, pos, id); } /// AI player void Notifier::newOffscreenSubmarine(Vec2 pos, int id) { newOffscreenEntry(offscreenEnemyPrototype, pos, id); } void Notifier::newOffscreenCounterMeasure(Vec2 pos, int id) { newOffscreenEntry(offscreenCMPrototype, pos, id); } void Notifier::newOffscreenPing(Vec2 pos, int id) { newOffscreenEntry(offscreenPingPrototype, pos, id); } void Notifier::newOffscreenTubeFilling(Vec2 pos, int id) { newOffscreenEntry(offscreenTubeFillingPrototype, pos, id); } void Notifier::setLookingAt(Vec2 pos) { lookingAt = pos; } /// 0: nothing removed /// 1: only removed from the minimap /// 2: removed from both the minimap and the offscreen notification int Notifier::removeItem(int id) { auto mme = minimapEntries.find(id); if (mme == minimapEntries.end()) return 0; minimap->removeChild(mme->second->sprite, true); delete minimapEntries.find(id)->second; minimapEntries.erase(id); auto ose = offscreenEntries.find(id); // is detected but visible on screen if (ose == offscreenEntries.end()) return 1; removeChild(ose->second->sprite, true); delete offscreenEntries.find(id)->second; offscreenEntries.erase(id); return 2; } void Notifier::setHPBar(float ratio) { setBarPercentage("hp bar", ratio); } void Notifier::setThrustBar(float ratio) { setBarPercentage("thrust bar", ratio); } void Notifier::setNoiseBar(float dB) { auto ratio = dB < 0 ? 1 : dB / 100 * 2; setBarPercentage("noise bar", ratio); } void Notifier::setHPText(float hp) { hpText->setString(std::to_string((int)std::round(hp))); } void Notifier::setThrustText(float thrust) { auto xpos = thrust < 0 ? thrustNegativeX : thrustNormalX; thrustText->setPosition(Vec2(xpos, thrustText->getPosition().y)); thrustText->setString(std::to_string((int)std::round(thrust)) + "%"); } void Notifier::setNoiseText(float noise) { std::string out = noise < 0 ? "deafening" : std::to_string((int)std::round(noise)) + " dB"; noiseText->setString(out); } void Notifier::setSpeedText(float speed) { speedText->setString(std::to_string((int)std::round(speed * OBJECT_SPEED_FUDGE)) + " kt"); } void Notifier::setMenuText(std::string txt) { menuText->setString(txt); } void Notifier::setActiveMenuText(std::string txt) { activeMenuText->setString(txt); } void Notifier::update(float dt) { timeSinceLastOpacityUpdate += dt; std::vector<int> toRemove; // minimap curation. Opacity modification / deleting old dots if (timeSinceLastOpacityUpdate >= MINIMAP_REDRAW_FREQ) { timeSinceLastOpacityUpdate -= MINIMAP_REDRAW_FREQ; for (auto kvp : minimapEntries) { auto elem = kvp.second; elem->ttl -= MINIMAP_REDRAW_FREQ; bool removeFlag = false; if (elem->ttl <= 0) { removeFlag = true; } else if(elem->isDotNode) { if(elem->dirty) { Vec2 swapTemp; for (auto i : elem->sprite->getChildren()) { swapTemp = i->getPosition(); i->setPosition(elem->nextPos); elem->nextPos = swapTemp; } elem->dirty = false; } } else if (elem->dirty) { elem->sprite->setPosition(elem->nextPos); elem->dirty = false; } if(removeFlag) { toRemove.push_back(kvp.first); } else if(elem->fading) { for (auto i : elem->sprite->getChildren()) { if(i->isVisible()) { i->setVisible(false); break; } } elem->dirty = true; } } // clean up since you can't erase collection elements while iterating over it for (int id : toRemove) { removeItem(id); } } for (auto kvp : minimapEntries) { kvp.second->sprite->update(dt); for (auto s : kvp.second->sprite->getChildren()) { s->update(dt); } } for (auto kvp : offscreenEntries) { kvp.second->sprite->update(dt); } } int Notifier::isOffscreen(Vec2 pos) { bool n, e, s, w; n = e = s = w = false; if(pos.y > lookingAt.y + screenSize.y / 2) n = true; else if(pos.y < lookingAt.y - screenSize.y / 2) s = true; if(pos.x > lookingAt.x + screenSize.x / 2) e = true; else if(pos.x < lookingAt.x - screenSize.x / 2) w = true; if(n && e) return 2; if(n && w) return 8; if(s && e) return 4; if(s && w) return 6; if(n) return 1; if(e) return 3; if(s) return 5; if(w) return 7; return 0; } /// ratio should have range [0, 1] void Notifier::setBarPercentage(std::string name, float ratio) { auto sprite = sprites.find(name)->second; float toShow = ratio * GUI_BAR_HEIGHT; sprite->setTextureRect(Rect(0, GUI_BAR_HEIGHT - toShow, 68, toShow)); }
faad6599a6a18eba030fad1d2ce2091de5a53525
ca3df20a5b4b133de37a2b2714757f78d4fdf693
/Assignment 4/Sav9EdC4P5/main.cpp
40c3ec4a813f73b4cecf9426483551210c84155a
[]
no_license
1391878122/Qingkai-Zhang1
62547d66ebdb6e6a6605b5a7c6e5bb49cefe879d
cc5f0479b9c573a942e063c01389a6fca020d3d8
refs/heads/master
2022-09-25T14:06:19.745665
2020-06-06T04:48:57
2020-06-06T04:48:57
258,684,644
0
0
null
null
null
null
UTF-8
C++
false
false
1,079
cpp
//System Libraries #include <iostream> //Input/Output Library #include<iomanip> using namespace std; //User Libraries //Global Constants, no Global Variables are allowed //Math/Physics/Conversions/Higher Dimensions - i.e. PI, e, etc... //Function Prototypes //Execution Begins Here! int main(int argc, char** argv) { float num1,num2,num3; char command; while(command!='n'){ cout<<"Enter current price:"<<endl<<"Enter year-ago price:"<<endl<<"Inflation rate: "; cin>>num1>>num2>>command; num3=(num1-num2)/num2*100; cout<<fixed<<setprecision(2)<<num3<<"%"<<endl<<endl; cout<<"Price in one year: $"<<num1*(1+num3/100)<<endl; cout<<"Price in two year: $"<<num1*(1+num3/100)*(1+num3/100)<<endl<<endl<<"Again:"<<endl; if(command=='y') cout<<endl; } //Set the random number seed //Declare Variables //Initialize or input i.e. set variable values //Map inputs -> outputs //Display the outputs //Exit stage right or left! return 0; }
76f7bb6b28b56a8f3b139ba81f083971a4716792
53400caec1b30e7b6e8895fe4dc60cf6799a9e55
/MyTools/TypeTool.h
5892d0a5d66dc819a3767014dc5a3f773217db2d
[]
no_license
181847/MyLibrary_of_C_Cplusplus
9d46e6641af5371af82dc7536633845691df5170
c9a62e2be04c280e38f2f5154f968ac734453486
refs/heads/master
2018-11-11T16:08:33.736318
2018-09-09T12:01:34
2018-09-09T12:01:34
111,888,240
0
0
null
null
null
null
UTF-8
C++
false
false
5,594
h
#pragma once #include <type_traits> namespace TypeTool { // this struct is used to generate the id for specific type, // the id is unique for specific SERIES_TYPE, // you can change the SERIES_TYPE to get other series id. // the ID start from one, // and the zero means a invalid ID. template<typename SERIES_TYPE> struct IDGenerator { private: // store the current max id, // before called newID(), it should be 0. static size_t m_distribID; public: template<typename TYPE> inline static const size_t IDOf() { static const size_t idOfTheType = ++m_distribID; return idOfTheType; } }; //|||||||||||||||||||||||||||||||||||||||||||||||||| // initialize the series id of the specific Series type template<typename Series> size_t IDGenerator<Series>::m_distribID = 0; // BoolCondition used to return the bool based on the CONDITION value. template<bool CONDITION, bool THEM, bool ELSE> struct BoolCondition{}; //|||||||||||||||||||||||||||||||||||||||||||||||||| template<bool THEN, bool ELSE> struct BoolCondition<true, THEN, ELSE> { enum { value = THEN }; }; //|||||||||||||||||||||||||||||||||||||||||||||||||| template<bool THEN, bool ELSE> struct BoolCondition<false, THEN, ELSE> { enum { value = ELSE }; }; // struct IsOneOf is used to check whether a type is in the list of types. // the first parameter is the type to be checked, rest are the typeList. // Usage: IsOneOf<int, float, char, double>::value => false // IsOneOf<int, float, char, int>::value => true. template<typename TYPE, typename ...TYPE_LIST> struct IsOneOf {}; //|||||||||||||||||||||||||||||||||||||||||||||||||| template<typename TYPE, typename FIRST, typename ...REST> struct IsOneOf<TYPE, FIRST, REST...> { enum { value = BoolCondition<std::is_same<TYPE, FIRST>::value, true, IsOneOf<TYPE, REST...>::value>::value }; }; //|||||||||||||||||||||||||||||||||||||||||||||||||| template<typename TYPE> struct IsOneOf<TYPE> { enum { value = false }; }; // TypeContainer to have a set of type to be checked. template<typename ...TYPE_LIST> struct TypeContainer{}; //|||||||||||||||||||||||||||||||||||||||||||||||||| // Seperate the set of types to the firstType, // and the rest to another TypeContainer. template<typename FIRST, typename ...REST> struct TypeContainer<FIRST, REST...> { typedef typename FIRST firstType; typedef typename TypeContainer<REST...> restTypeContainer; }; //|||||||||||||||||||||||||||||||||||||||||||||||||| // If there is only one type left, // the restTypeContainer is the TypeContainer which have no template parameters. template<typename LAST> struct TypeContainer<LAST> { typedef LAST firstType; typedef typename TypeContainer<> restTypeContainer; }; // IsAllOf is the extension of IsOneOf, // It will check if all the types are in another typeList. // It MUST be used with typeContainer. // Usage: IsAllOf< TypeContainer<int, char>, double, int, char >::value => true // IsAllOf< TypeContainer<>, double, int >::value => true // IsAllOf< TypeContainer<void>, double, int >::value => false // IsAllOf< TypeContainer<void, double, int> >::value => false // IsAllOf< int, float, double >::value => compile error template<typename ...CHECK_ARGS> struct IsAllOf {}; //|||||||||||||||||||||||||||||||||||||||||||||||||| template<typename ...TYPE_LIST> struct IsAllOf<TypeContainer<>, TYPE_LIST...> { enum { value = true }; }; //|||||||||||||||||||||||||||||||||||||||||||||||||| template<typename ...TYPE_LIST_ALL, typename ...TYPE_LIST> struct IsAllOf<TypeContainer<TYPE_LIST_ALL...>, TYPE_LIST...> { typedef TypeContainer<TYPE_LIST_ALL...> TYPE_CONTAINER; enum { value = IsOneOf<TYPE_CONTAINER::firstType, TYPE_LIST...>::value && IsAllOf<TYPE_CONTAINER::restTypeContainer, TYPE_LIST...>::value }; }; /*! \brief in the TYPE_LIST, get one type whose size equal to TYPE_SIZE \param TYPE_SIZE the size of the expected type \param TYPE_LIST... where to selected the type, or can use a TypeContainer to obtain a set of types \usage GetTypeBySize<8>::type => compile error GetTypeBySize<4, char, short, int, long>::type => int GetTypeBySize<13, char, short, int, long>::type => void, no type whose size is 13 GetTypeBySize<4, TypeContainer<char, int>>::type => int GetTypeBySize<4, TypeContainer<>>::type => void GetTypeBySize<13, TypeContainer<char, long>>::type => void */ template<unsigned int TYPE_SIZE, typename ...TYPE_LIST> struct GetTypeBySize { typedef typename GetTypeBySize<TYPE_SIZE, TypeTool::TypeContainer<TYPE_LIST...>>::type type; }; //||||||||| no type provided |||||||||||| template<unsigned int TYPE_SIZE> struct GetTypeBySize<TYPE_SIZE> { //static_assert(false, "Please provide some type to choose"); }; //|||||||||| type container is empty ||||||||||||||||||||| template<unsigned int TYPE_SIZE> struct GetTypeBySize<TYPE_SIZE, TypeTool::TypeContainer<>> { // no compile error, but return void as the wrong signal. typedef void type; }; //||||||||||| try to get one type that satisfies the TYPE_SIZE |||||||||||||||||||||||||| template<unsigned int TYPE_SIZE, typename ...TYPE_LIST> struct GetTypeBySize<TYPE_SIZE, TypeTool::TypeContainer<TYPE_LIST...>> { typedef typename TypeTool::TypeContainer<TYPE_LIST...> M_TypeContainer; typedef typename std::conditional<TYPE_SIZE == sizeof(typename M_TypeContainer::firstType), typename M_TypeContainer::firstType, typename GetTypeBySize<TYPE_SIZE, typename M_TypeContainer::restTypeContainer >::type >::type type; //static_assert(TYPE_SIZE == sizeof(type)); }; } // namespace TypeTool
c06e5d711df40ee3df183ead72afd570e9601d08
b495209212ba745251914fee2ba6aebf90932b44
/src/PageResource«CurrencyResource».h
ced2ba0b3be50dedb382ac260bf2a7149a667eda
[]
no_license
knetikmedia/knetikcloud-tizen-client
21e1d9a0f98ca275f372af05dfb699adf46b7679
28be72af9caa0980570ff20fc798bdcf67b5550a
refs/heads/master
2021-01-13T13:34:44.915887
2018-03-14T16:05:13
2018-03-14T16:05:13
76,421,710
0
0
null
null
null
null
UTF-8
C++
false
false
2,198
h
/* * PageResource«CurrencyResource».h * * */ #ifndef _PageResource«CurrencyResource»_H_ #define _PageResource«CurrencyResource»_H_ #include <string> #include "CurrencyResource.h" #include "Order.h" #include <list> #include "Object.h" /** \defgroup Models Data Structures for API * Classes containing all the Data Structures needed for calling/returned by API endpoints * */ namespace Tizen { namespace ArtikCloud { /*! \brief * * \ingroup Models * */ class PageResource«CurrencyResource» : public Object { public: /*! \brief Constructor. */ PageResource«CurrencyResource»(); PageResource«CurrencyResource»(char* str); /*! \brief Destructor. */ virtual ~PageResource«CurrencyResource»(); /*! \brief Retrieve a string JSON representation of this class. */ char* toJson(); /*! \brief Fills in members of this class from JSON string representing it. */ void fromJson(char* jsonStr); /*! \brief Get */ std::list<CurrencyResource> getContent(); /*! \brief Set */ void setContent(std::list <CurrencyResource> content); /*! \brief Get */ bool getFirst(); /*! \brief Set */ void setFirst(bool first); /*! \brief Get */ bool getLast(); /*! \brief Set */ void setLast(bool last); /*! \brief Get */ int getNumber(); /*! \brief Set */ void setNumber(int number); /*! \brief Get */ int getNumberOfElements(); /*! \brief Set */ void setNumberOfElements(int number_of_elements); /*! \brief Get */ int getSize(); /*! \brief Set */ void setSize(int size); /*! \brief Get */ std::list<Order> getSort(); /*! \brief Set */ void setSort(std::list <Order> sort); /*! \brief Get */ long long getTotalElements(); /*! \brief Set */ void setTotalElements(long long total_elements); /*! \brief Get */ int getTotalPages(); /*! \brief Set */ void setTotalPages(int total_pages); private: std::list <CurrencyResource>content; bool first; bool last; int number; int number_of_elements; int size; std::list <Order>sort; long long total_elements; int total_pages; void __init(); void __cleanup(); }; } } #endif /* _PageResource«CurrencyResource»_H_ */
33052c57b947df6a6130a5fc850267f9de274090
9369318cdbde33f5910c6de3736f1d07400cf276
/414B.cpp
d7245de4aa3749c300f0394060fabbb486b8f0b8
[]
no_license
cwza/codeforces
cc58c646383a201e10422ec80567b52bef4a0da9
e193f5d766e8ddda6cdc8a43b9f1826eeecfc870
refs/heads/master
2023-04-11T12:22:04.555974
2021-04-22T04:45:20
2021-04-22T04:45:20
352,477,628
0
0
null
null
null
null
UTF-8
C++
false
false
1,077
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; /* 1. Precompute [1, 2000] number's factors 2. DP dp[n][k] = sum(dp[x][k-1] for x in factors[n]) dp[.][1] = 1 */ int n, k; const int maxN = 2000, maxK = 2000, M = 1e9+7; vector<int> factors[maxN+1]; int dp[maxN+1][maxK+1]; void createFactors() { // O(nlogn) for(int i = 1; i <= maxN; ++i) { for(int j = i; j <= maxN; j += i) { factors[j].push_back(i); } } } int main() { ios::sync_with_stdio(0); cin.tie(0); // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); createFactors(); cin >> n >> k; for(int i = 1; i <= n; ++i) { for(int j = 1; j <= k; ++j) { if(j==1) { dp[i][j] = 1; continue; } for(int a = 0; a < factors[i].size(); ++a) { dp[i][j] = (dp[i][j] + dp[factors[i][a]][j-1]) % M; } } } int ans = 0; for(int i = 1; i <= n; ++i) ans = (ans + dp[i][k]) % M; cout << ans; }
5655134d040e58882286894472935b3ec554f188
6d54335ef9d679c947473163513d5da971289887
/client/source/Image2D.h
817ca0819dd3c1f722fa3fe83562bdec70d7c506
[]
no_license
Blanel/agi_project_2
868f4afca2aa1f93fde30896917a90131ac6cfe5
62797a71dea01af259912f35d0496ea1893521d7
refs/heads/master
2020-06-08T07:36:47.025804
2012-12-21T09:09:17
2012-12-21T09:09:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,843
h
#ifndef IMAGE2D_H_ #define IMAGE2D_H_ #include "Types.h" #include <vector> #include <iostream> #include <cassert> #include <fstream> #include <cstring> #include "SDL_Image.h" #include "Log.h" #include <iterator> namespace revel { enum class PixelFormat { RGB_U8, RGBA_U8, GRAY_U8, GRAY_F32, UNDEFINED }; enum class ImageFormat { TGA, UNDEFINED }; namespace pixel { //forward decl struct RGB_u8; struct RGBA_u8; struct Gray_u8; struct Gray_f32; struct RGB_u8 { RGB_u8(); RGB_u8(u8 r, u8 g, u8 b); RGB_u8(const RGB_u8& c); RGB_u8(const RGBA_u8& c); RGB_u8(const Gray_u8& c); RGB_u8(const Gray_f32& c); static PixelFormat pixel_format(); u8 r, g, b; }; struct RGBA_u8 { RGBA_u8(); RGBA_u8(u8 r, u8 g, u8 b, u8 a); RGBA_u8(const RGBA_u8& c); RGBA_u8(const RGB_u8& c, u8 a = 255); RGBA_u8(const Gray_f32& c); static PixelFormat pixel_format(); u8 r, g, b, a; }; struct Gray_u8 { Gray_u8(u8 val = 0); static PixelFormat pixel_format(); u8 val; }; struct Gray_f32 { Gray_f32(f32 val = 0); static PixelFormat pixel_format(); f32 val; }; } // ::revel::pixel template <typename T> class Image2D { std::vector<T> m_Pixels; u32 m_Width, m_Height; PixelFormat m_PixelFormat; public: Image2D(u32 w, u32 h, T val = T()) : m_Pixels(w * h, val) , m_Width(w) , m_Height(h) , m_PixelFormat(T::pixel_format()) {} template <typename U> Image2D(const Image2D<U>& img) : m_Pixels(img.width() * img.height()) , m_Width(img.width()) , m_Height(img.height()) , m_PixelFormat(T::pixel_format()) { for (u32 i = 0; i < m_Pixels.size(); ++i) { m_Pixels[i] = img.data()[i]; } } Image2D(u32 w, u32 h, const std::vector<T>& pixeldata) : m_Pixels(pixeldata) , m_Width(w) , m_Height(h) , m_PixelFormat(T::pixel_format()) { assert(w * h == pixeldata.size()); } Image2D(const std::string& filename) { SDL_Surface* image = IMG_Load(filename.c_str()); SDL_PixelFormat* format = image->format; auto dataptr = (T*)image->pixels; if (image) { m_Width = image->w; m_Height = image->h; m_PixelFormat = T::pixel_format(); u32 pixelcount = m_Width * m_Height; /* u32 nOfColors = surface->format->BytesPerPixel; if (nOfColors == 4) // contains an alpha channel { if (surface->format->Rmask == 0x000000ff) texture_format = GL_RGBA; else texture_format = GL_BGRA; } else if (nOfColors == 3) // no alpha channel { if (surface->format->Rmask == 0x000000ff) texture_format = GL_RGB; else texture_format = GL_BGR; } else { R_LOG_ERR("warning: the image is not truecolor.. this will probably break"); } */ T* dataptr = (T*)image->pixels; m_Pixels.reserve(pixelcount); m_Pixels = std::vector<T>(dataptr, dataptr + pixelcount); for (auto& pixel : m_Pixels) { std::swap(pixel.r, pixel.b); } SDL_FreeSurface(image); } else { R_LOG_ERR("SDL Image" << IMG_GetError()); throw std::exception(); } } /* template <typename... Args> Image2D(u32 w, u32 h, Args&&... args) : m_Pixels(w*h, std::forward<Args>(args)...) , m_Width(w) , m_Height(h) , m_PixelFormat(T::pixel_format()) {} */ virtual ~Image2D() {} u32 width() const { return m_Width; } u32 height() const { return m_Height; } PixelFormat pixel_format() const { return m_PixelFormat; } T& operator()(u32 x, u32 y) { return m_Pixels[y*m_Width + x]; } const T& operator()(u32 x, u32 y) const { return m_Pixels[y*m_Width + x]; } const std::vector<T>& data() const { return m_Pixels; } }; } // ::revel #endif // IMAGE2D_H_
846ca4e0add16ddfc7fca701e1eb34f6f306055e
6f80725456e91d83cc22bd515a8a636460085039
/codeplus/16928.cpp
28241d787ceaddb0b4a0ef65c30e698139defafd
[]
no_license
greedy0110/algorithm
6061c9b48d93eb70b0dda6f40128325dee534047
ce205f04d29a9d6d6d98060bf92aa5511eb09418
refs/heads/master
2023-09-04T16:06:33.552642
2021-11-10T00:59:39
2021-11-10T00:59:39
279,033,190
0
0
null
null
null
null
UTF-8
C++
false
false
1,054
cpp
// // Created by 신승민 on 2021/08/01. // #include <bits/stdc++.h> using namespace std; #define RP(i, X) for (int i=0; i<((X)); i++) #define all(X) begin((X)), end((X)) #define endl '\n' typedef vector<int> vi; typedef vector<bool> vb; typedef vector<vi> vvi; typedef long long ll; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int N, M; cin >> N >> M; vi D(101, -1); vi next(101, -1); RP(i, 101) next[i] = i; RP(i, N) { int a, b; cin >> a >> b; next[a] = b; } RP(i, M) { int a, b; cin >> a >> b; next[a] = b; } queue<int> q; D[1] = 0; q.push(1); while (!q.empty()) { int c = q.front(); q.pop(); for (int i = 1; i <= 6; i++) { int n = c + i; if (n > 100) continue; n = next[n]; if (D[n] != -1) continue; D[n] = D[c] + 1; q.push(n); } } cout << D[100] << endl; return 0; }
1b689b82f9728f6530eab960d6eaa06e86da18ed
f22f1c9b9f0265295be7cb83433fcba66b620776
/native/include/src/main/include/jcpp/native/api/NativeString.h
4812c53094d18f8f8cd3790c697a65850328d10e
[]
no_license
egelor/jcpp-1
63c72c3257b52b37a952344a62fa43882247ba6e
9b5a180b00890d375d2e8a13b74ab5039ac4388c
refs/heads/master
2021-05-09T03:46:22.585245
2015-08-07T16:04:20
2015-08-07T16:04:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,873
h
#ifndef JCPP_NATIVE_API_NATIVESTRING #define JCPP_NATIVE_API_NATIVESTRING #include "jcpp/native/api/NativeInclude.h" #include <string> #include <iostream> namespace jcpp { namespace native { namespace api { class JCPP_EXPORT NativeString { friend JCPP_EXPORT NativeString operator+(const char*, const NativeString&); friend JCPP_EXPORT NativeString operator+(const wchar_t* wstr, const NativeString&); friend JCPP_EXPORT NativeString operator+(const std::string&, const NativeString&); friend JCPP_EXPORT NativeString operator+(const std::wstring&, const NativeString&); private: static char * className; jchar * value; jint size; NativeString(jchar * value, jint size); public: NativeString(); ~NativeString(); NativeString(const NativeString& original); NativeString(const char* str); NativeString(const wchar_t* wstr); NativeString(const std::string& str); NativeString(const std::wstring& wstr); NativeString(jchar c); NativeString(const char* str, jint offset, jint length); NativeString(const wchar_t* wstr, jint offset, jint length); NativeString(const jchar* c, jint offset, jint length); jint length() const; jbool isEmpty() const; jchar charAt(jint index) const; void getChars(jint cBegin, jint srcEnd, jchar * dst, jint dstBegin) const; jint indexOf(jchar ch) const; jint indexOf(jchar ch, jint fromIndex) const; jint lastIndexOf(jchar ch) const; jint lastIndexOf(jchar ch, jint fromIndex) const; jint indexOf(const NativeString& str) const; jint indexOf(const NativeString& str, jint fromIndex) const; jint lastIndexOf(const NativeString& str) const; jint lastIndexOf(const NativeString& str, jint fromIndex) const; jbool startsWith(const jchar ch) const; jbool startsWith(const NativeString& prefix) const; jbool startsWith(const NativeString& prefix, jint toffset) const; jbool endsWith(const jchar ch) const; jbool endsWith(const NativeString& suffix) const; NativeString substring(jint beginIndex) const; NativeString substring(jint beginIndex, jint endIndex) const; NativeString concat(const NativeString& str) const; NativeString replace(jchar oldChar, jchar newChar) const; NativeString trim() const; NativeString reverse() const; NativeString clone() const; NativeString toLowerCase() const; NativeString toUpperCase() const; jbool equalsIgnoreCase(const NativeString& str) const; jchar* getChars() const; std::string getString() const; std::wstring getWString() const; jchar operator[](jint index) const; NativeString& operator=(const NativeString& other); NativeString& operator=(const char* str); NativeString& operator=(const wchar_t* wstr); NativeString& operator=(const std::string& str); NativeString& operator=(const std::wstring& wstr); NativeString operator+(const NativeString& other) const; NativeString operator+(const char* str) const; NativeString operator+(const wchar_t* wstr) const; NativeString operator+(const std::string& str) const; NativeString operator+(const std::wstring& wstr) const; NativeString operator+(const jbool b) const; NativeString operator+(const jint i) const; NativeString operator+(const jshort s) const; NativeString operator+(const jlong l) const; NativeString operator+(const jfloat f) const; NativeString operator+(const jdouble d) const; NativeString operator+(const jbyte b) const; void operator+=(const NativeString& other); void operator+=(const char* str); void operator+=(const wchar_t* wstr); void operator+=(const std::string& str); void operator+=(const std::wstring& wstr); void operator+=(const jbool b); void operator+=(const jint i); void operator+=(const jshort s); void operator+=(const jlong l); void operator+=(const jfloat f); void operator+=(const jdouble d); void operator+=(const jbyte b); jbool operator==(const NativeString& other) const; jbool operator==(const char* str) const; jbool operator==(const wchar_t* wstr) const; jbool operator==(const std::string& str) const; jbool operator==(const std::wstring& wstr) const; jbool operator!=(const NativeString& other) const; jbool operator!=(const char* str) const; jbool operator!=(const wchar_t* wstr) const; jbool operator!=(const std::string& str) const; jbool operator!=(const std::wstring& wstr) const; jbool operator<(const NativeString& other) const; jbool toJbool() const; jint toJint() const; jshort toJshort() const; jlong toJlong() const; jfloat toJfloat() const; jdouble toJdouble() const; jbyte toJbyte() const; static NativeString valueOf(jbool b); static NativeString valueOf(jint i); static NativeString valueOf(jshort s); static NativeString valueOf(jlong l); static NativeString valueOf(jfloat f); static NativeString valueOf(jdouble d); static NativeString valueOf(jbyte b); }; JCPP_EXPORT NativeString operator+(const char* str, const NativeString& other); JCPP_EXPORT NativeString operator+(const wchar_t* wstr, const NativeString& other); JCPP_EXPORT NativeString operator+(const std::string& str, const NativeString& other); JCPP_EXPORT NativeString operator+(const std::wstring& wstr, const NativeString& other); JCPP_EXPORT NativeString operator+(const jbool b, const NativeString& other); JCPP_EXPORT NativeString operator+(const jint i, const NativeString& other); JCPP_EXPORT NativeString operator+(const jshort s, const NativeString& other); JCPP_EXPORT NativeString operator+(const jlong l, const NativeString& other); JCPP_EXPORT NativeString operator+(const jfloat f, const NativeString& other); JCPP_EXPORT NativeString operator+(const jdouble d, const NativeString& other); JCPP_EXPORT NativeString operator+(const jbyte b, const NativeString& other); JCPP_EXPORT jbool operator==(const char* str, const NativeString& other); JCPP_EXPORT jbool operator==(const wchar_t* wstr, const NativeString& other); JCPP_EXPORT jbool operator==(const std::string& str, const NativeString& other); JCPP_EXPORT jbool operator==(const std::wstring& wstr, const NativeString& other); JCPP_EXPORT jbool operator!=(const char* str, const NativeString& other); JCPP_EXPORT jbool operator!=(const wchar_t* wstr, const NativeString& other); JCPP_EXPORT jbool operator!=(const std::string& str, const NativeString& other); JCPP_EXPORT jbool operator!=(const std::wstring& wstr, const NativeString& other); JCPP_EXPORT std::ostream& operator<<(std::ostream& out, const NativeString& str); JCPP_EXPORT std::wostream& operator<<(std::wostream& out, const NativeString& wstr); } } } #endif
[ "mimi4930" ]
mimi4930
2a85eb0c06c9a245af852703235cba0899652423
127c53f4e7e220f44dc82d910a5eed9ae8974997
/Common/Packets/GCTeamAskApply.h
ee2eec81116d706d09e0008e4289738965e56978
[]
no_license
zhangf911/wxsj2
253e16265224b85cc6800176a435deaa219ffc48
c8e5f538c7beeaa945ed2a9b5a9b04edeb12c3bd
refs/heads/master
2020-06-11T16:44:14.179685
2013-03-03T08:47:18
2013-03-03T08:47:18
null
0
0
null
null
null
null
GB18030
C++
false
false
5,149
h
#ifndef _GC_TEAMASKAPPLY_H_ #define _GC_TEAMASKAPPLY_H_ #include "Type.h" #include "Packet.h" #include "PacketFactory.h" namespace Packets { class GCTeamAskApply: public Packet { public: GCTeamAskApply() { m_SourNameSize = 0; m_DestNameSize = 0; memset( (void*)m_SourName, 0, sizeof(CHAR) * MAX_CHARACTER_NAME ); memset( (void*)m_DestName, 0, sizeof(CHAR) * MAX_CHARACTER_NAME ); } virtual ~GCTeamAskApply(){} //公用接口 virtual BOOL Read( SocketInputStream& iStream ); virtual BOOL Write( SocketOutputStream& oStream ) const; virtual UINT Execute( Player* pPlayer ); virtual PacketID_t GetPacketID() const { return PACKET_GC_TEAMASKAPPLY; } virtual UINT GetPacketSize() const { UINT uSize; uSize = sizeof(GUID_t)*2 + sizeof(UCHAR)*3 + sizeof(UINT) + sizeof(SceneID_t) + sizeof(INT); uSize += sizeof(CHAR)*(m_SourNameSize + m_DestNameSize) + sizeof(USHORT) ; if ( m_DetailFlag>0 ) { uSize += sizeof(UINT)*10; } return uSize; } public : VOID SetSourGUID( GUID_t guid ) { m_SourGUID = guid; } GUID_t GetSourGUID( ) { return m_SourGUID; } VOID SetDestGUID( GUID_t guid ){ m_DestGUID = guid; } GUID_t GetDestGUID( ) { return m_DestGUID; } VOID SetSourName( const CHAR* pName ) { strncpy( m_SourName, pName, MAX_CHARACTER_NAME-1 ); m_SourNameSize = (UCHAR)strlen(m_SourName); } const CHAR* GetSourName( ){ return m_SourName; } VOID SetDestName( const CHAR* pName ) { strncpy( m_DestName, pName, MAX_CHARACTER_NAME-1 ); m_DestNameSize = (UCHAR)strlen(m_DestName); } const CHAR* GetDestName( ){ return m_DestName; } VOID SetFamily( UINT family ) { m_uFamily = family; } UINT GetFamily( ) { return m_uFamily; } VOID SetScene( SceneID_t id ){ m_Scene = id; } SceneID_t GetScene( ){ return m_Scene; } VOID SetLevel(INT lvl) { m_Level = lvl; } INT GetLevel() { return m_Level; } VOID SetDetailFlag(INT flag) { m_DetailFlag = flag; } UCHAR GetDetailFlag() { return m_DetailFlag; } VOID SetDataID(USHORT dataid) { m_uDataID = dataid; } USHORT GetDataID() { return m_uDataID; } VOID SetWeaponID(UINT weaponid) { m_WeaponID = weaponid; } UINT GetWeaponID() { return m_WeaponID; } VOID SetAssihandID(UINT AssihandID) { m_AssihandID = AssihandID; } UINT GetAssihandID() { return m_AssihandID; } VOID SetScapularID(UINT ScapularID) { m_ScapularID = ScapularID; } UINT GetScapularID() { return m_ScapularID; } VOID SetCapID(UINT capid) { m_CapID = capid; } UINT GetCapID() { return m_CapID; } VOID SetArmourID(UINT armorid) { m_ArmourID = armorid; } UINT GetArmourID() { return m_ArmourID; } VOID SetCuffID(UINT cuffid) { m_CuffID = cuffid; } UINT GetCuffID() { return m_CuffID; } VOID SetFootID(UINT footid) { m_FootID = footid; } UINT GetFootID() { return m_FootID; } VOID SetFaceModel(UINT uFaceMeshID) { m_uFaceMeshID = uFaceMeshID; } UINT GetFaceModel() const { return m_uFaceMeshID; } VOID SetHairModel(UINT uHairMeshID) { m_uHairMeshID = uHairMeshID; } UINT GetHairModel() const { return m_uHairMeshID; } VOID SetHairColor(UINT uHairColor) { m_uHairColor = uHairColor; } UINT GetHairColor() const { return m_uHairColor; } public : GUID_t m_SourGUID; //申请人 GUID_t m_DestGUID; //被申请人 UCHAR m_SourNameSize; UCHAR m_DestNameSize; CHAR m_SourName[MAX_CHARACTER_NAME]; // 1.申请人名字 CHAR m_DestName[MAX_CHARACTER_NAME]; // 被申请人名字 UINT m_uFamily; // 2.门派 SceneID_t m_Scene; // 3.场景 INT m_Level; // 4.等级 USHORT m_uDataID; // 5.玩家性别 UCHAR m_DetailFlag; // 是否发送详细信息 // 以下是详细信息 UINT m_WeaponID; // 7.主武器 UINT m_AssihandID; // 副武器 UINT m_CapID; // 8.帽子 UINT m_ScapularID; // 肩甲 UINT m_ArmourID; // 9.衣服 UINT m_CuffID; // 10.护腕 UINT m_FootID; // 11.靴子 UINT m_uFaceMeshID; // 12.面部模型 UINT m_uHairMeshID; // 13.头发模型 UINT m_uHairColor; // 14.头发颜色 }; class GCTeamAskApplyFactory: public PacketFactory { public: Packet* CreatePacket() { return new GCTeamAskApply(); } PacketID_t GetPacketID()const { return PACKET_GC_TEAMASKAPPLY; } UINT GetPacketMaxSize()const { return sizeof(GUID_t)*2+ sizeof(UCHAR)*3+ sizeof(CHAR)*MAX_CHARACTER_NAME*2+ sizeof(UINT)*11+ sizeof(SceneID_t)+ sizeof(INT)+ sizeof(USHORT); } }; class GCTeamAskApplyHandler { public: static UINT Execute(GCTeamAskApply* pPacket,Player* pPlayer); }; } using namespace Packets; #endif
df3a18bdda44bc1f7c0c2dcfa2b439d893adeae8
1061ad6b439908c40d42c79076afa5d2539f83aa
/CdS Photoresistor/LM34_Test/LM34_Test.ino
a3ad4be8b32efd281e92e4e41840e5b6e4c21a91
[]
no_license
wstreyer/Arduino
e86252b196e0702d59e0e4d760b4fdf3f8382a97
8f3f24d436b7684ddc9aeac8db18c0507382cee5
refs/heads/master
2020-04-03T04:04:31.557036
2018-10-27T20:04:30
2018-10-27T20:04:30
155,002,288
0
0
null
null
null
null
UTF-8
C++
false
false
488
ino
//LM34 DZ analog pin const int LM34 = A3; //Initialize values to read and display dht11 data int sensorValue = 0; // value read from the pot float outputValue = 0; // value output to the PWM (analog out) void setup() { //Open serial port Serial.begin(9600); } void loop() { //Update after 1 seconds delay(250); //Read LM34 DZ temperature sensorValue = analogRead(LM34); outputValue = map(sensorValue, 0, 1023, 0, 500); Serial.println(outputValue); }
c6053cd903b0df4f257ba22732fe651846fc75f9
8bb16b4bfb077fc4f9bd683ad0aae797213371d7
/SDK/PUBG_QualitySliderWidget_functions.cpp
c05d17217272cb4aa8300698c1f253f46c86ad12
[]
no_license
yuaom/PUBG-SDK-3.7.19.10-
f6582e3c25fe5c0f8c38955f9ad96dc41427f099
e87a6484e75611908c34ed58c933efd914bedb14
refs/heads/master
2023-06-10T02:22:55.546476
2018-03-16T17:05:00
2018-03-16T17:05:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,874
cpp
// PLAYERUNKNOWN BATTLEGROUND'S ( EDITED BY PHYSXCORE, THANKS TO KN4CKER ) (3.7.19.10) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "PUBG_QualitySliderWidget_parameters.hpp" namespace Classes { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function QualitySliderWidget.QualitySliderWidget_C.GetGamePadHelpWidgetClass // (Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // class UClass* GuideClass (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UQualitySliderWidget_C::GetGamePadHelpWidgetClass(class UClass** GuideClass) { static auto fn = UObject::GetObjectCasted<UFunction>(86455); UQualitySliderWidget_C_GetGamePadHelpWidgetClass_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (GuideClass != nullptr) *GuideClass = params.GuideClass; } // Function QualitySliderWidget.QualitySliderWidget_C.OnKeyDown // (BlueprintCosmetic, Event, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (Parm, IsPlainOldData) // struct FKeyEvent* InKeyEvent (Parm) // struct FEventReply ReturnValue (Parm, OutParm, ReturnParm) struct FEventReply UQualitySliderWidget_C::OnKeyDown(struct FGeometry* MyGeometry, struct FKeyEvent* InKeyEvent) { static auto fn = UObject::GetObjectCasted<UFunction>(86449); UQualitySliderWidget_C_OnKeyDown_Params params; params.MyGeometry = MyGeometry; params.InKeyEvent = InKeyEvent; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function QualitySliderWidget.QualitySliderWidget_C.OnKeyUp // (BlueprintCosmetic, Event, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (Parm, IsPlainOldData) // struct FKeyEvent* InKeyEvent (Parm) // struct FEventReply ReturnValue (Parm, OutParm, ReturnParm) struct FEventReply UQualitySliderWidget_C::OnKeyUp(struct FGeometry* MyGeometry, struct FKeyEvent* InKeyEvent) { static auto fn = UObject::GetObjectCasted<UFunction>(86444); UQualitySliderWidget_C_OnKeyUp_Params params; params.MyGeometry = MyGeometry; params.InKeyEvent = InKeyEvent; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function QualitySliderWidget.QualitySliderWidget_C.ProcessKeyDown // (Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // struct FKey Key (Parm) // struct FEventReply Reply (Parm, OutParm) void UQualitySliderWidget_C::ProcessKeyDown(const struct FKey& Key, struct FEventReply* Reply) { static auto fn = UObject::GetObjectCasted<UFunction>(86425); UQualitySliderWidget_C_ProcessKeyDown_Params params; params.Key = Key; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Reply != nullptr) *Reply = params.Reply; } // Function QualitySliderWidget.QualitySliderWidget_C.OnPrepass_1 // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // class UWidget* BoundWidget (Parm, ZeroConstructor, IsPlainOldData) void UQualitySliderWidget_C::OnPrepass_1(class UWidget* BoundWidget) { static auto fn = UObject::GetObjectCasted<UFunction>(86416); UQualitySliderWidget_C_OnPrepass_1_Params params; params.BoundWidget = BoundWidget; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function QualitySliderWidget.QualitySliderWidget_C.GetValueText // (Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UQualitySliderWidget_C::GetValueText() { static auto fn = UObject::GetObjectCasted<UFunction>(86411); UQualitySliderWidget_C_GetValueText_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function QualitySliderWidget.QualitySliderWidget_C.SetValue // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // float Value (Parm, ZeroConstructor, IsPlainOldData) void UQualitySliderWidget_C::SetValue(float Value) { static auto fn = UObject::GetObjectCasted<UFunction>(86408); UQualitySliderWidget_C_SetValue_Params params; params.Value = Value; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function QualitySliderWidget.QualitySliderWidget_C.GetQualityName // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText UQualitySliderWidget_C::GetQualityName() { static auto fn = UObject::GetObjectCasted<UFunction>(86406); UQualitySliderWidget_C_GetQualityName_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function QualitySliderWidget.QualitySliderWidget_C.GetValueByRange // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure, Const) // Parameters: // float Value (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UQualitySliderWidget_C::GetValueByRange(float* Value) { static auto fn = UObject::GetObjectCasted<UFunction>(86402); UQualitySliderWidget_C_GetValueByRange_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Value != nullptr) *Value = params.Value; } // Function QualitySliderWidget.QualitySliderWidget_C.BndEvt__Button_2_K2Node_ComponentBoundEvent_370_OnButtonClickedEvent__DelegateSignature // (BlueprintEvent) void UQualitySliderWidget_C::BndEvt__Button_2_K2Node_ComponentBoundEvent_370_OnButtonClickedEvent__DelegateSignature() { static auto fn = UObject::GetObjectCasted<UFunction>(86401); UQualitySliderWidget_C_BndEvt__Button_2_K2Node_ComponentBoundEvent_370_OnButtonClickedEvent__DelegateSignature_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function QualitySliderWidget.QualitySliderWidget_C.BndEvt__RightButotn_K2Node_ComponentBoundEvent_395_OnButtonClickedEvent__DelegateSignature // (BlueprintEvent) void UQualitySliderWidget_C::BndEvt__RightButotn_K2Node_ComponentBoundEvent_395_OnButtonClickedEvent__DelegateSignature() { static auto fn = UObject::GetObjectCasted<UFunction>(86400); UQualitySliderWidget_C_BndEvt__RightButotn_K2Node_ComponentBoundEvent_395_OnButtonClickedEvent__DelegateSignature_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function QualitySliderWidget.QualitySliderWidget_C.BndEvt__EditableText_2_K2Node_ComponentBoundEvent_82_OnEditableTextChangedEvent__DelegateSignature // (HasOutParms, BlueprintEvent) // Parameters: // struct FText Text (ConstParm, Parm, OutParm, ReferenceParm) void UQualitySliderWidget_C::BndEvt__EditableText_2_K2Node_ComponentBoundEvent_82_OnEditableTextChangedEvent__DelegateSignature(const struct FText& Text) { static auto fn = UObject::GetObjectCasted<UFunction>(86398); UQualitySliderWidget_C_BndEvt__EditableText_2_K2Node_ComponentBoundEvent_82_OnEditableTextChangedEvent__DelegateSignature_Params params; params.Text = Text; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function QualitySliderWidget.QualitySliderWidget_C.ExecuteUbergraph_QualitySliderWidget // (HasDefaults) // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UQualitySliderWidget_C::ExecuteUbergraph_QualitySliderWidget(int EntryPoint) { static auto fn = UObject::GetObjectCasted<UFunction>(86383); UQualitySliderWidget_C_ExecuteUbergraph_QualitySliderWidget_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
54b0af4b3b7c19c04905f6ec773feb8784123bfc
1bcad704ae63cc40942453e3d5c20eb9634734e0
/LocalGENSIM/Pythia/ADDonly.cc
e8478e30aa97aac42638df36ccb707e441019600
[]
no_license
uzzielperez/CMSAlabama
0128550eb72b0378d28fee1aeaf230a15a457efe
145480bf39f80a00c175292c658b38b75a44941b
refs/heads/master
2021-09-13T20:03:36.437519
2018-05-03T17:01:57
2018-05-03T17:01:57
119,589,397
0
0
null
null
null
null
UTF-8
C++
false
false
1,635
cc
// Copyright (C) 2017 Torbjorn Sjostrand. // PYTHIA is licenced under the GNU GPL version 2, see COPYING for details. // Please respect the MCnet Guidelines, see GUIDELINES for details. // http://home.thep.lu.se/~torbjorn/pythia8/worksheet8153.pdf #include "Pythia8/Pythia.h" using namespace Pythia8; int main() { // Generator. Process selection. Tevatron initialization. Histogram. Pythia pythia; // Beam Parameter Settings pythia.readString("Beams:idA = 2212"); //proton pythia.readString("Beams:idB = 2212"); //proton pythia.readString("Beams:eCM = 13000."); //CM energy of collision // Settings for the Process Generation pythia.readString("ExtraDimensionsLED:ffbar2gammagamma = on"); pythia.readString("ExtraDimensionsLED:gg2gammagamma = on"); pythia.readString("PhaseSpace:pTHatMin = 70."); // LED parameters pythia.readString("ExtraDimensionsLED:MD = 3000"); // Fundamental scale of gravity, same order as Ms pythia.readString("ExtraDimensionsLED:n = 2"); // number of extradimensions, default =2 // Initialize. pythia.init(); // Book histograms. Hist pTG("process pT scale", 100, 1000., 2000.); // Begin event loop. Generate event. Skip if error. List first one. for (int iEvent = 0; iEvent < 1000; ++iEvent) { if (!pythia.next()) continue; // Loop over particles in event.Fill its pT. int iG = 0; for (int i = 0; i < pythia.event.size(); ++i) if (pythia.event[i].id() == 22) iG = i; // gamma ID = 22 pTG.fill( pythia.event[iG].pT() ); // End of event loop. Statistics. Histogram. Done. } pythia.stat(); cout << pTG; return 0; }
c20ddcda7ceabb2fe5477e6acb75957b1147e98e
c05ec6793dc48b2e966f204989a32a65623288f9
/src/opengldrv/oglvertexvbo.cpp
7ed981ad8f5eba9b92165f3d3682d666550b4b46
[]
no_license
pkamenarsky/hastegame
b29741a7f2f38d51ce445f14a3dd4f656e204102
5320863576804e51f799bdeacf29321ed50a0962
refs/heads/master
2021-01-13T02:06:26.613636
2015-08-17T13:18:40
2015-08-17T13:18:40
40,895,961
0
0
null
null
null
null
UTF-8
C++
false
false
12,549
cpp
#include "bufobject.hh" #include "ogldevice.hh" #include "oglvertexvbo.hh" #include "../video/vertexformat.hh" namespace ion { namespace opengldrv { OGLVertexVBO::OGLVertexVBO(OGLDevice& rOGLDevice,const ion_uint32 numVertices, const video::Vertexformat& format,const ion_uint32 flags,video::Vertexstream::Vertexsource *pSource): Vertexstream(format,numVertices,pSource), m_pBuffer(new BufferObject(GL_ARRAY_BUFFER_ARB)),m_rOGLDevice(rOGLDevice),m_IsDataOK(true) { GLenum usage; if (flags& video::Streamflags_Dynamic) { usage=GL_DYNAMIC_DRAW_ARB; } else usage=GL_STATIC_DRAW_ARB; m_pBuffer->bind(); m_pBuffer->create(static_cast<GLsizeiptrARB>(m_Format.stride()*numVertices),0,usage); m_Pointers.m_CurrentVtx=0; m_Pointers.m_pp1DTexcoords=m_pp1DTexcoords; m_Pointers.m_pp2DTexcoords=m_pp2DTexcoords; m_Pointers.m_pp3DTexcoords=m_pp3DTexcoords; } OGLVertexVBO::~OGLVertexVBO() { delete m_pBuffer; } bool OGLVertexVBO::isValid() const { return (m_pBuffer!=0); } bool OGLVertexVBO::isDataOK() const { return m_IsDataOK; } void OGLVertexVBO::dataIsOK() { m_IsDataOK=true; } void *OGLVertexVBO::mappedPointer() { return m_pBuffer->mappedPointer(); } bool OGLVertexVBO::isMapped() const { return m_pBuffer->mappedPointer()!=0; } void OGLVertexVBO::bind() { // IMPORTANT: FIRST bind the vbo, THEN set the pointers! m_pBuffer->bind(); ion_uint8* offset=0; int numtexcoord=0; int texsize=0; bool isNormalEnabled=false,isColorEnabled=false; for (ion_uint32 entrynr=0;entrynr<m_Format.numEntries();++entrynr) { video::VertexFormatEntry vfentry=m_Format.entry(entrynr); texsize=0; switch (vfentry) { case video::VertexFormatEntry_Position: glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3,GL_FLOAT,m_Format.stride(),(const GLvoid*)offset); break; case video::VertexFormatEntry_Normal: glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT,m_Format.stride(),(const GLvoid*)offset); isNormalEnabled=true; break; case video::VertexFormatEntry_Diffuse: glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4,GL_UNSIGNED_BYTE,m_Format.stride(),(const GLvoid*)offset); isColorEnabled=true; break; case video::VertexFormatEntry_Specular:continue; break; case video::VertexFormatEntry_Texcoord1D: texsize=1; case video::VertexFormatEntry_Texcoord2D: if (texsize==0) texsize=2; case video::VertexFormatEntry_Texcoord3D: if (texsize==0) texsize=3; glActiveTextureARB(GL_TEXTURE0_ARB+numtexcoord); glClientActiveTextureARB(GL_TEXTURE0_ARB+numtexcoord); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(texsize,GL_FLOAT,m_Format.stride(),(const GLvoid*)offset); ++numtexcoord; break; case video::VertexFormatEntry_Boneweight:break; // TODO: Support for this } offset+=video::vertexFormatEntrySizeLookup(vfentry); } if (glIsEnabled(GL_NORMAL_ARRAY) && !isNormalEnabled) glDisableClientState(GL_NORMAL_ARRAY); if (glIsEnabled(GL_COLOR_ARRAY) && !isColorEnabled) { glDisableClientState(GL_COLOR_ARRAY); glColor3f(1,1,1); } for (int stagenr=numtexcoord;stagenr!=m_rOGLDevice.caps().m_MaxTextureBlendStages;++stagenr) { glActiveTextureARB(GL_TEXTURE0_ARB+stagenr); glClientActiveTextureARB(GL_TEXTURE0_ARB+stagenr); if (glIsEnabled(GL_TEXTURE_COORD_ARRAY)) { glDisableClientState(GL_TEXTURE_COORD_ARRAY); } } } void OGLVertexVBO::unbind() { int numtexcoord=0; int texsize=0; for (ion_uint32 entrynr=0;entrynr<m_Format.numEntries();++entrynr) { video::VertexFormatEntry vfentry=m_Format.entry(entrynr); texsize=0; switch (vfentry) { case video::VertexFormatEntry_Position: glDisableClientState(GL_VERTEX_ARRAY); break; case video::VertexFormatEntry_Normal: glDisableClientState(GL_NORMAL_ARRAY); break; case video::VertexFormatEntry_Diffuse: glDisableClientState(GL_COLOR_ARRAY); break; case video::VertexFormatEntry_Specular:continue; break; case video::VertexFormatEntry_Texcoord1D: texsize=1; case video::VertexFormatEntry_Texcoord2D: if (texsize==0) texsize=2; case video::VertexFormatEntry_Texcoord3D: if (texsize==0) texsize=3; glActiveTextureARB(GL_TEXTURE0_ARB+numtexcoord); glClientActiveTextureARB(GL_TEXTURE0_ARB+numtexcoord); glDisableClientState(GL_TEXTURE_COORD_ARRAY); ++numtexcoord; break; case video::VertexFormatEntry_Boneweight:break; // TODO: Support for this } } for (int stagenr=numtexcoord;stagenr!=m_rOGLDevice.caps().m_MaxTextureBlendStages;++stagenr) { glActiveTextureARB(GL_TEXTURE0_ARB+stagenr); glClientActiveTextureARB(GL_TEXTURE0_ARB+stagenr); if (glIsEnabled(GL_TEXTURE_COORD_ARRAY)) { glDisableClientState(GL_TEXTURE_COORD_ARRAY); } } m_pBuffer->disableVBO(GL_ARRAY_BUFFER_ARB); } void OGLVertexVBO::map(const ion_uint32 flags) { GLenum access=GL_READ_WRITE_ARB; /* enum Mapflags { Map_Writeonly=1, Map_Readonly=2, Map_Discard=4, Map_Nooverwrite=8 }; @param access Access mode. Valid values:\n \n <b>GL_READ_ONLY_ARB</b>\n Read-only access.\n \n <b>GL_WRITE_ONLY_ARB</b>\n Write-only access.\n \n <b>GL_READ_WRITE_ARB</b>\n Read-write access.\n*/ if (flags&video::Map_Readonly) { access=GL_READ_ONLY_ARB; } else if (flags&video::Map_Writeonly) { access=GL_WRITE_ONLY_ARB; } m_pBuffer->bind(); m_pBuffer->map(access); calculatePointers(m_Pointers); } void OGLVertexVBO::unmap() { m_pBuffer->bind(); m_pBuffer->unmap(); } void OGLVertexVBO::calculatePointers(video::VertexiteratorPointers& vitp) { if ((vitp.m_CurrentVtx>=capacity()) || !isMapped()) return; ion_uint8* pPtr=((ion_uint8*)m_pBuffer->mappedPointer())+m_Format.stride()*vitp.m_CurrentVtx; int numtexcoords[3]={0,0,0}; for (unsigned long entrynr=0;entrynr<m_Format.numEntries();++entrynr) { video::VertexFormatEntry entry=m_Format.entry(entrynr); switch (entry) { case video::VertexFormatEntry_Position:vitp.m_pPosition=(math::Vector3f*)pPtr; break; case video::VertexFormatEntry_Normal:vitp.m_pNormal=(math::Vector3f*)pPtr; break; case video::VertexFormatEntry_Texcoord1D:vitp.m_pp1DTexcoords[numtexcoords[0]++]=(float*)pPtr; break; case video::VertexFormatEntry_Texcoord2D:vitp.m_pp2DTexcoords[numtexcoords[1]++]=(math::Vector2f*)pPtr; break; case video::VertexFormatEntry_Texcoord3D:vitp.m_pp3DTexcoords[numtexcoords[2]++]=(math::Vector3f*)pPtr; break; case video::VertexFormatEntry_Diffuse:vitp.m_pDiffuseColor=(ion_uint32*)pPtr; case video::VertexFormatEntry_Specular:vitp.m_pSpecularColor=(ion_uint32*)pPtr; default:break; } pPtr+=video::vertexFormatEntrySizeLookup(entry); } } const math::Vector3f& OGLVertexVBO::position(const ion_uint32 vtxindex) const { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pPosition)+m_Format.stride()*vtxindex; return *((math::Vector3f*)pPtr); } const math::Vector3f& OGLVertexVBO::normal(const ion_uint32 vtxindex) const { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pNormal)+m_Format.stride()*vtxindex; return *((math::Vector3f*)pPtr); } ion_uint32 OGLVertexVBO::diffuseColor(const ion_uint32 vtxindex) const { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pDiffuseColor)+m_Format.stride()*vtxindex; return *((ion_uint32*)pPtr); } ion_uint32 OGLVertexVBO::specularColor(const ion_uint32 vtxindex) const { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pSpecularColor)+m_Format.stride()*vtxindex; return *((ion_uint32*)pPtr); } float OGLVertexVBO::texcoord1D(const ion_uint32 vtxindex,const ion_uint32 texstage) const { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pp1DTexcoords[texstage])+m_Format.stride()*vtxindex; return *((float*)pPtr); } const math::Vector2f& OGLVertexVBO::texcoord2D(const ion_uint32 vtxindex,const ion_uint32 texstage) const { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pp2DTexcoords[texstage])+m_Format.stride()*vtxindex; return *((math::Vector2f*)pPtr); } const math::Vector3f& OGLVertexVBO::texcoord3D(const ion_uint32 vtxindex,const ion_uint32 texstage) const { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pp3DTexcoords[texstage])+m_Format.stride()*vtxindex; return *((math::Vector3f*)pPtr); } void OGLVertexVBO::position(const ion_uint32 vtxindex,const float x,const float y,const float z) { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pPosition)+m_Format.stride()*vtxindex; /*((math::Vector3f*)pPtr)->x()=x; ((math::Vector3f*)pPtr)->y()=y; ((math::Vector3f*)pPtr)->z()=z;*/ ((float*)pPtr)[0]=x; ((float*)pPtr)[1]=y; ((float*)pPtr)[2]=z; } void OGLVertexVBO::position(const ion_uint32 vtxindex,const math::Vector3f& newPosition) { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pPosition)+m_Format.stride()*vtxindex; /*((math::Vector3f*)pPtr)->x()=newPosition.x(); ((math::Vector3f*)pPtr)->y()=newPosition.y(); ((math::Vector3f*)pPtr)->z()=newPosition.z();*/ ((float*)pPtr)[0]=newPosition.x(); ((float*)pPtr)[1]=newPosition.y(); ((float*)pPtr)[2]=newPosition.z(); } void OGLVertexVBO::normal(const ion_uint32 vtxindex,const float x,const float y,const float z) { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pNormal)+m_Format.stride()*vtxindex; /*((math::Vector3f*)pPtr)->x()=x; ((math::Vector3f*)pPtr)->y()=y; ((math::Vector3f*)pPtr)->z()=z;*/ ((float*)pPtr)[0]=x; ((float*)pPtr)[1]=y; ((float*)pPtr)[2]=z; } void OGLVertexVBO::normal(const ion_uint32 vtxindex,const math::Vector3f& newNormal) { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pNormal)+m_Format.stride()*vtxindex; /*((math::Vector3f*)pPtr)->x()=newNormal.x(); ((math::Vector3f*)pPtr)->y()=newNormal.y(); ((math::Vector3f*)pPtr)->z()=newNormal.z();*/ ((float*)pPtr)[0]=newNormal.x(); ((float*)pPtr)[1]=newNormal.y(); ((float*)pPtr)[2]=newNormal.z(); } void OGLVertexVBO::diffuseColor(const ion_uint32 vtxindex,const ion_uint8 a,const ion_uint8 r,const ion_uint8 g,const ion_uint8 b) { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pDiffuseColor)+m_Format.stride()*vtxindex; *((ion_uint32*)pPtr)=(((ion_uint32)a)<<24)|(((ion_uint32)b)<<16)|(((ion_uint32)g)<<8)|((ion_uint32)r); } void OGLVertexVBO::diffuseColor(const ion_uint32 vtxindex,const ion_uint32 color) { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pDiffuseColor)+m_Format.stride()*vtxindex; // TODO: Correct the RGBA order *((ion_uint32*)pPtr)=color; } void OGLVertexVBO::specularColor(const ion_uint32 vtxindex,const ion_uint8 a,const ion_uint8 r,const ion_uint8 g,const ion_uint8 b) { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pSpecularColor)+m_Format.stride()*vtxindex; *((ion_uint32*)pPtr)=(((ion_uint32)a)<<24)|(((ion_uint32)b)<<16)|(((ion_uint32)g)<<8)|((ion_uint32)r); } void OGLVertexVBO::specularColor(const ion_uint32 vtxindex,const ion_uint32 color) { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pSpecularColor)+m_Format.stride()*vtxindex; // TODO: Correct the RGBA order *((ion_uint32*)pPtr)=color; } void OGLVertexVBO::texcoord1D(const ion_uint32 vtxindex,const ion_uint32 texstage,const float newTexcoord1D) { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pp1DTexcoords[texstage])+m_Format.stride()*vtxindex; *((float*)pPtr)=newTexcoord1D; } void OGLVertexVBO::texcoord2D(const ion_uint32 vtxindex,const ion_uint32 texstage,const float u,const float v) { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pp2DTexcoords[texstage])+m_Format.stride()*vtxindex; ((float*)pPtr)[0]=u; ((float*)pPtr)[1]=v; } void OGLVertexVBO::texcoord2D(const ion_uint32 vtxindex,const ion_uint32 texstage,const math::Vector2f& newTexcoord2D) { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pp2DTexcoords[texstage])+m_Format.stride()*vtxindex; ((float*)pPtr)[0]=newTexcoord2D.x(); ((float*)pPtr)[1]=newTexcoord2D.y(); } void OGLVertexVBO::texcoord3D(const ion_uint32 vtxindex,const ion_uint32 texstage,const float u,const float v,const float w) { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pp3DTexcoords[texstage])+m_Format.stride()*vtxindex; ((float*)pPtr)[0]=u; ((float*)pPtr)[1]=v; ((float*)pPtr)[2]=w; } void OGLVertexVBO::texcoord3D(const ion_uint32 vtxindex,const ion_uint32 texstage,const math::Vector3f& newTexcoord3D) { ion_uint8 *pPtr=(ion_uint8*)(m_Pointers.m_pp3DTexcoords[texstage])+m_Format.stride()*vtxindex; ((float*)pPtr)[0]=newTexcoord3D.x(); ((float*)pPtr)[1]=newTexcoord3D.y(); ((float*)pPtr)[2]=newTexcoord3D.z(); } } }
[ "trevo.palev@2706c42f-771c-0410-b8f5-5191b43d0857" ]
trevo.palev@2706c42f-771c-0410-b8f5-5191b43d0857
204befac9a706ec2ab17b236a8baa626b8237861
f8ea7e042a62404b1f420a7cc84b7c3167191f57
/SimLib/FitEmpirical.cpp
71427dd7a90bd9093f2b1c0cde732ed92e2c9958
[]
no_license
alexbikfalvi/SimNet
0a22d8bd0668e86bf06bfb72d123767f24248b48
20b24e15647db5467a1187f8be5392570023d670
refs/heads/master
2016-09-15T17:50:23.459189
2013-07-05T14:41:18
2013-07-05T14:41:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,260
cpp
/* * Copyright (C) 2011 Alex Bikfalvi * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "Headers.h" #include "FitEmpirical.h" #include "ExceptionArgument.h" namespace SimLib { FitEmpirical::FitEmpirical(double* data, uint size) { for(uint index = 0; index < size; index++) this->Add(data[index]); } FitEmpirical::FitEmpirical(std::vector<double>& data) { for(std::vector<double>::iterator iter = data.begin(); iter != data.end(); iter++) this->Add(*iter); } void FitEmpirical::Clear() { this->data.clear(); while(!this->samples.empty()) this->samples.pop(); } void FitEmpirical::Add(double value) { // Add value to the empirical data set this->data.insert(value); this->samples.push(value); assert(this->data.size() == this->samples.size()); } void FitEmpirical::Remove() { // Remove value from the empirical data set if(!this->samples.empty()) { this->data.erase(this->data.find(this->samples.front())); this->samples.pop(); assert(this->data.size() == this->samples.size()); } } double FitEmpirical::Min() { return this->data.empty() ? std::numeric_limits<double>::quiet_NaN() : *this->data.begin(); } double FitEmpirical::Max() { return this->data.empty() ? std::numeric_limits<double>::quiet_NaN() : *this->data.rbegin(); } double FitEmpirical::Quantile(double prob) { // Calculate the quantile for the specified probability if((prob < 0) || (prob >= 1)) throw ExceptionArgument(__FILE__, __LINE__, "FitEmpirical::Quantile : the probability must be in the interval [0,1) (current value is %lf).", prob); // If the data set is empty, return NaN if(this->data.empty()) { return std::numeric_limits<double>::quiet_NaN(); } // Else, calculate the quantile else { double step = 1.0/this->data.size(); uint index = 0; for(std::multiset<double>::iterator iter = this->data.begin(); iter != this->data.end(); iter++, index++) if((index*step <= prob) && ((index+1.0)*step > prob)) return *iter; // Return the largest value return *this->data.rbegin(); } } std::vector<double>& FitEmpirical::Data() { this->vdata.resize(this->data.size()); uint index = 0; for(std::multiset<double>::iterator iter = this->data.begin(); iter != this->data.end(); iter++, index++) this->vdata[index] = *iter; return this->vdata; } std::vector<double>& FitEmpirical::Cdf() { this->cdf.resize(this->data.size()); for(uint index = 0; index < this->cdf.size(); index++) this->cdf[index] = (double)(index + 1.0) / this->cdf.size(); return this->cdf; } }
1a795407a64b6404fb97114b70c35d5e94fe949b
3f85d90aa33926c9a3fbd61bc95068033965ab17
/Twitter.cpp
84273678cda6e8e8fbe4883c24136c2ae05bc1b2
[]
no_license
falay/MiniTwitter
faafc98ecd10d55cc15cfc97a5c6e6744030fbf7
17dfa44726a52f43102eb09a93457be71bcdd4a1
refs/heads/master
2021-01-12T10:54:22.685550
2016-11-03T13:31:59
2016-11-03T13:31:59
72,748,233
0
0
null
null
null
null
UTF-8
C++
false
false
2,285
cpp
#include "Twitter.hpp" Twitter::Twitter() { CurTime = 0 ; } void Twitter::postTweet(int userId, int tweetId) { Tweet newPost( tweetId, CurTime++ ) ; postedTweets[userId].insert( postedTweets[userId].begin(), newPost ) ; } vector<int> Twitter::getNewsFeed(int userId) { vector<int> newsIndex(friends[userId].size()+1, 0) ; vector<int> newsFeed ; while( newsFeed.size() < 10 && hasArticles(userId, newsIndex) ) newsFeed.push_back( getNextNews( userId, newsIndex ) ) ; return newsFeed ; } int Twitter::getNextNews(int Uid, vector<int>& newsIndex) { int curMaxTime = -1, curMaxIndex = -1, curTid ; for(int i=0; i<newsIndex.size()-1; i++) { if( newsIndex[i] >= postedTweets[friends[Uid][i]].size() ) continue ; Tweet friendsTweet = postedTweets[friends[Uid][i]][newsIndex[i]] ; if( curMaxTime < friendsTweet.timeStamp ) { curMaxTime = friendsTweet.timeStamp ; curMaxIndex = i ; curTid = friendsTweet.tweetID ; } } if( newsIndex.back() < postedTweets[Uid].size() ) { Tweet myTweet = postedTweets[Uid][newsIndex.back()] ; if( curMaxTime < myTweet.timeStamp ) { newsIndex.back() ++ ; return myTweet.tweetID ; } } newsIndex[ curMaxIndex ] ++ ; return curTid ; } bool Twitter::hasArticles(int Uid, vector<int> newsIndex) { for(int i=0; i<newsIndex.size(); i++) { if( i < newsIndex.size() - 1 ) { if( newsIndex[i] < postedTweets[friends[Uid][i]].size() ) return true ; } else { if( newsIndex[i] < postedTweets[Uid].size() ) return true ; } } return false ; } void Twitter::follow(int followerId, int followeeId) { if( followerId == followeeId || find(friends[followerId].begin(), friends[followerId].end(), followeeId) != friends[followerId].end() ) return ; friends[ followerId ].push_back( followeeId ) ; } void Twitter::unfollow(int followerId, int followeeId) { if( followerId == followeeId ) return ; for(int i=0; i<friends[followerId].size(); i++) if( friends[followerId][i] == followeeId ) { friends[followerId].erase( friends[followerId].begin()+i ) ; break ; } }
2e54f73537774211ce4a0a2ee82875073b19cb03
7c5c667d10f01f6cd0e87e6af53a720bd2502bc7
/src/杂/12.29训练/1713ELE.cpp
cda8245ed45a526b298b6f3d4434e16f04e72dd5
[]
no_license
xyiyy/icpc
3306c163a4fdefb190518435c09929194b3aeebc
852c53860759772faa052c32f329149f06078e77
refs/heads/master
2020-04-12T06:15:50.747975
2016-10-25T12:16:57
2016-10-25T12:16:57
40,187,486
5
0
null
null
null
null
UTF-8
C++
false
false
998
cpp
#include<iostream> using namespace std; int vis[30005]; int max_fl; int judge(int t) { int i,j; int num=0; i=t/20+2; while(i<=max_fl) { while(i<=max_fl&&!vis[i]) i++; if(10*num+4*(i-1)>t) return 0; j=(t-10*num+20*i+4)/24; i=(t-10*num+16*j+4)/20+1; num++; } return 1; } int main() { int n,fl; while(cin>>n,n) { max_fl=0; for(int i=0;i<30005;i++) vis[i]=0; while(n--) { cin>>fl; vis[fl]=1; max_fl=max(max_fl,fl); } int low=0,high=20*(max_fl-1); int mid; while(low<=high) { mid=(low+high)>>1; if(judge(mid)) high=mid-1; else low=mid+1; } cout<<low<<endl; } return 0; }
4b2afecb0bb2cd9d968d8d88b0f3f6a5988cecd3
679dd2f9d1fb7cf267bec361ba2a77e5ad234ed3
/cadrantvitesse.cpp
6f855af85338c287a50dcfd3e1a675f487706805
[]
no_license
SahliMaroua15/dashbord
7a877d82a2ca4ca46be4b418277eb876d19ffce9
6511747e1f56969678c81f31fd1a1b5e385b418f
refs/heads/master
2020-11-24T09:25:54.875944
2019-12-14T20:32:32
2019-12-14T20:32:32
228,079,619
0
0
null
null
null
null
UTF-8
C++
false
false
4,413
cpp
#include "cadrantvitesse.h" #include <QGraphicsItem> #include <QObject> #include <QPainter> #include <QStyleOptionGraphicsItem> #include <QRectF> #include <QtMath> #include <QtDebug> #include <QPointF> #include <QDateTime> cadrantvitesse::cadrantvitesse(QGraphicsItem *parent) { vitesse=0; } QRectF cadrantvitesse::boundingRect() const { QRectF rectf(-800,-500,1600,1000); return rectf; } void cadrantvitesse::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { //définition des paramétres : painter->setRenderHint(QPainter::Antialiasing); float pi = 3.14159265359; double xCentre=0.0; double yCentre=0.0; double angStart = 220; double c=cos((angStart-vitesse)*pi/180); double s=sin((angStart-vitesse)*pi/180); double xpos=xCentre+280*c; double ypos=yCentre-280*s; //création aiguille calcul Vitesse {int vitesse =0; QPen pen; pen.setWidth(0.5); pen.setColor("white"); QBrush brushAig(Qt::SolidPattern); brushAig.setColor("#DF0101"); painter->setPen(pen); painter->setBrush(brushAig); QPointF pts[3]= { QPointF(-11*cos((angStart-vitesse-90)*pi/180),11*sin((angStart-vitesse-90)*pi/180)), QPointF(xpos, ypos), QPointF(+11*cos((angStart-vitesse-90)*pi/180),-11*sin((angStart-vitesse-90)*pi/180)) }; painter->drawConvexPolygon(pts, 3);} {QPen pen; pen.setColor("dark"); QBrush brush(Qt::SolidPattern); brush.setColor("dark"); painter->setPen(pen); painter->setBrush(brush); painter->drawEllipse(-140,-140,280,280); } { painter->setFont(QFont("arial", 45, -1,false)); painter->setPen(QPen(QBrush("white") ,45, Qt::SolidLine,Qt::FlatCap)); painter->drawText(-45,20, QString("%1").arg(vitesse)); painter->setFont(QFont("arial", 10, -1,false)); painter->setPen(QPen(QBrush("white") ,10, Qt::SolidLine,Qt::FlatCap)); painter->drawText(30, 40, "km/h");} //création des traits désignants la vitesse {QPen pen; for (int i=0;i<=260;i+=10) { if (i%20==0) { pen.setWidthF(35); painter->setPen(QPen(QBrush("white"), 30, Qt::SolidLine, Qt::FlatCap)); QRect rectTrait(-210,-210,420,420); painter->drawArc(rectTrait,(220-i)*16,19.28*0.8);} if(i%20!=0){ pen.setWidthF(15); pen.setColor("white"); pen.setCapStyle(Qt::FlatCap); pen.setStyle(Qt::SolidLine); painter->setPen(pen); QRect rectTrait(-210,-210,420,420); painter->drawArc(rectTrait,(220-i)*16,19.28*0.8); } }} //création des nombres désignants la vitesse {int j=0; for (float i=220*pi/180; i>-45*pi/180; i-=20*pi/180) { QPen pen; painter->setFont(QFont("georgia", 16, -1,false)); painter->setPen(QPen(QBrush("white") , 10, Qt::SolidLine)); painter->drawText(qCos(i)*255-10,-qSin(i)*255+10,QString("%1").arg(j)); j+=20; } } {painter->setPen(QPen(QColor(0,0,0,0) , 1, Qt::SolidLine,Qt::FlatCap)); painter->setBrush(QColor(0,128,255,15)); painter->drawRect(-80,205,160,80); QRadialGradient radialGrad(QPointF(0, 240), 50); radialGrad.setColorAt(0, QColor(0,204,255)); radialGrad.setColorAt(1, QColor(0, 128, 255)); painter->setPen(QPen(QColor(0,204,255) , 1, Qt::SolidLine,Qt::FlatCap)); painter->setBrush(radialGrad);} {QRect rectHeure(-35,220,200,100); painter->setPen(QPen(QBrush("white"), 5, Qt::SolidLine)); painter->setFont(QFont("georgia ", 15,QFont::Bold, Qt::AlignVCenter)); QString stime = QDateTime::currentDateTime().toString("hh:mm"); painter->drawText(rectHeure,stime); } {QRect rectDate(-45,250,200,100); painter->setPen(QPen(QBrush("white"), 5, Qt::SolidLine)); painter->setFont(QFont("georgia", 15, Qt::AlignVCenter,false)); QString sDate = QDateTime::currentDateTime().toString("dd/MM/yy"); painter->drawText(rectDate,sDate);} }
0789af46dfbbf78dfef99d021fc7c0cddae7018b
b5ebf30dab231afd8e8d6dcda7934d29f88fa292
/label.cpp
8786e58969aa05a0d217d704ea773a4d49ecb225
[]
no_license
eipiplus/graph-compute
01cd45fdf1c4742f7f439b0d7dffc21248547bb3
19a9d1079e80214696b036c130387b947e3cba30
refs/heads/master
2021-01-01T05:12:49.333039
2017-03-09T14:09:44
2017-03-09T14:09:44
59,816,550
0
0
null
null
null
null
UTF-8
C++
false
false
550
cpp
#include"label.h" segment::segment(int p,int n){ path=p; node=n; } Label::~Label(){ delete tp; delete ps; delete hash; delete idx; } Label::Label(Topo* tps){ int vs=tps->getVs(); tp=tps; ps=tp->djikstr(); hash=new vector<int> [ vs*vs ]; idx=new vector<segment> [ vs ]; int src=0,dst=0; Path* tmp; for (int i = 0; i < ps->num ; ++i) { tmp=ps->path + i; src=tmp->road[0]; dst=tmp->getDst(); hash [ src*vs + dst].push_back(i); for (int j = 1; j < tmp->len-1; ++j) { idx[ tmp->road[j] ].push_back(new segment(i,j)); } } }
fdfb5d8a30092b68d318b13d10aa7726abbb5736
bd75df2a6d81b1023b0fd23c3bec2dfa4a1fa8a3
/exercise/BOJ/1011.cpp
0844d3573651cf24a66c838bd988cb512e625c32
[]
no_license
jongwuner/ps-study
596215ed2f3405197eabb4251dbfb3bff1b09352
a3f198dcf2467f1637aa8e1efdce81662d6b62ef
refs/heads/master
2021-07-18T15:54:51.622618
2020-05-10T11:53:11
2020-05-10T11:53:11
156,563,729
0
0
null
null
null
null
UTF-8
C++
false
false
378
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int T; cin >> T; while (T--) { ll A, B, N = 0, add = 0; cin >> A >> B; while (N * (N + 1) < B - A) { N++; } if (N * (N - 1) + N < B - A) { add+=2; } else { add++; } N--; cout << 2*N + add<< "\n"; } return 0; }